node-miio 0.0.0-dev-20250810-f1674d0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/.editorconfig +21 -0
  2. package/.eslintrc +32 -0
  3. package/.github/workflows/build.yml +50 -0
  4. package/.github/workflows/codecov.yml +35 -0
  5. package/.github/workflows/codeql.yml +24 -0
  6. package/.github/workflows/publish-dev-from-main.yml +92 -0
  7. package/.github/workflows/publish-release-to-npm.yml +48 -0
  8. package/CONTRIBUTING.md +104 -0
  9. package/LICENSE.md +20 -0
  10. package/README.md +216 -0
  11. package/cli/commands/configure.js +69 -0
  12. package/cli/commands/control.js +54 -0
  13. package/cli/commands/discover.js +36 -0
  14. package/cli/commands/inspect.js +197 -0
  15. package/cli/commands/protocol/call.js +66 -0
  16. package/cli/commands/protocol/json-dump.js +52 -0
  17. package/cli/commands/protocol/packet.js +29 -0
  18. package/cli/commands/protocol.js +8 -0
  19. package/cli/commands/tokens/update.js +58 -0
  20. package/cli/commands/tokens.js +8 -0
  21. package/cli/device-finder.js +66 -0
  22. package/cli/index.js +9 -0
  23. package/cli/log.js +89 -0
  24. package/docs/advanced-api.md +103 -0
  25. package/docs/devices/README.md +111 -0
  26. package/docs/devices/air-purifier.md +142 -0
  27. package/docs/devices/controller.md +89 -0
  28. package/docs/devices/gateway.md +41 -0
  29. package/docs/devices/humidifier.md +136 -0
  30. package/docs/devices/light.md +141 -0
  31. package/docs/devices/power-outlet.md +56 -0
  32. package/docs/devices/power-plug.md +69 -0
  33. package/docs/devices/power-strip.md +73 -0
  34. package/docs/devices/sensor.md +74 -0
  35. package/docs/devices/vacuum.md +80 -0
  36. package/docs/devices/wall-switch.md +62 -0
  37. package/docs/management.md +109 -0
  38. package/docs/missing-devices.md +48 -0
  39. package/docs/protocol.md +77 -0
  40. package/docs/reporting-issues.md +47 -0
  41. package/example.js +11 -0
  42. package/lib/checkResult.js +13 -0
  43. package/lib/connectToDevice.js +62 -0
  44. package/lib/device.js +290 -0
  45. package/lib/device_info.js +329 -0
  46. package/lib/device_info.test.js +337 -0
  47. package/lib/devices/air-monitor.js +53 -0
  48. package/lib/devices/air-purifier.js +162 -0
  49. package/lib/devices/capabilities/battery-level.js +16 -0
  50. package/lib/devices/capabilities/buzzer.js +78 -0
  51. package/lib/devices/capabilities/changeable-led-brightness.js +48 -0
  52. package/lib/devices/capabilities/colorable.js +14 -0
  53. package/lib/devices/capabilities/dimmable.js +14 -0
  54. package/lib/devices/capabilities/mode.js +13 -0
  55. package/lib/devices/capabilities/power.js +14 -0
  56. package/lib/devices/capabilities/sensor.js +50 -0
  57. package/lib/devices/capabilities/switchable-led.js +49 -0
  58. package/lib/devices/chuangmi.plug.v1.js +61 -0
  59. package/lib/devices/eyecare-lamp2.js +179 -0
  60. package/lib/devices/gateway/86sw1.js +28 -0
  61. package/lib/devices/gateway/86sw2.js +44 -0
  62. package/lib/devices/gateway/ctrl_ln1.js +44 -0
  63. package/lib/devices/gateway/ctrl_ln2.js +53 -0
  64. package/lib/devices/gateway/ctrl_neutral1.js +44 -0
  65. package/lib/devices/gateway/ctrl_neutral2.js +53 -0
  66. package/lib/devices/gateway/cube.js +55 -0
  67. package/lib/devices/gateway/developer-api.js +120 -0
  68. package/lib/devices/gateway/light-channel.js +32 -0
  69. package/lib/devices/gateway/light-mixin.js +71 -0
  70. package/lib/devices/gateway/magnet.js +29 -0
  71. package/lib/devices/gateway/magnet2.js +13 -0
  72. package/lib/devices/gateway/motion.js +27 -0
  73. package/lib/devices/gateway/motion2.js +31 -0
  74. package/lib/devices/gateway/plug.js +45 -0
  75. package/lib/devices/gateway/sensor_ht.js +17 -0
  76. package/lib/devices/gateway/subdevice.js +227 -0
  77. package/lib/devices/gateway/subdevices.js +37 -0
  78. package/lib/devices/gateway/switch.js +29 -0
  79. package/lib/devices/gateway/switch2.js +27 -0
  80. package/lib/devices/gateway/voltage.js +28 -0
  81. package/lib/devices/gateway/weather.js +22 -0
  82. package/lib/devices/gateway.js +244 -0
  83. package/lib/devices/humidifier.js +162 -0
  84. package/lib/devices/mijiavacuum.js +22 -0
  85. package/lib/devices/philips-light-bulb.js +73 -0
  86. package/lib/devices/power-plug.js +26 -0
  87. package/lib/devices/power-strip.js +38 -0
  88. package/lib/devices/vacuum.js +412 -0
  89. package/lib/devices/viomivacuum.js +250 -0
  90. package/lib/devices/yeelight.color.js +6 -0
  91. package/lib/devices/yeelight.js +286 -0
  92. package/lib/devices/yeelight.mono.js +9 -0
  93. package/lib/discovery.js +192 -0
  94. package/lib/index.js +40 -0
  95. package/lib/infoFromHostname.js +24 -0
  96. package/lib/management.js +102 -0
  97. package/lib/models.js +77 -0
  98. package/lib/network.js +234 -0
  99. package/lib/packet.js +191 -0
  100. package/lib/placeholder.js +12 -0
  101. package/lib/safeishJSON.js +14 -0
  102. package/lib/tokens.js +129 -0
  103. package/npm-shrinkwrap.json +853 -0
  104. package/package.json +40 -0
@@ -0,0 +1,109 @@
1
+ # Device management
2
+
3
+ The `miio` command line utility supports many device operations, including
4
+ discovering and configuring devices. It is also the primary tool used for
5
+ managing access to devices by storing tokens of devices.
6
+
7
+ ## Install the command line tool
8
+
9
+ You can install the command line tool with:
10
+
11
+ `npm install -g miio`
12
+
13
+ ## Discovering devices on current network
14
+
15
+ `miio discover`
16
+
17
+ This will list devices that are connected to the same network as your computer.
18
+ Let it run for a while so it has a chance to reach all devices, as it might
19
+ take a minute or two for all devices to answer.
20
+
21
+ The commands outputs each device on this format:
22
+
23
+ ```
24
+ Device ID: 48765421
25
+ Model info: zhimi.airpurifier.m1
26
+ Address: 192.168.100.9
27
+ Token: token-as-hex-here via auto-token
28
+ Support: At least basic
29
+ ```
30
+
31
+ The information output is:
32
+
33
+ * __Device ID__ - the unique identifier of the device, does not change if the device is reset.
34
+ * __Model ID__ - the model id if it could be determined, this indicates what type of device it is
35
+ * __Address__ - the IP that the device has on the network
36
+ * __Token__ - the token of the device or ??? if it could not be automatically determined
37
+
38
+ ### Storing tokens of all discovered devices
39
+
40
+ As future firmware updates might start hiding the token of a device it is a good
41
+ idea to sync the tokens to the local token storage. Use the flag `--sync` to
42
+ enable this:
43
+
44
+ `miio discover --sync`
45
+
46
+ ## Changing the WiFi settings of a device
47
+
48
+ `miio configure id-or-address --ssid network-ssid --passwd network-password`
49
+
50
+ Options:
51
+
52
+ * `--ssid` - the required SSID of the 2.4 GHz WiFi network that the device should connect to
53
+ * `--passwd` - the password of the WiFi network
54
+
55
+ _Warning:_ This command does not verify that the device can actually connect to
56
+ the network. If it can not it will be stuck and will need to be reset.
57
+
58
+ ## Configuring a new device
59
+
60
+ If you have gotten a new device the `--configure` flag can also be used to
61
+ configure this new device without using the Mi Home app.
62
+
63
+ 1. The Mi Home device will create a wireless network, connect your computer to this network. Your device model will be included in the name such as: `zhimi-airpurifier-m1_miapdf91`.
64
+ 2. Run `miio discover` to make sure you can see your device. Make a note of the address (IP) or id.
65
+ 3. Configure the WiFi: `miio id-or-address configure --ssid ssid-of-network --passwd password-of-network`. See above for details about the flags.
66
+ 4. After the device has been configured the token is saved locally and made available to on your current machine. If you don't need the token locally you can also now copy the token and transfer it to where it is needed.
67
+ 5. Reconnect to your regular network.
68
+ 6. _Optional:_ Run `miio discover` again to make sure the device actually connected to the network.
69
+
70
+ If the device does not show up on your main network the problem is probably one of:
71
+
72
+ * Wrong SSID - check that the SSID you gave the `--configure` command is correct.
73
+ * Wrong password - check that the password is correct for the WiFi network.
74
+ * Not a 2.4 GHz network - make sure to use a 2.4 GHz network as 5 GHz networks are not supported.
75
+
76
+ You will need to reset the device to try another connection.
77
+
78
+ ## Resetting a device
79
+
80
+ There is currently no way to do this via the client, see your manual for how to
81
+ do it with your device. It usually involves pressing one or two buttons for
82
+ 5 to 10 seconds. The buttons can either be visible or hidden behind a pinhole.
83
+
84
+ ## Getting the token of a device
85
+
86
+ Some Mi Home devices hide their token and require a reset and reconfiguration
87
+ before the device can be used. If you do not use the Mi Home app, do a
88
+ reset and the follow the section _Configuring a new device_ found above.
89
+
90
+ ### Getting the token when using the Mi Home app
91
+
92
+ 1. Reset your Mi Home device. This will reset the token and remove the device from the Mi Home app - you will need to readd it later. Check the manual of your device to find out how to perform a reset.
93
+ 2. The Mi Home device will create a wireless network, connect your computer to this network. Your device model will be included in the name such as: `zhimi-airpurifier-m1_miapddd8`.
94
+ 3. Run `miio discover --sync` in a terminal window.
95
+ 4. a) If you are using the device on the current machine the token has been saved and is now available locally.<br>b) If you need the token somewhere else copy the token as displayed, add it wherever you need to and store a copy somewhere.
96
+ 5. Press Ctrl+C to stop the discovery.
97
+ 6. Reconnect to your regular wireless network.
98
+ 7. Readd the device in the Mi Home app so that it has access to your regular wireless network.
99
+
100
+ ## Setting the token of a device
101
+
102
+ If you want to update the token of a device use the `tokens update` command:
103
+
104
+ `miio tokens update id-or-address --token token-as-hex`
105
+
106
+ This is mostly used when you configured the device on another computer but want
107
+ to use another computer to have access to the device. Make sure to run the
108
+ `miio` command as the correct user as tokens are stored tied to the current
109
+ user.
@@ -0,0 +1,48 @@
1
+ # Missing devices
2
+
3
+ This library does not yet support all Mi Home devices that speak the
4
+ miIO protocol.
5
+
6
+ ## Can my device be supported?
7
+
8
+ The command line application can help with discovering if a device speaks the
9
+ miIO protocol. Get started by installing the command line application:
10
+
11
+ `npm install -g miio`
12
+
13
+ Run the app in discovery mode to list devices on your network:
14
+
15
+ `miio discover`
16
+
17
+ This will start outputting all of the devices found, with their address,
18
+ identifiers, models and tokens (if found). If your device can be supported it
19
+ will show up in this list. You might need to figure out if the IP of your device
20
+ to be able to find it easily.
21
+
22
+ If the device shows up feel free to open an issue about supporting the device.
23
+ Include this information:
24
+
25
+ * The name of the device model - such Mi Air Purifier or Mi Smart Power Strip 2
26
+ * The model id from the output
27
+ * If the token for the device displayed N/A or a hex value (don't include the hex value)
28
+
29
+ ## Implementing a device
30
+
31
+ If a device can be supported the next step is to figure out what commands the
32
+ device supports. You can help by either forking this repository and
33
+ implementing the device or by opening an issue with information about what
34
+ the device seems to support.
35
+
36
+ In certain cases its possible to find documentation or someone that has already
37
+ done most of the work figuring out what commands a device supports.
38
+
39
+ Most often this involves more advanced steps like packet capturing via a local
40
+ Android emulator. Details about that can be found under [Protocol and commands](protocol.md)
41
+ if you feel up for it.
42
+
43
+ ## Donating devices
44
+
45
+ If you really want a device to be supported it's possible to contact the author
46
+ of this library to discuss donating a device. Be aware that this is not a
47
+ guarantee that this library will support the device as sometimes it might
48
+ not be possible to figure out how to support a device.
@@ -0,0 +1,77 @@
1
+ # Protocol and commands
2
+
3
+ The base protocol is based on documentation provided by OpenMiHome. See https://github.com/OpenMiHome/mihome-binary-protocol for details. This
4
+ protocol defines how packets are sent to and from the devices are structured,
5
+ but does not describe the commands that can be issued to the devices.
6
+
7
+ Currently the best way to figure out what commands a device supports is to
8
+ run a packet capture with Wireshark between the Mi Home app and your device.
9
+ The `miio` command line app can the be used together with JSON export from
10
+ Wireshark to extract messages sent back and forth.
11
+
12
+ First make sure you have installed the `miio` app:
13
+
14
+ `npm install -g miio`
15
+
16
+ ## Creating a capture
17
+
18
+ ### Figure out your device token before starting
19
+
20
+ If you do not have the token of your device yet, run `miio --discover` to list
21
+ devices on your network and their auto-extracted tokens. If the token is not
22
+ found, follow the [instructions to find device tokens](management.md). This needs
23
+ to be done before you start your capture or the capture will be useless as
24
+ resetting the device will generate a new token.
25
+
26
+ ### Running Wireshark and Mi Home
27
+
28
+ If you have knowledge about Wireshark you can run a capture however you like,
29
+ but if you do not the easiest way is to use the method described in the
30
+ readme of [Homey app for Xiaomi Mi Robot Vaccum Cleaner](https://github.com/jghaanstra/com.robot.xiaomi-mi) to capture the
31
+ traffic.
32
+
33
+ ## Analyzing the capture
34
+
35
+ ### Exporting the packets as JSON
36
+
37
+ The first step is to export the capture from Wireshark as a JSON file. You
38
+ should be able to extract a file with all your traffic, but you might want to
39
+ apply a filter in Wireshark to limit the size of the file.
40
+
41
+ A good starting filter is: `udp.dstport == 54321 or udp.srcport == 54321`
42
+
43
+ ### Running the `miio` app
44
+
45
+ To extract messages sent back and forth and dump to your terminal:
46
+
47
+ `miio protocol json-dump path/to/file.json --token tokenAsHex`
48
+
49
+ ### Figuring out the output
50
+
51
+ The output will be filled with output such as this:
52
+
53
+ ```
54
+ -> 192.168.100.7 data={"id":10026,"method":"get_status","params":[]}
55
+ <- 192.168.100.8 data={ "result": [ { "msg_ver": 4, "msg_seq": 238, "state": 6, "battery": 100, "clean_time": 21, "clean_area": 240000, "error_code": 0, "map_present": 1, "in_cleaning": 0, "fan_power": 60, "dnd_enabled": 1 } ], "id": 10026 }
56
+ ```
57
+
58
+ Lines starting with `->` are messages sent to a device and `<-` are messages
59
+ from a device. If the data is `N/A` it was either a handshake or the message
60
+ could not be decoded due to an invalid token.
61
+
62
+ The `method` and `params` property in outgoing messages can be plugged into
63
+ `device.call(method, params)` to perform the same call. Go through and see what
64
+ the Mi Home app calls and how the replies look.
65
+
66
+ ## Testing commands
67
+
68
+ The `miio` command line app can be used to control devices and test things
69
+ when you are implementing or debugging your device.
70
+
71
+ Use the `--control` flag to issue a command:
72
+
73
+ `miio protocol call id-or-address nameOfMethod paramsAsJSON`
74
+
75
+ For example to get a property from the device:
76
+
77
+ `miio protocol call id-or-address get_prop '["temperature","use_time"]'`
@@ -0,0 +1,47 @@
1
+ # Reporting issues
2
+
3
+ Any report of issues within `miio` library is welcome. This includes both
4
+ bugs and feature requests, within the generic part of related to a specific
5
+ device.
6
+
7
+ There are a few things that can help with solving your issue.
8
+
9
+ ## Missing support for a device
10
+
11
+ If your device is unsupported you can check the [list of supported devices](devices/README.md)
12
+ to see if your device is or can be supported. If you do not see it in the list
13
+ or if it is listed as Unknown you can read more about figuring out if your
14
+ [device can be supported](missing-devices.md).
15
+
16
+ ## Something with your device does not work
17
+
18
+ To make debugging an issue with your device easier it helps to include some
19
+ debug information. You will need to have the `miio` command line interface
20
+ installed to get some of this information. You can install it via `npm` in a
21
+ terminal window:
22
+
23
+ `npm install -g miio`
24
+
25
+ The `miio` tool comes with a command for inspecting a device. You will need
26
+ either the device id or address of your device. To use the inspect tool run:
27
+
28
+ `miio inspect id-or-address`
29
+
30
+ This will find the device on your network, connect to it and fetch some debug
31
+ information. Including that information when you open an issue will be of great
32
+ help. You can safely exclude the IP and token of your device and any properties
33
+ that include sensitive information.
34
+
35
+ If you do not know the id or address of your device, try running `miio discover`
36
+ to list all devices on your network.
37
+
38
+ ## Other bugs
39
+
40
+ The more details you can share about a bug the better. If you have a small
41
+ test case including it will be greatly appreciated.
42
+
43
+ ## Feature requests
44
+
45
+ Open an issue and describe the feature you want. If its related to a device
46
+ you can include the same information as described in the section
47
+ "Something with your device does not work".
package/example.js ADDED
@@ -0,0 +1,11 @@
1
+ /* eslint-disable */
2
+
3
+ const miio = require('./lib');
4
+
5
+ // Create a new device over the given address
6
+ miio.device({
7
+ address: 'ipHere',
8
+ }).then(device => {
9
+ console.log('Connected to device');
10
+ console.log(device);
11
+ }).catch(err => console.log('Error occurred:', err));
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ function checkResult(r) {
4
+ //console.log(r)
5
+ // {"result":0,"id":17} = Firmware 3.3.9_003095 (Gen1)
6
+ // {"result":["ok"],"id":11} = Firmware 3.3.9_003194 (Gen1), 3.3.9_001168 (Gen2)
7
+ // {"result":["OK"],"id":11} = Firmware 1.3.0_0752 on Xiaowa E202-02
8
+ if (r !== 0 && r[0] !== 'ok' && r[0] !== 'OK') {
9
+ throw new Error('Could not complete call to device');
10
+ }
11
+ }
12
+
13
+ module.exports = checkResult;
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ const network = require('./network');
4
+
5
+ const Device = require('./device');
6
+ const Placeholder = require('./placeholder');
7
+ const models = require('./models');
8
+
9
+ const Vacuum = require('./devices/vacuum');
10
+ const ViomiVacuum = require('./devices/viomivacuum');
11
+
12
+ module.exports = function(options) {
13
+ let handle = network.ref();
14
+
15
+ // Connecting to a device via IP, ask the network if it knows about it
16
+ return network.findDeviceViaAddress(options)
17
+ .then(device => {
18
+ const deviceHandle = {
19
+ ref: network.ref(),
20
+ api: device
21
+ };
22
+
23
+ // Try to resolve the correct model, otherwise use the generic device
24
+ let d = models[device.model];
25
+
26
+ // Hack to accept any vacuum in the form of 'WORD.vacuum.*'
27
+ if (!d && device.model.match(/^\w+\.vacuum\./)) {
28
+ d = Vacuum;
29
+ if (device.model.startsWith('viomi')) {
30
+ d = ViomiVacuum;
31
+ }
32
+ }
33
+
34
+ if(! d) {
35
+ return new Device(deviceHandle);
36
+ } else {
37
+ return new d(deviceHandle);
38
+ }
39
+ })
40
+ .catch(e => {
41
+ if((e.code === 'missing-token' || e.code === 'connection-failure') && options.withPlaceholder) {
42
+ const deviceHandle = {
43
+ ref: network.ref(),
44
+ api: e.device
45
+ };
46
+
47
+ return new Placeholder(deviceHandle);
48
+ }
49
+
50
+ // Error handling - make sure to always release the handle
51
+ handle.release();
52
+
53
+ e.device = null;
54
+ throw e;
55
+ })
56
+ .then(device => {
57
+ // Make sure to release the handle
58
+ handle.release();
59
+
60
+ return device.init();
61
+ });
62
+ };
package/lib/device.js ADDED
@@ -0,0 +1,290 @@
1
+ 'use strict';
2
+
3
+ const util = require('util');
4
+ const isDeepEqual = require('deep-equal');
5
+ const { Thing, Polling } = require('abstract-things');
6
+
7
+ const DeviceManagement = require('./management');
8
+
9
+ const IDENTITY_MAPPER = (v) => v;
10
+
11
+ module.exports = Thing.type(
12
+ (Parent) =>
13
+ class extends Parent.with(Polling) {
14
+ static get type() {
15
+ return 'miio';
16
+ }
17
+
18
+ static availableAPI(builder) {
19
+ builder
20
+ .action('miioModel')
21
+ .description('Get the model identifier of this device')
22
+ .returns('string')
23
+ .done();
24
+
25
+ builder
26
+ .action('miioProperties')
27
+ .description('Get properties of this device')
28
+ .returns('string')
29
+ .done();
30
+
31
+ builder
32
+ .action('miioCall')
33
+ .description('Execute a raw miio-command to the device')
34
+ .argument('string', false, 'The command to run')
35
+ .argument('array', true, 'Arguments of the command')
36
+ .done();
37
+ }
38
+
39
+ constructor(handle) {
40
+ super();
41
+
42
+ this.handle = handle;
43
+ this.id = 'miio:' + handle.api.id;
44
+ this.miioModel = handle.api.model;
45
+
46
+ this._properties = {};
47
+ this._propertiesToMonitor = [];
48
+ this._propertyDefinitions = {};
49
+ this._reversePropertyDefinitions = {};
50
+
51
+ this.poll = this.poll.bind(this);
52
+ // Set up polling to destroy device if unreachable for 5 minutes
53
+ this.updateMaxPollFailures(10);
54
+
55
+ this.management = new DeviceManagement(this);
56
+ }
57
+
58
+ /**
59
+ * Public API: Call a miio method.
60
+ *
61
+ * @param {*} method
62
+ * @param {*} args
63
+ */
64
+ miioCall(method, args) {
65
+ return this.call(method, args);
66
+ }
67
+
68
+ /**
69
+ * Call a raw method on the device.
70
+ *
71
+ * @param {*} method
72
+ * @param {*} args
73
+ * @param {*} options
74
+ */
75
+ call(method, args, options) {
76
+ return this.handle.api.call(method, args, options).then((res) => {
77
+ if (options && options.refresh) {
78
+ // Special case for loading properties after setting values
79
+ // - delay a bit to make sure the device has time to respond
80
+ return new Promise((resolve) =>
81
+ setTimeout(
82
+ () => {
83
+ const properties = Array.isArray(options.refresh)
84
+ ? options.refresh
85
+ : this._propertiesToMonitor;
86
+
87
+ this._loadProperties(properties)
88
+ .then(() => resolve(res))
89
+ .catch(() => resolve(res));
90
+ },
91
+ (options && options.refreshDelay) || 50
92
+ )
93
+ );
94
+ } else {
95
+ return res;
96
+ }
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Define a property and how the value should be mapped. All defined
102
+ * properties are monitored if #monitor() is called.
103
+ */
104
+ defineProperty(name, def) {
105
+ this._propertiesToMonitor.push(name);
106
+
107
+ if (typeof def === 'function') {
108
+ def = {
109
+ mapper: def,
110
+ };
111
+ } else if (typeof def === 'undefined') {
112
+ def = {
113
+ mapper: IDENTITY_MAPPER,
114
+ };
115
+ }
116
+
117
+ if (!def.mapper) {
118
+ def.mapper = IDENTITY_MAPPER;
119
+ }
120
+
121
+ if (def.name) {
122
+ this._reversePropertyDefinitions[def.name] = name;
123
+ }
124
+ this._propertyDefinitions[name] = def;
125
+ }
126
+
127
+ /**
128
+ * Map and add a property to an object.
129
+ *
130
+ * @param {object} result
131
+ * @param {string} name
132
+ * @param {*} value
133
+ */
134
+ _pushProperty(result, name, value) {
135
+ const def = this._propertyDefinitions[name];
136
+ if (!def) {
137
+ result[name] = value;
138
+ } else if (def.handler) {
139
+ def.handler(result, value);
140
+ } else {
141
+ result[def.name || name] = def.mapper(value);
142
+ }
143
+ }
144
+
145
+ poll(isInitial) {
146
+ // Polling involves simply calling load properties
147
+ return this._loadProperties();
148
+ }
149
+
150
+ _loadProperties(properties) {
151
+ if (typeof properties === 'undefined') {
152
+ properties = this._propertiesToMonitor;
153
+ }
154
+
155
+ if (properties.length === 0) return Promise.resolve();
156
+
157
+ return this.loadProperties(properties).then((values) => {
158
+ Object.keys(values).forEach((key) => {
159
+ this.setProperty(key, values[key]);
160
+ });
161
+ });
162
+ }
163
+
164
+ setProperty(key, value) {
165
+ const oldValue = this._properties[key];
166
+
167
+ if (!isDeepEqual(oldValue, value)) {
168
+ this._properties[key] = value;
169
+ this.debug('Property', key, 'changed from', oldValue, 'to', value);
170
+
171
+ this.propertyUpdated(key, value, oldValue);
172
+ }
173
+ }
174
+
175
+ propertyUpdated(key, value, oldValue) {}
176
+
177
+ setRawProperty(name, value) {
178
+ const def = this._propertyDefinitions[name];
179
+ if (!def) return;
180
+
181
+ if (def.handler) {
182
+ const result = {};
183
+ def.handler(result, value);
184
+ Object.keys(result).forEach((key) => {
185
+ this.setProperty(key, result[key]);
186
+ });
187
+ } else {
188
+ this.setProperty(def.name || name, def.mapper(value));
189
+ }
190
+ }
191
+
192
+ property(key) {
193
+ return this._properties[key];
194
+ }
195
+
196
+ get properties() {
197
+ return Object.assign({}, this._properties);
198
+ }
199
+
200
+ /**
201
+ * Public API to get properties defined by the device.
202
+ */
203
+ miioProperties() {
204
+ return this.properties;
205
+ }
206
+
207
+ /**
208
+ * Get several properties at once.
209
+ *
210
+ * @param {array} props
211
+ */
212
+ getProperties(props) {
213
+ const result = {};
214
+ props.forEach((key) => {
215
+ result[key] = this._properties[key];
216
+ });
217
+ return result;
218
+ }
219
+
220
+ /**
221
+ * Load properties from the device.
222
+ *
223
+ * @param {*} props
224
+ */
225
+ loadProperties(props) {
226
+ // Rewrite property names to device internal ones
227
+ props = props.map(
228
+ (key) => this._reversePropertyDefinitions[key] || key
229
+ );
230
+
231
+ // Call get_prop to map everything
232
+ return this.call('get_prop', props).then((result) => {
233
+ const obj = {};
234
+ for (let i = 0; i < result.length; i++) {
235
+ this._pushProperty(obj, props[i], result[i]);
236
+ }
237
+ return obj;
238
+ });
239
+ }
240
+
241
+ /**
242
+ * Callback for performing destroy tasks for this device.
243
+ */
244
+ destroyCallback() {
245
+ return super.destroyCallback().then(() => {
246
+ // Release the reference to the network
247
+ this.handle.ref.release();
248
+ });
249
+ }
250
+
251
+ [util.inspect.custom](depth, options) {
252
+ if (depth === 0) {
253
+ return (
254
+ options.stylize('MiioDevice', 'special') +
255
+ '[' +
256
+ this.miioModel +
257
+ ']'
258
+ );
259
+ }
260
+
261
+ return (
262
+ options.stylize('MiioDevice', 'special') +
263
+ ' {\n' +
264
+ ' model=' +
265
+ this.miioModel +
266
+ ',\n' +
267
+ ' types=' +
268
+ Array.from(this.metadata.types).join(', ') +
269
+ ',\n' +
270
+ ' capabilities=' +
271
+ Array.from(this.metadata.capabilities).join(', ') +
272
+ '\n}'
273
+ );
274
+ }
275
+
276
+ /**
277
+ * Check that the current result is equal to the string `ok`.
278
+ */
279
+ static checkOk(result) {
280
+ if (
281
+ !result ||
282
+ (typeof result === 'string' && result.toLowerCase() !== 'ok')
283
+ ) {
284
+ throw new Error('Could not perform operation');
285
+ }
286
+
287
+ return null;
288
+ }
289
+ }
290
+ );