├── LICENSE
├── README.md
├── config.json
├── index.js
├── lib
├── mqtt.js
└── utils.js
└── package.json
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # xiaomi-mqtt
2 |
3 | [![NPM version][npm-image]][npm-url]
4 |
5 | [npm-image]: http://img.shields.io/npm/v/xiaomi-mqtt.svg
6 | [npm-url]: https://npmjs.org/package/xiaomi-mqtt
7 |
8 | A Bridge between the Xiaomi Mi Smart Home Gateway and the Mqtt broker.
9 |
10 | Xiaomi-mqtt exchanges data between the xiaomi gateway and the mqtt-broker at a low-level, principally based on the device `sid` (Security Identifier?). The automation and dashboard tasks are implemented at a higher level. [Node-RED](http://nodered.org/) is the perfect tool to use for this purpose.
11 |
12 | ### Installation
13 |
14 | ```sh
15 | sudo npm install -g xiaomi-mqtt
16 | ```
17 |
18 | ### Installation from GitHub
19 |
20 | Clone the source repository directly from GitHub to a local folder:
21 |
22 | ```sh
23 | git clone https://github.com/cflurin/xiaomi-mqtt.git
24 | ```
25 |
26 | Local Installation:
27 |
28 | ```sh
29 | cd xiaomi-mqtt
30 | npm install
31 | ```
32 |
33 | ### Configuration
34 |
35 | Copy the `config.json` file to the `.xiaomi-mqtt` folder inside of your home folder.
36 |
37 | ```sh
38 | mkdir ~/.xiaomi-mqtt
39 | cp config.json ~/.xiaomi-mqtt/
40 | ```
41 | On Linux the full path for your config.json would be `~/.xiaomi-mqtt/config.json`.
42 |
43 | Edit `~/xiaomi-mqtt/config.json` to fit your requirements:
44 |
45 | ```sh
46 | {
47 | "xiaomi": {
48 | "serverPort": 9898,
49 | "multicastAddress": "224.0.0.50",
50 | "multicastPort": 4321,
51 | "password": "FFF..."
52 | },
53 | "mqtt": {
54 | "url": "mqtt://127.0.0.1",
55 | "port": 1883,
56 | "username": "foo",
57 | "password": "bar",
58 | "topic_mode": "short",
59 | "topic_prefix": "xiaomi"
60 | },
61 | "loglevel": "info",
62 | "heartbeatfreq": 6,
63 | "dataFormat": "parsed"
64 | }
65 | ```
66 |
67 | ```sh
68 | "topic_mode": <"short"> | <"full"> | <"both">
69 | ```
70 |
71 | - `short` default
72 | - `full` allow you to do some topic filtering directly on client side.
73 | - `both` 2 topics are sent, `short` and `full`.
74 |
75 | ```sh
76 | "loglevel": <"debug"> | <"info"> | <"warn"> | <"error">
77 | ```
78 |
79 | Replace `127.0.0.1` with the address of your mqtt broker.
80 |
81 | Set `dataFormat` to `raw` to get data without parsing.
82 |
83 | By default the gateway send heartbeat every 10s which can do some pollution when testing/debug, the counter parameter in config named `heartbeatfreq` avoid this, in the example above set to 6 means only send a MQTT message each 6 heartbeat, so each 60s. Note this apply only to gateway heartbeat not the device's one.
84 |
85 | ### Usage (global installation)
86 |
87 | Use `xiaomi-mqtt` or `xm` to run xiaomi-mqtt.
88 | Use `ctrl c` to stop xiaomi-mqtt.
89 |
90 | ### Usage (local installation)
91 |
92 | In the `xiaomi-mqtt` folder.
93 |
94 | Use `npm start` to run xiaomi-mqtt.
95 | Use `ctrl c` to stop xiaomi-mqtt.
96 |
97 | #
98 | # mqtt API
99 |
100 | If the configuration option `topic_mode` is set to `short` or `both`, the data (payload) is sent/received in a JSON format using following topics:
101 |
102 | * xiaomi/from
103 | * xiaomi/to/read
104 | * xiaomi/to/write
105 | * xiaomi/to/get_id_list
106 |
107 | **Note**: Have look at: [How to benefit of the full topic option](https://github.com/cflurin/xiaomi-mqtt/wiki/How-to-benefit-of-the-full-topic-option)
108 |
109 |
110 | ## Howto examples
111 |
112 |
113 | At start and stop xiaomi-mqtt sends following messages.
114 |
115 | ### start
116 |
117 | ```sh
118 | topic: xiaomi/from
119 | payload: {"cmd":"xm","msg":"xiaomi-mqtt started."}
120 | ```
121 | and
122 |
123 | ```sh
124 | topic: xiaomi/from
125 | payload:
126 | {
127 | "cmd":"get_id_list_ack",
128 | "sid":"fff...",
129 | "data":["158d00017118ac","158d0001a2eb66","158d0001f35b90","158d0001e52516"]
130 | }
131 | ```
132 |
133 | ### stop
134 |
135 | ```sh
136 | topic: xiaomi/from
137 | payload: {"cmd":"xm","msg":"xiaomi-mqtt stopped."}
138 | ```
139 |
140 | ### heartbeat
141 |
142 | **gateway**
143 |
144 | ```sh
145 | topic: xiaomi/from
146 | payload:
147 | {
148 | "cmd": "heartbeat",
149 | "model": "gateway",
150 | "sid": "fff...",
151 | "short_id": "0",
152 | "token": "v4GeGCO9TBpTUlVy",
153 | "data": {
154 | "ip": "127.0.0.1"
155 | }
156 | }
157 | ```
158 |
159 | **cube**
160 |
161 | ```sh
162 | topic: xiaomi/from
163 | payload:
164 | {
165 | "cmd": "heartbeat",
166 | "model": "cube",
167 | "sid": "158d0003102db5",
168 | "short_id": 46605,
169 | "data": {
170 | "voltage": 2985
171 | }
172 | }
173 | ```
174 |
175 | ### reporting
176 |
177 | Xiaomi-mqtt sends periodically or on events device reports.
178 |
179 | **gateway**
180 |
181 | ```sh
182 | topic: xiaomi/from
183 | payload:
184 |
185 | {
186 | "cmd": "report",
187 | "model": "gateway",
188 | "sid": "fff...",
189 | "short_id": 0,
190 | "data": {
191 | "rgb": 0,
192 | "illumination": 1292
193 | }
194 | }
195 | ```
196 |
197 | **sensor_ht**
198 |
199 | ```sh
200 | topic: xiaomi/from
201 | payload:
202 | {
203 | "cmd":"report",
204 | "model":"sensor_ht",
205 | "sid":"158d0001a2eb66",
206 | "short_id":30124,
207 | "data":{"voltage":3005,"temperature":16.7,"humidity":null}
208 | }
209 | ```
210 |
211 | ```sh
212 | "data": {"voltage":3005,"temperature":16.7,"humidity":null}
213 | or
214 | "data": {"voltage":3005,"temperature":null,"humidity":51.7}
215 | ```
216 |
217 | **magnet**
218 |
219 | ```sh
220 | topic: xiaomi/from
221 | payload:
222 | {
223 | "cmd": "report",
224 | "model": "magnet",
225 | "sid": "158d0001f3651f",
226 | "short_id": 57029,
227 | "data": {
228 | "status": "close"
229 | }
230 | }
231 | ```
232 |
233 | ```sh
234 | "status": "close", "open"
235 | ```
236 |
237 | **switch**
238 |
239 | ```sh
240 | topic: xiaomi/from
241 | payload:
242 | {
243 | "cmd":"report",
244 | "model":"switch",
245 | "sid":"158d0001f35b90",
246 | "short_id":46517,
247 | "data":{"status":"click"}
248 | }
249 | ```
250 |
251 | ```sh
252 | "status": "click", "double_click", "long_click_press", "long_click_release"
253 | ```
254 |
255 | **86sw2**
256 |
257 | ```sh
258 | topic: xiaomi/from
259 | payload:
260 | {
261 | "cmd":"report",
262 | "model":"86sw2",
263 | "sid":"158d0001f55b88",
264 | "short_id":33911,
265 | "data":{"channel_0":"click"}
266 | }
267 | ```
268 |
269 | ```sh
270 | "data":{"channel_0":"click"}
271 | or
272 | "data":{"channel_1":"click"}
273 | ```
274 |
275 | **cube**
276 |
277 | ```sh
278 | topic: xiaomi/from
279 | payload:
280 | {
281 | "cmd":"report",
282 | "model":"cube",
283 | "sid":"158d0003102db5",
284 | "short_id":46605,
285 | "data":{"status":"move"}
286 | }
287 | ```
288 |
289 | ```sh
290 | "status": "move", "flip90", "flip180", "tape_twice", "shake_air", "alert"
291 | or
292 | "rotate": "99,999", "-99.999"
293 | ```
294 |
295 | ### read
296 |
297 | **gateway**
298 |
299 | ```sh
300 | topic: xiaomi/to/read
301 | payload: {"sid":"fff..."}
302 | ```
303 |
304 | response
305 |
306 | ```sh
307 | topic: xiaomi/from
308 | payload:
309 | {
310 | "cmd":"read_ack",
311 | "model":"gateway",
312 | "sid":"fff...",
313 | "short_id":0,
314 | "data":{"rgb":0,"illumination":1292,"proto_version":"1.0.9"}
315 | }
316 | ```
317 |
318 | **sensor_ht**
319 |
320 | ```sh
321 | topic: xiaomi/to/read
322 | payload: {"sid":"158d00017118ac"}
323 | ```
324 |
325 | response
326 |
327 | ```sh
328 | topic: xiaomi/from
329 | payload:
330 | {
331 | "cmd":"read_ack",
332 | "model":"sensor_ht",
333 | "sid":"158d00017118ac",
334 | "short_id":48290,
335 | "data":{"voltage":2985,"temperature":19,"humidity":46.3}
336 | }
337 | ```
338 |
339 | **switch**
340 |
341 | ```sh
342 | topic: xiaomi/to/read
343 | payload: {"sid":"158d0001f35b90"}
344 | ```
345 |
346 | response
347 |
348 | ```sh
349 | topic: xiaomi/from
350 | payload:
351 | {
352 | "cmd":"read_ack",
353 | "model":"switch",
354 | "sid":"158d0001f35b90",
355 | "short_id":46517,
356 | "data":{"voltage":3112}
357 | }
358 | ```
359 | ### write
360 |
361 | ```sh
362 | topic: xiaomi/to/write
363 | payload:
364 | {
365 | "cmd": "write",
366 | "model": "gateway",
367 | "sid": "fff...",
368 | "data": {
369 | "rgb": "1000FF00"
370 | }
371 | }
372 | ```
373 | **Note:** rgb = [brightness] [red] [green] [blue] - each hex 00 to FF
374 |
375 | response
376 |
377 | ```sh
378 | topic: xiaomi/from
379 | payload:
380 | {
381 | "cmd":"write_ack",
382 | "model":"gateway",
383 | "sid":"fff...",
384 | "short_id":0,
385 | "data":{"rgb":268500736,"illumination":1292,"proto_version":"1.0.9"}
386 | }
387 | ```
388 |
389 | ### get_id_list:
390 |
391 | ```sh
392 | topic: xiaomi/to/get_id_list
393 | payload: {"sid":"fff..."}
394 | ```
395 | **Note:** sid = gateway sid.
396 |
397 | response
398 |
399 | ```sh
400 | topic: xiaomi/from
401 | payload:
402 | {
403 | "cmd":"get_id_list_ack",
404 | "sid":"fff...",
405 | "data":["158d00017118ac","158d0001a2eb66","158d0001f35b90","158d0001e52516"]
406 | }
407 | ```
408 |
409 | ## Tested devices (models):
410 |
411 | * gateway
412 | * sensor_ht
413 | * motion
414 | * sensor_motion.aq2
415 | * sensor_wleak.aq1
416 | * magnet
417 | * switch
418 | * 86sw1
419 | * 86sw2
420 | * cube
421 | * ctrl_neutral1
422 | * ctrl_neutral2
423 | * ctrl_ln1.aq1
424 | * smoke
425 |
426 | **Note:** Untested devices using the same format will also send a payload.
427 |
428 | #
429 | # Node-RED examples
430 |
431 | ### basic
432 |
433 | 
434 |
435 | ### write gateway
436 |
437 | 
438 |
439 | Flow:
440 |
441 | ```sh
442 | [{"id":"9339669d.8e38b8","type":"mqtt out","z":"d0877ed4.9e0cc","name":"","topic":"xiaomi/to/write","qos":"","retain":"","broker":"325f5be5.555734","x":560,"y":480,"wires":[]},{"id":"c508a302.61467","type":"ui_colour_picker","z":"d0877ed4.9e0cc","name":"","label":"gateway color","group":"4d5fcade.c527d4","format":"hex","outformat":"string","showSwatch":true,"showPicker":false,"showValue":true,"showAlpha":false,"showLightness":true,"dynOutput":"false","order":0,"width":0,"height":0,"passthru":true,"topic":"","x":220,"y":480,"wires":[["dcd9ac95.fd93"]]},{"id":"dcd9ac95.fd93","type":"template","z":"d0877ed4.9e0cc","name":"map","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{\n \"cmd\": \"write\",\n \"model\": \"gateway\",\n \"sid\": \"fff...\",\n \"data\": {\n \"rgb\": \"10{{payload}}\"\n }\n}","output":"json","x":390,"y":480,"wires":[["9339669d.8e38b8"]]},{"id":"325f5be5.555734","type":"mqtt-broker","z":"","broker":"127.0.0.1","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willPayload":"","birthTopic":"","birthQos":"0","birthPayload":""},{"id":"4d5fcade.c527d4","type":"ui_group","z":"","name":"Xiaomi","tab":"f3d46e49.beaec","order":1,"disp":true,"width":"6"},{"id":"f3d46e49.beaec","type":"ui_tab","z":"","name":"Main","icon":"dashboard","order":1}]
443 | ```
444 |
445 | 
446 |
447 | Flow:
448 |
449 | ```sh
450 | [{"id":"aacbdba0.0519f8","type":"inject","z":"d0877ed4.9e0cc","name":"doorbell","topic":"","payload":"{\"cmd\":\"write\",\"model\":\"gateway\",\"sid\":\"fff...\",\"short_id\":0,\"key\":\"8\",\"data\":{\"mid\":10}}","payloadType":"json","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":120,"y":580,"wires":[["83a2b4f.eb0d748"]]},{"id":"8f56c43e.16c048","type":"inject","z":"d0877ed4.9e0cc","name":"police","topic":"","payload":"{\"cmd\":\"write\",\"model\":\"gateway\",\"sid\":\"fff...\",\"short_id\":0,\"key\":\"8\",\"data\":{\"mid\":1}}","payloadType":"json","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":110,"y":620,"wires":[["83a2b4f.eb0d748"]]},{"id":"83a2b4f.eb0d748","type":"mqtt out","z":"d0877ed4.9e0cc","name":"","topic":"xiaomi/to/write","qos":"","retain":"","broker":"325f5be5.555734","x":340,"y":580,"wires":[]},{"id":"325f5be5.555734","type":"mqtt-broker","z":"","broker":"192.168.0.35","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willPayload":"","birthTopic":"","birthQos":"0","birthPayload":""}]
451 | ```
452 |
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "xiaomi": {
3 | "serverPort": 9898,
4 | "multicastAddress": "224.0.0.50",
5 | "multicastPort": 4321,
6 | "password": "FFF..."
7 | },
8 | "mqtt": {
9 | "url": "mqtt://127.0.0.1",
10 | "port": 1883,
11 | "username": "foo",
12 | "password": "bar",
13 | "topic_mode": "short"
14 | },
15 | "loglevel": "info"
16 | }
17 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | 'use strict';
3 |
4 | var dgram = require('dgram');
5 | var Mqtt = require('./lib/mqtt.js').Mqtt;
6 | var Utils = require('./lib/utils.js').Utils;
7 | var log = require('loglevel');
8 | const crypto = require('crypto');
9 |
10 | var sidAddress = {};
11 | var sidPort = {};
12 | var token = {};
13 | var payload = {};
14 | var gateway_sid; // todo: multliple gateway
15 |
16 | const IV = Buffer.from([0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58, 0x56, 0x2e]);
17 | const package_name = Utils.read_packageName();
18 | const package_version = Utils.read_packageVersion();
19 | const config = Utils.loadConfig("config.json");
20 |
21 | var serverPort = config.xiaomi.serverPort || 9898;
22 | var multicastAddress = config.xiaomi.multicastAddress || '224.0.0.50';
23 | var multicastPort = config.xiaomi.multicastPort || 4321;
24 | var password = config.xiaomi.password || "";
25 | var level = config.loglevel || "info";
26 | var heartbeatfreq = config.heartbeatfreq || 1;
27 | var dataFormat = config.dataFormat || "parsed"
28 | global.hb_count = heartbeatfreq;
29 |
30 | Utils.setlogPrefix(log);
31 | log.setLevel(level);
32 |
33 | log.info("Start "+package_name+", version "+package_version);
34 | log.trace("config " + JSON.stringify(config, null, 2));
35 |
36 | var params = {
37 | "config": config,
38 | "package_name": package_name,
39 | "get_id_list": get_id_list,
40 | "read": read,
41 | "write": write,
42 | "log": log
43 | }
44 |
45 | var mqtt = new Mqtt(params);
46 | mqtt.connect();
47 |
48 | const server = dgram.createSocket('udp4');
49 | server.bind(serverPort);
50 |
51 | sendWhois();
52 |
53 | server.on('listening', function() {
54 | var address = server.address();
55 | log.info("Start a UDP server, listening on port "+address.port);
56 | server.addMembership(multicastAddress);
57 | })
58 |
59 | server.on('message', function(buffer, rinfo) {
60 | var msg;
61 |
62 | try {
63 | msg = JSON.parse(buffer);
64 | log.trace("msg "+JSON.stringify(msg));
65 | } catch (err) {
66 | log.error("invalid message: "+buffer);
67 | return;
68 | }
69 |
70 | switch (msg.cmd) {
71 | case "iam":
72 | log.trace("msg "+JSON.stringify(msg));
73 | var sid = msg.sid;
74 | sidAddress[sid] = msg.ip;
75 | sidPort[sid] = msg.port;
76 | gateway_sid = msg.sid;
77 | log.info("Gateway sid "+msg.sid+" Address "+sidAddress[sid]+", Port "+sidPort[sid]);
78 | get_id_list(sid);
79 | break;
80 | case "get_id_list_ack":
81 | var data = JSON.parse(msg.data);
82 | var sid;
83 | for(var index in data) {
84 | sid = data[index];
85 | sidAddress[sid] = rinfo.address;
86 | sidPort[sid] = rinfo.port;
87 | }
88 | log.trace(JSON.stringify(sidAddress)+ " "+JSON.stringify(sidPort))
89 | payload = {"cmd":msg.cmd, "sid":msg.sid, "data":JSON.parse(msg.data)};
90 | log.debug(JSON.stringify(payload));
91 | mqtt.publish(payload);
92 | break;
93 | case "read_ack":
94 | case "report":
95 | var data = JSON.parse(msg.data);
96 | switch (msg.model) {
97 | case "sensor_ht":
98 | if (dataFormat === "parsed") {
99 | data.temperature = data.temperature ? data.temperature / 100 : null;
100 | data.humidity = data.humidity ? data.humidity / 100: null;
101 | }
102 | payload = {"cmd":msg.cmd ,"model":msg.model, "sid":msg.sid, "short_id":msg.short_id, "data": data};
103 | log.debug(JSON.stringify(payload));
104 | break;
105 | case "gateway":
106 | case "motion":
107 | case "sensor_motion.aq2":
108 | case "sensor_wleak.aq1":
109 | case "magnet":
110 | case "switch":
111 | case "86sw1":
112 | case "86sw2":
113 | case "cube":
114 | case "ctrl_neutral1":
115 | case "ctrl_neutral2":
116 | case "ctrl_ln1.aq1":
117 | case "smoke":
118 | payload = {"cmd":msg.cmd ,"model":msg.model, "sid":msg.sid, "short_id":msg.short_id, "data": data};
119 | log.debug(JSON.stringify(payload));
120 | break;
121 | default:
122 | payload = {"cmd":msg.cmd ,"model":msg.model, "sid":msg.sid, "short_id":msg.short_id, "data": data};
123 | log.debug("untested "+JSON.stringify(payload));
124 | }
125 | mqtt.publish(payload);
126 | break;
127 | case "write_ack":
128 | var data = JSON.parse(msg.data);
129 | payload = {"cmd":msg.cmd ,"model":msg.model, "sid":msg.sid, "short_id":msg.short_id, "data": data};
130 | log.debug(JSON.stringify(payload));
131 | mqtt.publish(payload);
132 | break;
133 | case "heartbeat":
134 | var data = JSON.parse(msg.data);
135 | if (msg.model === "gateway") {
136 | token[msg.sid] = msg.token;
137 | if (hb_count > 0) {
138 | hb_count = hb_count - 1;
139 | //log.info("heartbeat not published, "+hb_count+" before next publish");
140 | } else {
141 | // reset counter, if this is done, it's time to publish this one
142 | hb_count = heartbeatfreq;
143 | }
144 | }
145 | payload = {"cmd":msg.cmd ,"model":msg.model, "sid":msg.sid, "short_id":msg.short_id, "token":msg.token, "data": data};
146 | if (msg.model !== "gateway" || hb_count===heartbeatfreq ) {
147 | mqtt.publish(payload);
148 | }
149 | break;
150 | default:
151 | log.warn("unknown msg "+JSON.stringify(msg)+" from client "+rinfo.address+":"+rinfo.port);
152 | }
153 | });
154 |
155 | // https://nodejs.org/api/errors.html
156 | server.on('error', function(err) {
157 | log.error("server.on('error') "+err.message);
158 | if (err.message.includes("EADDRINUSE")) {
159 | log.info("use 'lsof -i -P' to check for ports used.");
160 | }
161 | log.trace(err.stack);
162 | try {
163 | server.close();
164 | } catch(err) {
165 | log.error("server.close() "+err.message);
166 | log.trace(err.stack);
167 | process.exit(2);
168 | }
169 | });
170 |
171 | function sendWhois() {
172 | var msg = '{"cmd": "whois"}';
173 | log.trace("Send "+msg+" to a multicast address "+multicastAddress+":"+multicastPort);
174 | server.send(msg, 0, msg.length, multicastPort, multicastAddress);
175 | }
176 |
177 | function get_id_list(sid) {
178 | var msg = '{"cmd":"get_id_list"}';
179 | log.trace("Send "+msg+" to "+sidAddress[sid]+":"+sidPort[sid]);
180 | server.send(msg, 0, msg.length, sidPort[sid], sidAddress[sid]);
181 | }
182 |
183 | function read(sid) {
184 | if (sid in sidPort) {
185 | var msg = '{"cmd":"read", "sid":"' + sid + '"}';
186 | log.trace("Send "+msg+" to "+sidAddress[sid]+":"+sidPort[sid]);
187 | server.send(msg, 0, msg.length, sidPort[sid], sidAddress[sid]);
188 | } else {
189 | payload = {"cmd":"xm","msg":"sid >"+sid+"< unknown."};
190 | log.warn(JSON.stringify(payload));
191 | mqtt.publish(payload);
192 | }
193 | }
194 |
195 | function write(mqtt_payload) {
196 |
197 | var msg;
198 | payload = mqtt_payload;
199 | var sid = payload.sid;
200 |
201 | if (sid in sidPort) {
202 | try {
203 | var cipher = crypto.createCipheriv('aes-128-cbc', password, IV);
204 | } catch (e) {
205 | payload = {"cmd":"xm","msg":"Cipher "+JSON.stringify(cipher)+", check the password in config.json."};
206 | log.error(JSON.stringify(payload));
207 | mqtt.publish(payload);
208 | return;
209 | }
210 |
211 | if (token[gateway_sid]) {
212 | var key = cipher.update(token[gateway_sid], 'ascii', 'hex');
213 | payload.data.key = key;
214 | switch (payload.model) {
215 | case "gateway":
216 | if ("rgb" in payload.data) {
217 | payload.data.rgb = Utils.rgb_buf(payload.data.rgb);
218 | }
219 | break;
220 | default:
221 | // nothing
222 | }
223 | msg = JSON.stringify(payload);
224 | log.debug(msg);
225 | server.send(msg, 0, msg.length, sidPort[sid], sidAddress[sid]);
226 | } else {
227 | payload = {"cmd":"xm","msg":"gateway token unknown."};
228 | log.warn(JSON.stringify(payload));
229 | mqtt.publish(payload);
230 | }
231 | } else {
232 | payload = {"cmd":"xm","msg":"sid >"+sid+"< unknown."};
233 | log.warn(JSON.stringify(payload));
234 | mqtt.publish(payload);
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/lib/mqtt.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var mqtt = require('mqtt');
4 | var Utils = require('./utils.js').Utils;
5 |
6 | var topic_from, topic_mode, topic_to;
7 |
8 | var config, package_name;
9 | var get_id_list, read, write, log;
10 |
11 | var client;
12 |
13 | module.exports = {
14 | Mqtt: Mqtt
15 | }
16 |
17 | function Mqtt(params) {
18 |
19 | config = params.config;
20 | package_name = params.package_name;
21 | get_id_list = params.get_id_list;
22 | read = params.read;
23 | write = params.write;
24 | log = params.log;
25 |
26 | log.trace("config " + JSON.stringify(config, null, 2));
27 | }
28 |
29 | Mqtt.prototype.connect = function() {
30 |
31 | var options = {}
32 | var url = config.mqtt.url;
33 |
34 | var topic_prefix = config.mqtt.topic_prefix || "xiaomi";
35 | topic_mode = config.mqtt.topic_mode || "short";
36 | topic_from = topic_prefix + '/from';
37 | topic_to = topic_prefix + '/to';
38 |
39 | options.username = config.mqtt.username || null;
40 | options.password = config.mqtt.password || null;
41 | options.port = config.mqtt.port || 1883;
42 |
43 | options.clientId = package_name+"_"+Math.random().toString(16).substr(2, 8);
44 | log.info("clientId = " + options.clientId);
45 |
46 | client = mqtt.connect(url, options);
47 |
48 | var signals = { 'SIGINT': 2, 'SIGTERM': 15 };
49 | Object.keys(signals).forEach(function (signal) {
50 | process.on(signal, function () {
51 | log.info("Got " + signal + " closing mqtt connection.");
52 | this.end();
53 | }.bind(this));
54 | }.bind(this));
55 |
56 | var timeout = setTimeout(function() {
57 | if (!client.connected) {
58 | log.error("Mqtt connect error! url = "+url+":"+options.port);
59 | }
60 | }, 5000);
61 |
62 | client.on('connect', function () {
63 |
64 | log.info("Mqtt connected, url = "+url+":"+options.port);
65 |
66 | client.subscribe(topic_to+"/#");
67 | log.info("Mqtt subscribe " + topic_to+"/#");
68 |
69 | var payload = {"cmd":"xm" ,"msg":"xiaomi-mqtt started."};
70 | client.publish(topic_from, JSON.stringify(payload));
71 | });
72 |
73 | client.on('message', function (topic, buffer) {
74 |
75 | var payload = buffer.toString();
76 | var msg;
77 |
78 | try {
79 | payload = JSON.parse(payload);
80 | log.trace("Mqtt to " + payload);
81 | } catch(e) {
82 | msg = "invalid JSON format >"+payload+"<";
83 | payload = {"cmd":"xm" ,"msg":msg};
84 | log.warn(msg);
85 | client.publish(topic_from, JSON.stringify(payload));
86 | return;
87 | }
88 |
89 | switch(topic) {
90 | case topic_to+"/read":
91 | read(payload.sid);
92 | break;
93 | case topic_to+"/get_id_list":
94 | get_id_list(payload.sid);
95 | break;
96 | case topic_to+"/write":
97 | write(payload);
98 | break;
99 | default:
100 | log.warn("Mqtt topic unknown.");
101 | }
102 | });
103 |
104 | client.on('close', function() {
105 | log.info(package_name+"-client closed, shutting down.");
106 | process.exit();
107 | });
108 |
109 | }
110 |
111 | Mqtt.prototype.end = function() {
112 | var payload = {"cmd":"xm" ,"msg":"xiaomi-mqtt stopped."};
113 | client.publish(topic_from, JSON.stringify(payload));
114 | client.end();
115 | }
116 |
117 | Mqtt.prototype.publish = function(payload) {
118 |
119 | if (topic_mode == 'short' || topic_mode == 'both') {
120 | client.publish(topic_from, JSON.stringify(payload));
121 | }
122 | if (topic_mode == 'full' || topic_mode == 'both') {
123 | if (payload.sid && payload.cmd && payload.model) {
124 | var ft = topic_from +'/'+ payload.sid +'/'+ payload.cmd +'/'+ payload.model;
125 | if (payload.data.status) {
126 | client.publish(ft +'/status', JSON.stringify(payload));
127 | } else {
128 | client.publish(ft, JSON.stringify(payload));
129 | }
130 | } else {
131 | // Legacy if we send nothing
132 | if (topic_mode == 'full' ) {
133 | client.publish(topic_from, JSON.stringify(payload));
134 | }
135 | }
136 | }
137 | log.trace("Mqtt from " + JSON.stringify(payload));
138 | }
139 |
--------------------------------------------------------------------------------
/lib/utils.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var path = require('path');
4 | var fs = require('fs');
5 | var os = require('os');
6 | const prefix = require('loglevel-plugin-prefix');
7 | const chalk = require('chalk');
8 |
9 | var package_json = "../package.json";
10 | var package_version, github_version, npm_version;
11 |
12 | module.exports = {
13 | Utils: Utils
14 | }
15 |
16 | function Utils() {
17 | }
18 |
19 | Utils.loadConfig = function(config_name) {
20 |
21 | var config_path = path.join(os.homedir(), ".xiaomi-mqtt");
22 | config_path = path.join(config_path, config_name);
23 |
24 | // Complain and exit if config_name doesn't exist yet
25 | if (!fs.existsSync(config_path)) {
26 | console.log("Couldn't find a %s file at %s.", config_name, config_path);
27 | process.exit(1);
28 | }
29 |
30 | // Load up the configuration file
31 | var config;
32 | try {
33 | //console.log("Utils.loadConfig");
34 | config = JSON.parse(fs.readFileSync(config_path));
35 | }
36 | catch (err) {
37 | console.log("There was a problem reading your %s file.", config_name);
38 | console.log("Please try pasting your %s file here to validate it: http://jsonlint.com", config_name);
39 | console.log("");
40 | throw err;
41 | }
42 | return config;
43 | }
44 |
45 | Utils.rgb_buf = function (rgb) {
46 | var bri = parseInt("0x"+rgb.substr(0,2));
47 | var r = parseInt("0x"+rgb.substr(2,2));
48 | var g = parseInt("0x"+rgb.substr(4,2));
49 | var b = parseInt("0x"+rgb.substr(6,2));
50 |
51 | var buf = Buffer.alloc(4);
52 | buf.writeUInt8(bri, 0);
53 | buf.writeUInt8(r, 1);
54 | buf.writeUInt8(g, 2);
55 | buf.writeUInt8(b, 3);
56 |
57 | return buf.readUInt32BE(0);
58 | }
59 |
60 | Utils.setlogPrefix = function(log) {
61 | const colors = {
62 | TRACE: chalk.magentaBright,
63 | DEBUG: chalk.cyanBright,
64 | INFO: chalk.whiteBright,
65 | WARN: chalk.yellowBright,
66 | ERROR: chalk.redBright,
67 | };
68 |
69 | prefix.reg(log);
70 |
71 | prefix.apply(log, {
72 | format(level, name, timestamp) {
73 | //return `${chalk.white(`[${timestamp}]`)} ${colors[level.toUpperCase()](level)} ${chalk.green(`${name}`)}`;
74 | return `${chalk.white(`[${timestamp}]`)} ${colors[level.toUpperCase()](level)}`;
75 | },
76 | });
77 | }
78 |
79 | Utils.log = function(msg) {
80 | var date = new Date();
81 | var msg = "[" + date.toLocaleString() + "]" + " " + msg;
82 |
83 | console.log(msg);
84 | }
85 |
86 | Utils.get_npmVersion = function(pkg) {
87 | // Update version for the next call
88 | this.read_npmVersion(pkg, function(version) {
89 | npm_version = version;
90 | });
91 | return npm_version;
92 | }
93 |
94 | Utils.read_packageVersion = function() {
95 |
96 | var packageJSONPath = path.join(__dirname, package_json);
97 | var packageJSON = JSON.parse(fs.readFileSync(packageJSONPath));
98 | package_version = packageJSON.version;
99 | return package_version;
100 | }
101 |
102 | Utils.read_packageName = function() {
103 |
104 | var packageJSONPath = path.join(__dirname, package_json);
105 | var packageJSON = JSON.parse(fs.readFileSync(packageJSONPath));
106 | return packageJSON.name;
107 | }
108 |
109 | Utils.read_npmVersion = function(pck, callback) {
110 | var exec = require('child_process').exec;
111 | var cmd = 'npm view '+pck+' version';
112 | exec(cmd, function(error, stdout, stderr) {
113 | npm_version = stdout.trim();
114 | //npm_version = stdout.replace(/(\r\n|\n|\r)/gm,"");
115 | callback(npm_version);
116 | //console.log("npm_version %s", npm_version);
117 | });
118 | }
119 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "xiaomi-mqtt",
3 | "version": "0.5.2",
4 | "description": "Bridge between Xiaomi Mi Smart Home Gateway and Mqtt broker.",
5 | "license": "Apache-2.0",
6 | "main": "index.js",
7 | "scripts": {
8 | "start": "node index.js"
9 | },
10 | "bin": {
11 | "xm": "index.js",
12 | "xiaomi-mqtt": "index.js"
13 | },
14 | "repository": {
15 | "type": "git",
16 | "url": "https://github.com/cflurin/xiaomi-mqtt.git"
17 | },
18 | "keywords": [
19 | "Xiaomi",
20 | "Mqtt",
21 | "Gateway",
22 | "Bridge"
23 | ],
24 | "dependencies": {
25 | "mqtt": ">=2.16.0",
26 | "loglevel": ">=1.6.0",
27 | "loglevel-plugin-prefix": ">=0.8.3",
28 | "chalk": ">=2.3.0"
29 | },
30 | "author": "cflurin",
31 | "license": "ISC",
32 | "bugs": {
33 | "url": "https://github.com/cflurin/xiaomi-mqtt/issues"
34 | },
35 | "homepage": "https://github.com/cflurin/xiaomi-mqtt#readme"
36 | }
37 |
--------------------------------------------------------------------------------