node-miio 0.3.0-beta.2 → 0.3.0-beta.4

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 (253) hide show
  1. package/AGENTS.md +115 -0
  2. package/README.md +41 -2
  3. package/dist/cli/commands/configure.js +60 -0
  4. package/dist/cli/commands/configure.js.map +1 -0
  5. package/dist/cli/commands/control.js +47 -0
  6. package/dist/cli/commands/control.js.map +1 -0
  7. package/dist/cli/commands/discover.js +32 -0
  8. package/dist/cli/commands/discover.js.map +1 -0
  9. package/dist/cli/commands/inspect.js +183 -0
  10. package/dist/cli/commands/inspect.js.map +1 -0
  11. package/dist/cli/commands/miot-spec.js +60 -0
  12. package/dist/cli/commands/miot-spec.js.map +1 -0
  13. package/dist/cli/commands/protocol/call.js +59 -0
  14. package/dist/cli/commands/protocol/call.js.map +1 -0
  15. package/dist/cli/commands/protocol/json-dump.js +56 -0
  16. package/dist/cli/commands/protocol/json-dump.js.map +1 -0
  17. package/dist/cli/commands/protocol/packet.js +30 -0
  18. package/dist/cli/commands/protocol/packet.js.map +1 -0
  19. package/dist/cli/commands/protocol.js +49 -0
  20. package/dist/cli/commands/protocol.js.map +1 -0
  21. package/dist/cli/commands/tokens/update.js +53 -0
  22. package/dist/cli/commands/tokens/update.js.map +1 -0
  23. package/dist/cli/commands/tokens.js +44 -0
  24. package/dist/cli/commands/tokens.js.map +1 -0
  25. package/dist/cli/device-finder.js +72 -0
  26. package/dist/cli/device-finder.js.map +1 -0
  27. package/dist/cli/index.js +64 -0
  28. package/dist/cli/index.js.map +1 -0
  29. package/dist/cli/log.js +69 -0
  30. package/dist/cli/log.js.map +1 -0
  31. package/dist/lib/check_result.js +18 -0
  32. package/dist/lib/check_result.js.map +1 -0
  33. package/dist/lib/connect_to_device.js +123 -0
  34. package/dist/lib/connect_to_device.js.map +1 -0
  35. package/dist/lib/device.js +259 -0
  36. package/dist/lib/device.js.map +1 -0
  37. package/dist/lib/device_info.js +297 -0
  38. package/dist/lib/device_info.js.map +1 -0
  39. package/dist/lib/devices/air-monitor.js +42 -0
  40. package/dist/lib/devices/air-monitor.js.map +1 -0
  41. package/dist/lib/devices/air-purifier.js +144 -0
  42. package/dist/lib/devices/air-purifier.js.map +1 -0
  43. package/dist/lib/devices/capabilities/battery-level.js +13 -0
  44. package/dist/lib/devices/capabilities/battery-level.js.map +1 -0
  45. package/dist/lib/devices/capabilities/buzzer.js +69 -0
  46. package/dist/lib/devices/capabilities/buzzer.js.map +1 -0
  47. package/dist/lib/devices/capabilities/changeable-led-brightness.js +44 -0
  48. package/dist/lib/devices/capabilities/changeable-led-brightness.js.map +1 -0
  49. package/dist/lib/devices/capabilities/colorable.js +14 -0
  50. package/dist/lib/devices/capabilities/colorable.js.map +1 -0
  51. package/dist/lib/devices/capabilities/dimmable.js +14 -0
  52. package/dist/lib/devices/capabilities/dimmable.js.map +1 -0
  53. package/dist/lib/devices/capabilities/mode.js +13 -0
  54. package/dist/lib/devices/capabilities/mode.js.map +1 -0
  55. package/dist/lib/devices/capabilities/power.js +13 -0
  56. package/dist/lib/devices/capabilities/power.js.map +1 -0
  57. package/dist/lib/devices/capabilities/sensor.js +46 -0
  58. package/dist/lib/devices/capabilities/sensor.js.map +1 -0
  59. package/dist/lib/devices/capabilities/switchable-led.js +48 -0
  60. package/dist/lib/devices/capabilities/switchable-led.js.map +1 -0
  61. package/dist/lib/devices/chuangmi.plug.v1.js +47 -0
  62. package/dist/lib/devices/chuangmi.plug.v1.js.map +1 -0
  63. package/dist/lib/devices/eyecare-lamp2.js +151 -0
  64. package/dist/lib/devices/eyecare-lamp2.js.map +1 -0
  65. package/dist/lib/devices/gateway/86sw1.js +20 -0
  66. package/dist/lib/devices/gateway/86sw1.js.map +1 -0
  67. package/dist/lib/devices/gateway/86sw2.js +36 -0
  68. package/dist/lib/devices/gateway/86sw2.js.map +1 -0
  69. package/dist/lib/devices/gateway/ctrl_ln1.js +37 -0
  70. package/dist/lib/devices/gateway/ctrl_ln1.js.map +1 -0
  71. package/dist/lib/devices/gateway/ctrl_ln2.js +45 -0
  72. package/dist/lib/devices/gateway/ctrl_ln2.js.map +1 -0
  73. package/dist/lib/devices/gateway/ctrl_neutral1.js +37 -0
  74. package/dist/lib/devices/gateway/ctrl_neutral1.js.map +1 -0
  75. package/dist/lib/devices/gateway/ctrl_neutral2.js +45 -0
  76. package/dist/lib/devices/gateway/ctrl_neutral2.js.map +1 -0
  77. package/dist/lib/devices/gateway/cube.js +49 -0
  78. package/dist/lib/devices/gateway/cube.js.map +1 -0
  79. package/dist/lib/devices/gateway/developer-api.js +104 -0
  80. package/dist/lib/devices/gateway/developer-api.js.map +1 -0
  81. package/dist/lib/devices/gateway/light-channel.js +24 -0
  82. package/dist/lib/devices/gateway/light-channel.js.map +1 -0
  83. package/dist/lib/devices/gateway/light-mixin.js +59 -0
  84. package/dist/lib/devices/gateway/light-mixin.js.map +1 -0
  85. package/dist/lib/devices/gateway/magnet.js +23 -0
  86. package/dist/lib/devices/gateway/magnet.js.map +1 -0
  87. package/dist/lib/devices/gateway/magnet2.js +9 -0
  88. package/dist/lib/devices/gateway/magnet2.js.map +1 -0
  89. package/dist/lib/devices/gateway/motion.js +21 -0
  90. package/dist/lib/devices/gateway/motion.js.map +1 -0
  91. package/dist/lib/devices/gateway/motion2.js +25 -0
  92. package/dist/lib/devices/gateway/motion2.js.map +1 -0
  93. package/dist/lib/devices/gateway/plug.js +34 -0
  94. package/dist/lib/devices/gateway/plug.js.map +1 -0
  95. package/dist/lib/devices/gateway/sensor_ht.js +13 -0
  96. package/dist/lib/devices/gateway/sensor_ht.js.map +1 -0
  97. package/dist/lib/devices/gateway/subdevice.js +203 -0
  98. package/dist/lib/devices/gateway/subdevice.js.map +1 -0
  99. package/dist/lib/devices/gateway/subdevices.js +33 -0
  100. package/dist/lib/devices/gateway/subdevices.js.map +1 -0
  101. package/dist/lib/devices/gateway/switch.js +24 -0
  102. package/dist/lib/devices/gateway/switch.js.map +1 -0
  103. package/dist/lib/devices/gateway/switch2.js +19 -0
  104. package/dist/lib/devices/gateway/switch2.js.map +1 -0
  105. package/dist/lib/devices/gateway/voltage.js +21 -0
  106. package/dist/lib/devices/gateway/voltage.js.map +1 -0
  107. package/dist/lib/devices/gateway/weather.js +16 -0
  108. package/dist/lib/devices/gateway/weather.js.map +1 -0
  109. package/dist/lib/devices/gateway.js +212 -0
  110. package/dist/lib/devices/gateway.js.map +1 -0
  111. package/dist/lib/devices/humidifier.js +141 -0
  112. package/dist/lib/devices/humidifier.js.map +1 -0
  113. package/dist/lib/devices/philips-light-bulb.js +63 -0
  114. package/dist/lib/devices/philips-light-bulb.js.map +1 -0
  115. package/dist/lib/devices/power-plug.js +22 -0
  116. package/dist/lib/devices/power-plug.js.map +1 -0
  117. package/dist/lib/devices/power-strip.js +27 -0
  118. package/dist/lib/devices/power-strip.js.map +1 -0
  119. package/dist/lib/devices/vacuums/dreamevacuum.js +312 -0
  120. package/dist/lib/devices/vacuums/dreamevacuum.js.map +1 -0
  121. package/dist/lib/devices/vacuums/mijiavacuum.js +21 -0
  122. package/dist/lib/devices/vacuums/mijiavacuum.js.map +1 -0
  123. package/dist/lib/devices/vacuums/miot-vacuum.js +395 -0
  124. package/dist/lib/devices/vacuums/miot-vacuum.js.map +1 -0
  125. package/dist/lib/devices/vacuums/vacuum.js +669 -0
  126. package/dist/lib/devices/vacuums/vacuum.js.map +1 -0
  127. package/dist/lib/devices/vacuums/vacuum_modes.js +171 -0
  128. package/dist/lib/devices/vacuums/vacuum_modes.js.map +1 -0
  129. package/dist/lib/devices/vacuums/viomivacuum.js +222 -0
  130. package/dist/lib/devices/vacuums/viomivacuum.js.map +1 -0
  131. package/dist/lib/devices/yeelight.color.js +5 -0
  132. package/dist/lib/devices/yeelight.color.js.map +1 -0
  133. package/dist/lib/devices/yeelight.js +242 -0
  134. package/dist/lib/devices/yeelight.js.map +1 -0
  135. package/dist/lib/devices/yeelight.mono.js +5 -0
  136. package/dist/lib/devices/yeelight.mono.js.map +1 -0
  137. package/dist/lib/discovery.js +147 -0
  138. package/dist/lib/discovery.js.map +1 -0
  139. package/dist/lib/index.js +89 -0
  140. package/dist/lib/index.js.map +1 -0
  141. package/dist/lib/info_from_hostname.js +27 -0
  142. package/dist/lib/info_from_hostname.js.map +1 -0
  143. package/dist/lib/management.js +101 -0
  144. package/dist/lib/management.js.map +1 -0
  145. package/dist/lib/miio_error.js +23 -0
  146. package/dist/lib/miio_error.js.map +1 -0
  147. package/dist/lib/miot/miot_api.js +73 -0
  148. package/dist/lib/miot/miot_api.js.map +1 -0
  149. package/dist/lib/miot/miot_spec.js +105 -0
  150. package/dist/lib/miot/miot_spec.js.map +1 -0
  151. package/dist/lib/miot/spec_client.js +290 -0
  152. package/dist/lib/miot/spec_client.js.map +1 -0
  153. package/dist/lib/models.js +69 -0
  154. package/dist/lib/models.js.map +1 -0
  155. package/dist/lib/network.js +194 -0
  156. package/dist/lib/network.js.map +1 -0
  157. package/dist/lib/packet.js +177 -0
  158. package/dist/lib/packet.js.map +1 -0
  159. package/dist/lib/placeholder.js +16 -0
  160. package/dist/lib/placeholder.js.map +1 -0
  161. package/dist/lib/protocol.js +3 -0
  162. package/dist/lib/protocol.js.map +1 -0
  163. package/dist/lib/safeish_json.js +22 -0
  164. package/dist/lib/safeish_json.js.map +1 -0
  165. package/dist/lib/tokens.js +30 -0
  166. package/dist/lib/tokens.js.map +1 -0
  167. package/docs/devices/vacuum.md +53 -3
  168. package/example.js +1 -1
  169. package/package.json +49 -16
  170. package/snapshots/vacuum-specs.json.gz +0 -0
  171. package/.editorconfig +0 -26
  172. package/.eslintrc +0 -32
  173. package/.github/release.yml +0 -20
  174. package/.github/workflows/build.yml +0 -50
  175. package/.github/workflows/codecov.yml +0 -35
  176. package/.github/workflows/codeql.yml +0 -24
  177. package/.github/workflows/publish-dev-from-main.yml +0 -92
  178. package/.github/workflows/publish-release-to-npm.yml +0 -45
  179. package/cli/commands/configure.js +0 -69
  180. package/cli/commands/control.js +0 -54
  181. package/cli/commands/discover.js +0 -36
  182. package/cli/commands/inspect.js +0 -197
  183. package/cli/commands/protocol/call.js +0 -66
  184. package/cli/commands/protocol/json-dump.js +0 -52
  185. package/cli/commands/protocol/packet.js +0 -29
  186. package/cli/commands/protocol.js +0 -8
  187. package/cli/commands/tokens/update.js +0 -58
  188. package/cli/commands/tokens.js +0 -8
  189. package/cli/device-finder.js +0 -69
  190. package/cli/index.js +0 -9
  191. package/cli/log.js +0 -89
  192. package/lib/checkResult.js +0 -13
  193. package/lib/connectToDevice.js +0 -66
  194. package/lib/device.js +0 -290
  195. package/lib/device_info.js +0 -329
  196. package/lib/device_info.test.js +0 -337
  197. package/lib/devices/air-monitor.js +0 -53
  198. package/lib/devices/air-purifier.js +0 -162
  199. package/lib/devices/capabilities/battery-level.js +0 -16
  200. package/lib/devices/capabilities/buzzer.js +0 -78
  201. package/lib/devices/capabilities/changeable-led-brightness.js +0 -48
  202. package/lib/devices/capabilities/colorable.js +0 -14
  203. package/lib/devices/capabilities/dimmable.js +0 -14
  204. package/lib/devices/capabilities/mode.js +0 -13
  205. package/lib/devices/capabilities/power.js +0 -14
  206. package/lib/devices/capabilities/sensor.js +0 -50
  207. package/lib/devices/capabilities/switchable-led.js +0 -49
  208. package/lib/devices/chuangmi.plug.v1.js +0 -61
  209. package/lib/devices/eyecare-lamp2.js +0 -179
  210. package/lib/devices/gateway/86sw1.js +0 -28
  211. package/lib/devices/gateway/86sw2.js +0 -44
  212. package/lib/devices/gateway/ctrl_ln1.js +0 -44
  213. package/lib/devices/gateway/ctrl_ln2.js +0 -53
  214. package/lib/devices/gateway/ctrl_neutral1.js +0 -44
  215. package/lib/devices/gateway/ctrl_neutral2.js +0 -53
  216. package/lib/devices/gateway/cube.js +0 -55
  217. package/lib/devices/gateway/developer-api.js +0 -120
  218. package/lib/devices/gateway/light-channel.js +0 -32
  219. package/lib/devices/gateway/light-mixin.js +0 -71
  220. package/lib/devices/gateway/magnet.js +0 -29
  221. package/lib/devices/gateway/magnet2.js +0 -13
  222. package/lib/devices/gateway/motion.js +0 -27
  223. package/lib/devices/gateway/motion2.js +0 -31
  224. package/lib/devices/gateway/plug.js +0 -45
  225. package/lib/devices/gateway/sensor_ht.js +0 -17
  226. package/lib/devices/gateway/subdevice.js +0 -227
  227. package/lib/devices/gateway/subdevices.js +0 -37
  228. package/lib/devices/gateway/switch.js +0 -29
  229. package/lib/devices/gateway/switch2.js +0 -27
  230. package/lib/devices/gateway/voltage.js +0 -28
  231. package/lib/devices/gateway/weather.js +0 -22
  232. package/lib/devices/gateway.js +0 -244
  233. package/lib/devices/humidifier.js +0 -162
  234. package/lib/devices/philips-light-bulb.js +0 -73
  235. package/lib/devices/power-plug.js +0 -26
  236. package/lib/devices/power-strip.js +0 -38
  237. package/lib/devices/vacuums/dreamevacuum.js +0 -350
  238. package/lib/devices/vacuums/mijiavacuum.js +0 -22
  239. package/lib/devices/vacuums/vacuum.js +0 -518
  240. package/lib/devices/vacuums/viomivacuum.js +0 -250
  241. package/lib/devices/yeelight.color.js +0 -6
  242. package/lib/devices/yeelight.js +0 -286
  243. package/lib/devices/yeelight.mono.js +0 -9
  244. package/lib/discovery.js +0 -192
  245. package/lib/index.js +0 -40
  246. package/lib/infoFromHostname.js +0 -24
  247. package/lib/management.js +0 -102
  248. package/lib/models.js +0 -76
  249. package/lib/network.js +0 -234
  250. package/lib/packet.js +0 -191
  251. package/lib/placeholder.js +0 -12
  252. package/lib/safeishJSON.js +0 -14
  253. package/lib/tokens.js +0 -129
package/lib/device.js DELETED
@@ -1,290 +0,0 @@
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
- );
@@ -1,329 +0,0 @@
1
- 'use strict';
2
-
3
- const debug = require('debug');
4
- const Packet = require('./packet');
5
- const safeishJSON = require('./safeishJSON');
6
-
7
- const ERRORS = {
8
- '-5001': (method, args, err) =>
9
- err.message === 'invalid_arg' ? 'Invalid argument' : err.message,
10
- '-5005': (method, args, err) =>
11
- err.message === 'params error' ? 'Invalid argument' : err.message,
12
- '-10000': (method) => 'Method `' + method + '` is not supported',
13
- };
14
-
15
- class DeviceInfo {
16
- constructor(parent, id, address, port) {
17
- this.parent = parent;
18
- this.packet = new Packet();
19
-
20
- this.address = address;
21
- this.port = port;
22
-
23
- // Tracker for all promises associated with this device
24
- this.promises = new Map();
25
- this.lastId = 0;
26
-
27
- this.id = id;
28
- this.debug = id ? debug('thing:miio:' + id) : debug('thing:miio:pending');
29
-
30
- // Get if the token has been manually changed
31
- this.tokenChanged = false;
32
- }
33
-
34
- get token() {
35
- return this.packet.token;
36
- }
37
-
38
- set token(t) {
39
- this.debug('Using manual token:', t.toString('hex'));
40
- this.packet.token = t;
41
- this.tokenChanged = true;
42
- }
43
-
44
- /**
45
- * Enrich this device with detailed information about the model. This will
46
- * simply call miIO.info.
47
- */
48
- async enrich() {
49
- if (!this.id) {
50
- throw new Error('Device has no identifier yet, handshake needed');
51
- }
52
-
53
- if (this.model && !this.tokenChanged && this.packet.token) {
54
- // This device has model info and a valid token
55
- return Promise.resolve();
56
- }
57
-
58
- if (this.packet.token) {
59
- if (this.tokenChanged) {
60
- this.autoToken = false;
61
- } else {
62
- this.autoToken = true;
63
- this.debug('Using automatic token:', this.packet.token.toString('hex'));
64
- }
65
- }
66
-
67
- if (!this.enrichPromise) {
68
- this.enrichPromise = this.call('miIO.info');
69
- }
70
-
71
- try {
72
- const { model } = await this.enrichPromise;
73
- this.model = model;
74
- this.tokenChanged = false;
75
- } catch (err) {
76
- if (err.code === 'missing-token') {
77
- err.device = this;
78
- throw err;
79
- } else if (this.packet.token) {
80
- // Could not call the info method, this might be either a timeout or a token problem
81
- const e = new Error(
82
- 'Could not connect to device, token might be wrong'
83
- );
84
- e.code = 'connection-failure';
85
- e.device = this;
86
- throw e;
87
- } else {
88
- const e = new Error(
89
- 'Could not connect to device, token needs to be specified'
90
- );
91
- e.code = 'missing-token';
92
- e.device = this;
93
- throw e;
94
- }
95
- } finally {
96
- this.enriched = true;
97
- this.enrichPromise = null;
98
- }
99
- }
100
-
101
- onMessage(msg) {
102
- try {
103
- this.packet.raw = msg;
104
- } catch (ex) {
105
- this.debug('<- Unable to parse packet', ex);
106
- return;
107
- }
108
-
109
- let data = this.packet.data;
110
- if (data === null) {
111
- this.debug('<-', 'Handshake reply:', this.packet.checksum);
112
- this.packet.handleHandshakeReply();
113
-
114
- if (this.handshakeResolve) {
115
- this.handshakeResolve();
116
- }
117
- } else {
118
- // Handle null-terminated strings
119
- if (data[data.length - 1] === 0) {
120
- data = data.slice(0, data.length - 1);
121
- }
122
-
123
- // Parse and handle the JSON message
124
- let str = data.toString('utf8');
125
-
126
- // Remove non-printable characters to help with invalid JSON from devices
127
- // eslint-disable-next-line no-control-regex
128
- str = str.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F-\x9F]/g, '');
129
-
130
- this.debug('<- Message: `' + str + '`');
131
- try {
132
- let object = safeishJSON(str);
133
-
134
- const p = this.promises.get(object.id);
135
- if (!p) return;
136
- if (typeof object.result !== 'undefined') {
137
- p.resolve(object.result);
138
- } else {
139
- p.reject(object.error);
140
- }
141
- } catch (ex) {
142
- this.debug('<- Invalid JSON', ex);
143
- }
144
- }
145
- }
146
-
147
- async handshake() {
148
- if (!this.packet.needsHandshake) {
149
- return Promise.resolve(this.token);
150
- }
151
-
152
- // If a handshake is already in progress use it
153
- if (!this.handshakePromise) {
154
- this.handshakePromise = this._sendHandshakePackage();
155
- }
156
-
157
- try {
158
- return await Promise.race([this.handshakePromise, this._setTimeout()]);
159
- } catch (err) {
160
- if (err.code === 'timeout') {
161
- this.debug('<- Handshake timed out');
162
- }
163
- throw err;
164
- } finally {
165
- this.handshakeResolve = null;
166
- this.handshakePromise = null;
167
- }
168
- }
169
-
170
- async _sendHandshakePackage() {
171
- const waitForResponse = this._waitForHandshakeResponse();
172
- // Create and send the handshake data
173
- this.packet.handshake();
174
- await this._sendPacket();
175
- return await waitForResponse;
176
- }
177
-
178
- async _sendPacket() {
179
- return await new Promise((resolve, reject) => {
180
- const data = this.packet.raw;
181
- this.parent.socket.send(
182
- data,
183
- 0,
184
- data.length,
185
- this.port,
186
- this.address,
187
- (err) => (err ? reject(err) : resolve())
188
- );
189
- });
190
- }
191
-
192
- async _waitForHandshakeResponse() {
193
- return await new Promise((resolve, reject) => {
194
- // Handler called when a reply to the handshake is received
195
- this.handshakeResolve = () => {
196
- if (this.id !== this.packet.deviceId) {
197
- // Update the identifier if needed
198
- this.id = this.packet.deviceId;
199
- this.debug = debug('thing:miio:' + this.id);
200
- this.debug('Identifier of device updated');
201
- }
202
-
203
- if (this.packet.token) {
204
- resolve(this.token);
205
- } else {
206
- const err = new Error(
207
- 'Could not connect to device, token needs to be specified'
208
- );
209
- err.code = 'missing-token';
210
- reject(err);
211
- }
212
- };
213
- });
214
- }
215
-
216
- async _setTimeout() {
217
- await new Promise((resolve, reject) =>
218
- setTimeout(() => {
219
- const err = new Error('Could not connect to device, handshake timeout');
220
- err.code = 'timeout';
221
- reject(err);
222
- }, 2000)
223
- );
224
- }
225
-
226
- async call(method, params = [], options = {}) {
227
- const { retries = 5 } = options;
228
- return await this._retryOnTimeout(retries, async (retriesLeft) => {
229
- await this.handshake(); // Ensure the handshake is done
230
-
231
- const request = {
232
- id: this._nextId(retries === retriesLeft), // Assign the identifier
233
- method,
234
- params,
235
- sid: options.sid, // If we have a sub-device set it (used by Lumi Smart Home Gateway)
236
- };
237
-
238
- try {
239
- // Enqueue promise listener to this request ID
240
- const waitForResponse = this._waitForResponse(request.id);
241
-
242
- // Create the JSON and send it
243
- const json = JSON.stringify(request);
244
- this.debug('-> (' + retriesLeft + ')', json);
245
- this.packet.data = Buffer.from(json, 'utf8');
246
- await this._sendPacket();
247
- return await waitForResponse;
248
- } catch (err) {
249
- if (!(err instanceof Error) && typeof err.code !== 'undefined') {
250
- const code = err.code;
251
- const handler = ERRORS[code];
252
- const msg = handler
253
- ? handler(method, params, err)
254
- : err.message || err.toString();
255
-
256
- const newErr = new Error(msg);
257
- newErr.code = code;
258
- throw newErr;
259
- }
260
- throw err;
261
- } finally {
262
- this.promises.delete(request.id);
263
- }
264
- });
265
- }
266
-
267
- async _waitForResponse(requestId) {
268
- return new Promise((resolve, reject) => {
269
- // Store reference to the promise so reply can be received
270
- this.promises.set(requestId, { resolve, reject });
271
- });
272
- }
273
-
274
- /**
275
- * Retries the action defined in `actionPromiseFn` as many times as `retries`,
276
- * only if the action fails due to a timeout.
277
- * @param retries Max number of attempts
278
- * @param actionPromiseFn Method that returns a promise to repeat
279
- * @private
280
- */
281
- async _retryOnTimeout(retries = 5, actionPromiseFn) {
282
- while (retries > 0) {
283
- try {
284
- const result = await Promise.race([
285
- actionPromiseFn(retries),
286
- this._setTimeout(),
287
- ]);
288
- return result;
289
- } catch (err) {
290
- if (err.code !== 'timeout') {
291
- throw err;
292
- }
293
- retries--;
294
- }
295
- }
296
- this.debug('Reached maximum number of retries, giving up');
297
- const maxRetriesError = new Error('Call to device timed out');
298
- maxRetriesError.code = 'timeout';
299
- throw maxRetriesError;
300
- }
301
-
302
- _nextId(isFirstAttempt) {
303
- let id;
304
-
305
- if (isFirstAttempt) {
306
- id = this.lastId + 1;
307
- } else {
308
- /*
309
- * This is a failure, increase the last id. Should
310
- * increase the chances of the new request to
311
- * succeed. Related to issues with the vacuum
312
- * not responding such as described in issue
313
- * https://github.com/aholstenson/miio/issues/94.
314
- */
315
- id = this.lastId + 100;
316
- }
317
-
318
- // Check that the id hasn't rolled over
319
- if (id >= 10000) {
320
- this.lastId = id = 1;
321
- } else {
322
- this.lastId = id;
323
- }
324
-
325
- return id;
326
- }
327
- }
328
-
329
- module.exports = DeviceInfo;