mirror of
https://github.com/lehanspb/tuya-mqtt.git
synced 2025-12-18 16:17:30 +00:00
Compare commits
86 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5b344faeb | ||
|
|
aa80270ba2 | ||
|
|
b29b98911a | ||
|
|
44a5c6adbf | ||
|
|
bda39b03b4 | ||
|
|
48dd1c64b0 | ||
|
|
55014cda3b | ||
|
|
8f8d4fb185 | ||
|
|
91b41be953 | ||
|
|
d61c1f7cee | ||
|
|
51bbd612f2 | ||
|
|
5219c94cd7 | ||
|
|
66541558dd | ||
|
|
535b6edecf | ||
|
|
45a26f84de | ||
|
|
1147b9e8c1 | ||
|
|
1033e129de | ||
|
|
4a0a167863 | ||
|
|
b4942dffa1 | ||
|
|
1abcdb02dc | ||
|
|
ab2d4da5d6 | ||
|
|
748a5cae39 | ||
|
|
271697439c | ||
|
|
8f129617b0 | ||
|
|
60b50c760e | ||
|
|
d5217ce237 | ||
|
|
38d3092af3 | ||
|
|
d75e2189da | ||
|
|
4ff6fc221e | ||
|
|
3705efaaed | ||
|
|
6c72afd8ab | ||
|
|
3605037b69 | ||
|
|
df01beb8fc | ||
|
|
9176b8f85c | ||
|
|
68d8743882 | ||
|
|
99f5358794 | ||
|
|
f598d246cf | ||
|
|
1b33c60226 | ||
|
|
56b87aa27e | ||
|
|
311144a9ed | ||
|
|
77b697f5bb | ||
|
|
1181f66c32 | ||
|
|
d8a24d4e6f | ||
|
|
670a87e9fb | ||
|
|
d3b8b9244f | ||
|
|
3b60f3d4d5 | ||
|
|
390d81c893 | ||
|
|
b0549bf392 | ||
|
|
989834821a | ||
|
|
9944f326c5 | ||
|
|
df08c6fc8a | ||
|
|
d05ac857d8 | ||
|
|
868b0977b0 | ||
|
|
82faeff78e | ||
|
|
89a7bfd04d | ||
|
|
1bc87b513c | ||
|
|
01fd5abcff | ||
|
|
9091398810 | ||
|
|
65a9922a7f | ||
|
|
14fc702041 | ||
|
|
4a605f4536 | ||
|
|
ec8d2c62a5 | ||
|
|
a554cd3f58 | ||
|
|
fb79927020 | ||
|
|
279590eb71 | ||
|
|
6f0e03d3f2 | ||
|
|
c6e88ac08b | ||
|
|
a747e122c6 | ||
|
|
604256709a | ||
|
|
3b72a000c8 | ||
|
|
fa228074b3 | ||
|
|
54745c4f8b | ||
|
|
b5f1f1fd31 | ||
|
|
4ea15db772 | ||
|
|
61433e74a9 | ||
|
|
825b9f97ce | ||
|
|
cfefbabe90 | ||
|
|
59acf6d2a4 | ||
|
|
1485ae0689 | ||
|
|
7a9dde716c | ||
|
|
e9e46a7b77 | ||
|
|
998028fa1c | ||
|
|
18ebcbdd74 | ||
|
|
86e602d6cf | ||
|
|
7637a372f7 | ||
|
|
dd2385f6e2 |
18
.github/ISSUE_TEMPLATE/bug_report.md
vendored
18
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -4,35 +4,37 @@ about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
**!!! Please Read This First !!!**\
|
||||
If you are having difficulty controlling a specific device, please verify that the device works with tuya-cli prior to opening an issue here. If you are unable to control the device via tuya-cli it will not be possible to control it with tuya-mqtt. If the device is working with tuya-cli, please post your working commands and the equivalent commands for tuya-mqtt.
|
||||
|
||||
**Describe the bug**\
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
**To Reproduce**\
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
**Expected behavior**\
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
**Screenshots**\
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
**Desktop (please complete the following information):**\
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
**Smartphone (please complete the following information):**\
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
**Additional context**\
|
||||
Add any other context about the problem here.
|
||||
|
||||
3
.github/ISSUE_TEMPLATE/feature_request.md
vendored
3
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -7,6 +7,9 @@ assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**!!! Please Read This First !!!**\
|
||||
If this feature request is to support a device that currently doesn't work, please verify that the device works with tuya-cli first. If the device cannot be used with tuya-cli, then it won't be possible to add support to tuya-mqtt. If you can query and control your device with tuya-cli, please post the commands and the functions they perform as part of the feature request.
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,6 +1,8 @@
|
||||
devices/
|
||||
old/
|
||||
test/
|
||||
config.json
|
||||
.vscode/
|
||||
.bak
|
||||
|
||||
# Logs
|
||||
logs
|
||||
|
||||
67
CHANGELOG.md
Normal file
67
CHANGELOG.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
||||
|
||||
## [3.0.0]
|
||||
The 3.0.0 release is a major refactor of the project with significant changes from previous version. Only major additions and changes are listed below.
|
||||
### Added
|
||||
- Added templating engine for mapping device DPS value to friendly topics
|
||||
- Added pre-defined template for common devices
|
||||
- Command topics for DPS keys
|
||||
|
||||
### Changed
|
||||
- Configuration for devices is now via devices.conf file (based on output format of 'tuya-cli wizard' command)
|
||||
- Default device presents only raw DPS data
|
||||
- Commands sent only via MQTT messages to command topics
|
||||
- Updates all libraries to latest version
|
||||
|
||||
### Removed
|
||||
- Topic based configuraiton has been removed
|
||||
|
||||
## [2.1.0]
|
||||
### Added
|
||||
- Added ability to update validate communicaton with device and update state topic by issuing { "schema": true } command
|
||||
- Added support for protocol 3.3 either via automatic device discovery or manual specification when using IP address
|
||||
|
||||
### Changed
|
||||
- Can specify "discover" instead of IP address to automatically find device (only works if device on same IP subnet as system running this script). This mode will also automatically detect 3.1 and 3.3 protocol devices
|
||||
- Can manually specific protocol via ver3.1/ver3.3 in topic line after tuya/
|
||||
- Bump Tuyapi version to v5.3.x
|
||||
- Bump MQTT version to v4.x.x
|
||||
- Moved openHAB config to it's own document since many users use this with other tools
|
||||
- Verious other fixes and cleanups
|
||||
|
||||
## [2.0.1]
|
||||
### Added
|
||||
- Added capability to set multiple dps values over MQTT-Command
|
||||
- Custom Set-Function for TuyAPI-Class (added error handling for "index [1] not found" error)
|
||||
|
||||
### Changed
|
||||
- MQTT-Topic no longer requires a device type
|
||||
- Updated TuyAPI to v4.x.x
|
||||
|
||||
### Removed
|
||||
- remove device type from topic
|
||||
|
||||
## [2.0.0]
|
||||
### Added
|
||||
- support for OH MQTT-Binding 2.4
|
||||
- default QoS of 2, if not set through config.json
|
||||
|
||||
### Changed
|
||||
- Updated TuyAPI to v3.x.x
|
||||
- Constant off states after start #11
|
||||
|
||||
### Removed
|
||||
- custom set function for TuyAPI
|
||||
|
||||
## [1.0.0]
|
||||
### Added
|
||||
- Add ability to connect to protected MQTT server
|
||||
- Added seperate configuration file
|
||||
|
||||
### Changed
|
||||
- TuyAPI repository not found
|
||||
|
||||
### Removed
|
||||
323
README.md
323
README.md
@@ -1,169 +1,154 @@
|
||||
# TuyaAPI-MQTT Client
|
||||
MQTT interface for Tuya home automation devices sold under various names.
|
||||
This is a wrapper script for the Project codetheweb/tuyapi. https://github.com/codetheweb/tuyapi
|
||||
|
||||
This project provides an MQTT client for communication with the home automation devices.
|
||||
|
||||
:exclamation: There is a greate Step-By-Step guide from user HolgiHab at openhab community ([Step-By-Step Guide](
|
||||
https://community.openhab.org/t/step-by-step-guide-for-adding-tuya-bulbs-smart-life-to-oh2-using-tuya-mqtt-js-by-agentk/59371)). This guide is not only for light bulbs, but also applies to sockets. :exclamation:
|
||||
|
||||
## Instructions:
|
||||
|
||||
Download this project to your openhab2-script-folder "/etc/openhab2/scripts" and install tuyapi from the same folder that the tuya-mqtt.js is in
|
||||
```
|
||||
cd /etc/openhab2/scripts
|
||||
git clone git@github.com:TheAgentK/tuyaapi_mqtt.git // this project
|
||||
cd tuyaapi_mqtt
|
||||
npm install //downloads codetheweb/tuyapi
|
||||
```
|
||||
|
||||
This involves MIM of the connection. Instructions can be found here: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md
|
||||
|
||||
Create your configuration file:
|
||||
```
|
||||
cp config.json.sample config.json
|
||||
nano config.json // edit the configuration file
|
||||
```
|
||||
|
||||
Start command
|
||||
```
|
||||
node tuya-mqtt.js
|
||||
|
||||
// For debugging purpose
|
||||
DEBUG=* tuya-mqtt.js
|
||||
```
|
||||
|
||||
MQTT Topic
|
||||
```
|
||||
Current device state:
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/state
|
||||
|
||||
Change device state (by topic):
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/<STATE>
|
||||
|
||||
Example:
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/on
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/off
|
||||
|
||||
Change device state (by payload)
|
||||
Use with OpenHAB 2.X MQTT bindings or others where only a single command topic is preferred
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command // State as Payload (on,off)
|
||||
|
||||
Color for lightbulb:
|
||||
|
||||
Example:
|
||||
tuya/lightbulb/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/color // Color as Payload as hexColor
|
||||
|
||||
Read data from device:
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/dps // returns JSON.stringify(dps) values, use with care, does not always contain all dps values
|
||||
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/dps/<tuya-dps-id> // return single dps data value
|
||||
```
|
||||
|
||||
#### Issues
|
||||
There are some reliability issues with tuyapi. Latest changes changed the syntax but still getting error maybe at an even higher rate.
|
||||
|
||||
All questions regarding the TuyaAPI please ask in the project https://github.com/codetheweb/tuyapi .
|
||||
|
||||
|
||||
## Example items for OpenHAB 1.x Bindings (still works with >2.4 but only if legacy 1.x MQTT bindings are enabled)
|
||||
#### simple switch on/off
|
||||
```
|
||||
Switch tuya_kitchen_coffeemachine_mqtt "Steckdose Kaffeemaschine" <socket> (<GROUPS>) ["Switchable"] {
|
||||
mqtt="<[broker:tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/state:state:default:.*],
|
||||
>[broker:tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/on:command:ON:true],
|
||||
>[broker:tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/off:command:OFF:false]"
|
||||
}
|
||||
|
||||
Switch tuya_livingroom_ledstrip_tv "LED Regal" <lightbulb> (<GROUPS>) ["Lighting"] {
|
||||
mqtt="<[broker:tuya/lightbulb/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/state:state:default:.*],
|
||||
>[broker:tuya/lightbulb/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/on:command:ON:true],
|
||||
>[broker:tuya/lightbulb/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/off:command:OFF:false]"
|
||||
}
|
||||
```
|
||||
#### change color of lightbulb
|
||||
```
|
||||
# .items
|
||||
Group gTuyaLivingColor "Tuya color group" <lightbulb>
|
||||
Color tuya_livingroom_colorpicker "Stehlampe farbe" (LivingDining, Wohnzimmer)
|
||||
|
||||
String tuya_livingroom_ledstrip_tv_color "Set color [%s]" (gTuyaLivingColor, LivingDining, Wohnzimmer) {
|
||||
mqtt=">[broker:tuya/lightbulb/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/color:command:*:default]"
|
||||
}
|
||||
|
||||
# .rules
|
||||
import org.openhab.core.library.types.HSBType;
|
||||
|
||||
rule "Set HSB value of item RGBLed to RGB color value"
|
||||
when
|
||||
Item tuya_livingroom_colorpicker received command
|
||||
then
|
||||
var appName = "Colorpicker.livingroom"
|
||||
var color = receivedCommand.toString;
|
||||
|
||||
// get all colors and send it via mqtt if light ist enabled
|
||||
gTuyaLivingColor.members.forEach[ i |
|
||||
var name = i.name;
|
||||
var stateName = name.toString.split("_color").get(0);
|
||||
var stateItem = gTuyaLights.allMembers.filter [ conf | conf.name.contains(stateName.toString) ].head;
|
||||
|
||||
if(stateItem.state == ON){
|
||||
logInfo(appName, name + " change to color: " + color);
|
||||
i.sendCommand(color);
|
||||
Thread::sleep(400);
|
||||
}
|
||||
]
|
||||
end
|
||||
|
||||
```
|
||||
## Example items for OpenHAB 2.4 Bindings
|
||||
#### simple switch on/off
|
||||
|
||||
With OpenHAB 2.X MQTT bindings you can add devices using a generic MQTT Thing via PaperUI or
|
||||
configuration files. For PaperUI simply at the generic MQTT Thing and set the state and
|
||||
command topics as follows:
|
||||
```
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/state
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command
|
||||
```
|
||||
If you prefer using configuration files vs PaperUI, it should look something like this:
|
||||
|
||||
```
|
||||
Bridge mqtt:broker:myUnsecureBroker [ host="192.168.0.42", secure=false ]
|
||||
{
|
||||
Thing mqtt:topic:mything {
|
||||
Channels:
|
||||
Type switch : tuya_kitchen_coffeemachine_mqtt "Steckdose Kaffeemaschine" [ stateTopic="tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/state", commandTopic="tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command" ]
|
||||
}
|
||||
}
|
||||
```
|
||||
For a light with color you would need a separate channel with the command topic set to
|
||||
tuya/<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/color and link that to your
|
||||
color item.
|
||||
|
||||
#### Basic UI sitemap
|
||||
```
|
||||
Switch item=tuya_kitchen_coffeemachine_mqtt mappings=[ON="On", OFF="Off"]
|
||||
Switch item=tuya_livingroom_ledstrip_tv mappings=[ON="On", OFF="Off"]
|
||||
|
||||
|
||||
# Colorpicker for Lightbulbs
|
||||
Colorpicker item=tuya_livingroom_colorpicker label="RGB Lampenfarbe" icon="slider" sendFrequency=30000
|
||||
```
|
||||
|
||||
## Contributors
|
||||
- [TheAgentK](https://github.com/TheAgentK)
|
||||
- [tsightler](https://github.com/tsightler)
|
||||
- [Tycale](https://github.com/Tycale)
|
||||
- [crashdummymch](https://github.com/crashdummymch)
|
||||
|
||||
|
||||
## Related Projects:
|
||||
- https://github.com/codetheweb/tuyapi
|
||||
- https://github.com/unparagoned/njsTuya
|
||||
- https://github.com/clach04/python-tuya
|
||||
- https://github.com/Marcus-L/m4rcus.TuyaCore
|
||||
- Specs: https://docs.tuya.com/en/cloudapi/cloud_access.html
|
||||
|
||||
[](https://forthebadge.com)
|
||||
[](https://forthebadge.com)
|
||||
# tuya-mqtt
|
||||
This project provides a method for locally controlling IOT devices manufactured by Tuya Inc., and sold under many different brands, via MQTT.
|
||||
|
||||
Using this script requires obtaining the device ID and local keys for each of your devices after they are configured via the Tuya/Smart Life or other Tuya compatible app (there are many). With this information it is possible to communicate locally with Tuya devices using Tuya protocol version 3.1 and 3.3 without using the Tuya Cloud service, however, getting the keys requires signing up for a Tuya IOT developer account or using one of several other alternative methods (such as dumping the memory of a Tuya based app running on Android).
|
||||
|
||||
To acquire keys for your device please see the instructions at the TuyAPI project (on which this script is based) available at the [TuyAPI GitHub site](https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md).
|
||||
|
||||
**Acquiring device keys is outside the scope of this project!** Issues opened regarding acquiring keys will likely be closed without comment. Please verify that your device can be queried and controlled via tuya-cli before opening any issue. If your device can't be controlled by tuya-cli then it cannot be used with this project.
|
||||
|
||||
**!!!!!!!!!! Important information regarding the 3.0 release !!!!!!!!!!**\
|
||||
The 3.0.0 release (Oct 17th, 2020) is a major refactor of the tuya-mqtt project and, as such, is a breaking release for all users of previous versions. Almost everything about the project is different, including configuration method, topic names, etc. Upgrading users should carefully read the instructions below and assume they are starting over from scratch.
|
||||
|
||||
## Installation
|
||||
Download this project to your system into any directory (example below uses /opt/tuya-mqtt) and install tuyapi from the same folder that the tuya-mqtt.js is in
|
||||
```
|
||||
// switch to opt directory
|
||||
cd /opt
|
||||
|
||||
// clone this project
|
||||
git clone https://github.com/TheAgentK/tuya-mqtt
|
||||
|
||||
// change directory to the project directory
|
||||
cd tuya-mqtt
|
||||
|
||||
//installs this project along with codetheweb/tuyapi project
|
||||
npm install
|
||||
```
|
||||
|
||||
## Configuration
|
||||
Tuya-mqtt has two different configuration files. The first is config.json, a simple file which contains settings for connection to the MQTT broker. The second is devices.conf, a JSON5 formatted file which defines the Tuya devices that the script should connect to and expose via MQTT. This file uses the same basic format as the "tuya-cli wizard" outputs when used to acquire the device keys, so it can be used as the basis for your tuya-mqtt device configuration.
|
||||
|
||||
### Setting up config.json:
|
||||
```
|
||||
cp config.json.sample config.json
|
||||
```
|
||||
Edit config.json with your MQTT broker settings and save:
|
||||
```
|
||||
nano config.json
|
||||
```
|
||||
|
||||
### Setting up devices.conf:
|
||||
If you use the "tuya-cli wizard" method to acquire your device keys you can leverage the output of this tool as the start of your devices.conf file. Otherwise, you want to create a file using a formate like this:
|
||||
```
|
||||
[
|
||||
{
|
||||
name: 'Tuya Device 1',
|
||||
id: '86435357d8b123456789',
|
||||
key: '8b2a69c9876543210'
|
||||
},
|
||||
{
|
||||
name: 'Tuya Device 2',
|
||||
id: 'eb532eea7d12345678abc',
|
||||
key: '899810012345678'
|
||||
}
|
||||
]
|
||||
```
|
||||
Note that, because the format is JSON5, which is a superset of JSON, you can use standard, strict JSON syntax, or the more forgiving JSON5 format, or even mix and match in the same file.
|
||||
|
||||
By default tuya-mqtt will attempt to find the device and automatically detect the Tuya protocol version, however, this only works if the system running tuya-mqtt is on the same network/subnet as the devices being controlled. If this is not the case, or if automatic detection fails for some other reason, it is possible to specify the IP address and protocol manually by adding the "ip:" property to the devices.conf file. Note that if the IP address is specified manually it is required to also manually specify the protocol version using the "version:" parameter as either "3.1" or "3.3". The easiest way to determine the protocol version is to try controlling the device with tuya-cli and try each version to see which one works.
|
||||
|
||||
While the above syntax may be enough to create a working tuya-mqtt install with raw DPS values accessible via DPS topics, the full functionality of tuya-mqtt 3.0 is only unlocked by configuring device types to get. Please see the full [DEVICES](docs/DEVICES.md) documentation for details.
|
||||
|
||||
### Starting tuya-mqtt
|
||||
```
|
||||
node tuya-mqtt.js
|
||||
```
|
||||
To enable debugging output (required when opening an issue):
|
||||
```
|
||||
DEBUG=tuya-mqtt:* tuya-mqtt.js
|
||||
```
|
||||
|
||||
### Updating devices.conf with new and/or changed devices:
|
||||
After adding or changing devices to your Tuya account the devices.conf file can be automatically updated with all new devices and name/key changes by using the merge-devices.js script. Create a file named new-devices.conf with the new "tuya-cli wizard" output then run ```node merge-devices.js```. A dated backup of the original devices.conf file will be created automatically before changes are made. Devices are only added and updated, never removed. The resulting devices.conf file will be neatly formatted and sorted alphabetically by device name.
|
||||
|
||||
To prevent device entries from being updated by the merge script, add property "allowMerge: false" to the device definition in the devices.conf file.
|
||||
|
||||
### Usage Overview
|
||||
Tuya devices work by mapping device functions to various values stored in data points (referred to as DPS values) which are referenced via an index number, referred to as the DPS key. For example, a simple on/off switch may have a single DPS value, stored in DPS kep 1 (DPS1). This value is likely to have a setting of true/false representing the on/off state of the device. The device state can be read via DPS1, and, for values that can be changed (some DPS values are read-only), sending true/false to DPS1 will turn the device on/off. A simple dimmer might have the same DPS1 value, but an additional DPS2 value from 1-255 representing the state of the dimmer. More complex devices use more DPS keys with various values representing the states and control functions of the device.
|
||||
|
||||
The tuya-mqtt script provides access to these DPS keys and their values via MQTT, allowing any tool that can use MQTT to monitor and control these devices via a local network connection. In addition to providing access to the raw DPS data, there is also a template engine that allows those DPS values to be mapped to device specific topics, called "friendly topics", allowing for consistent mapping even between devices that use different DPS keys for the same functions. These friendly topics also support various transforms and other functions that make it easier for other devices to communicate with Tuya devices without a detailed understanding of the data formats Tuya devices use.
|
||||
|
||||
### MQTT Topic Overview
|
||||
The top level topics are created using the device name or ID as the primary identifier. If the device name is available, it will be converted to lowercase and any spaces replace with underscores('_') characters so, for example, if the device as the name "Kitchen Table", the top level topic would be:
|
||||
```
|
||||
tuya/kitchen_table/
|
||||
```
|
||||
If the device name was not available in the devices.conf file, tuya-mqtt falls back to using the device ID for the top level topic:
|
||||
```
|
||||
tuya/86435357d8b123456789/
|
||||
```
|
||||
All additional state/command topics are then built below this level. You can view the connectivity status of the device using the status topic, which reports online/offline based on whether tuya-mqtt has an active connection to the device or not. The script monitors both the device socket connection for errors and also device heartbeats, to report proper status.
|
||||
```
|
||||
tuya/kitchen_table/state --> online/offline
|
||||
```
|
||||
You can also trigger the device to send an immediate update of all known device DPS topics by sending the message "get-states" to the command topic (this topic exist for all devices):
|
||||
```
|
||||
tuya/kitchen_table/command <-- get-states
|
||||
```
|
||||
As noted above, tuya-mqtt supports two distinct topic types for interfacing with and controlling devices. For all devices, the DPS topics are always published and commands are accepted, however, friendly topics are the generally recommended approach but require you to use a pre-defined device template or create a customer template for your device when using the generic device.
|
||||
|
||||
If you do create a template for your device, please feel free to share it with the community as adding additional pre-defined devices is desired for future versions of tuya-mqtt. There is a templates section of the project that you can submit a PR for your templates.
|
||||
|
||||
If you would like to use the raw DPS topics, please jump to the [DPS topics](#dps-topics) section of this document.
|
||||
|
||||
## Friendly Topics
|
||||
Friendly topics are only available when using a pre-defined device template or, for the generic device, when you have defined a custom template for your device. Friendly topics use the tuya-mqtt templating engine to map raw Tuya DPS key values to easy to consume topics and transform the data where needed.
|
||||
|
||||
Another advantage of friendly topics is that not all devices respond to schema requests (i.e. a request to report all DPS topics the device uses). Because of this, it's not always possible for tuya-mqtt to know which DPS topics to acquire state information from during initial startup. With a defined template the required DPS keys for each friendly topic are configured and tuya-mqtt will always query these DPS key values during initial connection to the device and report their state appropriately.
|
||||
|
||||
For more details on using friendly topics, please read the [DEVICES](docs/DEVICES.md) documentation which discusses how to configure supported devices or define a custom template.
|
||||
|
||||
## DPS Topics
|
||||
Controlling devices directly via DPS topics requires enough knowledge of the device to know which topics accept what values. Described below are two different methods for interfacing with DPS values, the JSON DPS topic, and the individual DPS key topics.
|
||||
|
||||
### DPS JSON topic
|
||||
The JSON DPS topic allows controlling Tuya devices by sending Tuya native style JSON messages to the command topic, and by monitoring for Tuya style JSON replies on the state topic. You can get more details on this format by reading the [TuyAPI documentation](https://codetheweb.github.io/tuyapi/index.html), but, for example, to turn off a dimmer switch you could issue a MQTT message containing the JSON value ```{dps: 1, set: false}``` to the DPS/command topic for the device. If you wanted to turn the dimmer on, and set brightness to 50%, you could issue separate messages ```{dps: 1, set: true}``` and then ```{dps: 2, set: 128}```, or, the Tuya JSON protocol also allows setting multiple values in a single set command using the format ```{'multiple': true, 'data': {'1': true, '2': 128}}```. JSON state and commands should use the DPS/state and DPS/command topics respectively. Below is an example of the topics:
|
||||
```
|
||||
tuya/dimmer_device/DPS/state
|
||||
tuya/dimmer_device/DPS/command
|
||||
```
|
||||
### DPS Key topics
|
||||
In addition to the JSON DPS topic, it's also possible to use the DPS key topics. DPS key topics allow you to monitor and send simple bool/number/string values directly to DPS keys without having to use the Tuya JSON format, the conversion to Tuya JSON is handled by tuya-mqtt. Using the example from above, turning on the dimmer and setting brightness to 50% you would simply issue the message "true" to DPS/1/command and the message "128" to DPS/2/command.
|
||||
```
|
||||
tuya/dimmer_device/DPS/1/state --> true/false for on/off state
|
||||
tuya/dimmer_device/DPS/2/command <-- 1-255 for brightness state
|
||||
tuya/dimmer_device/DPS/1/state --> accept true/false for turning device on/off
|
||||
tuya/dimmer_device/DPS/2/command <-- accepts 1-255 for controlling brightness level
|
||||
```
|
||||
**!!! Important Note !!!**
|
||||
When sending commands directly to DPS values there are no limitation on what values are sent as tuya-mqtt has no way to know what are valid vs invalid for any given DPS key. Sending values that are out-of-range or of different types than the DPS key expects can cause unpredictable behavior of your device, from causing timeouts, to reboots, to hanging the device. While I've never seen a device fail to recover after a restart, please keep this in mind when sending commands to your device.
|
||||
|
||||
## Issues
|
||||
Not all Tuya protocols are supported. For example, some devices use protocol 3.2 which currently remains unsupported by the TuyAPI project due to lack of enough information to reverse engineer the protocol. If you are unable to control your devices with tuya-mqtt please verify that you can query and control them with tuya-cli first. If tuya-cli works, then this script should also work, if it doesn't then this script will not work either.
|
||||
|
||||
## Integration with other Home Automation tools
|
||||
openHAB examples are [here](docs/openHAB.md).
|
||||
|
||||
## Contributors
|
||||
- [TheAgentK](https://github.com/TheAgentK)
|
||||
- [tsightler](https://github.com/tsightler)
|
||||
- [Tycale](https://github.com/Tycale)
|
||||
- [crashdummymch](https://github.com/crashdummymch)
|
||||
- [GadgetAngel](https://github.com/GadgetAngel)
|
||||
- [dkrahmer](https://github.com/dkrahmer)
|
||||
|
||||
## Related Projects:
|
||||
- https://github.com/codetheweb/tuyapi
|
||||
- https://github.com/unparagoned/njsTuya
|
||||
- https://github.com/clach04/python-tuya
|
||||
- https://github.com/Marcus-L/m4rcus.TuyaCore
|
||||
- Specs: https://docs.tuya.com/en/cloudapi/cloud_access.html
|
||||
|
||||
[](https://forthebadge.com)
|
||||
[](https://forthebadge.com)
|
||||
|
||||
29
cleanup.js
29
cleanup.js
@@ -1,29 +0,0 @@
|
||||
// Object to capture process exits and call app specific cleanup function
|
||||
var debug = require('debug')('Cleanup');
|
||||
|
||||
function noOp() {};
|
||||
|
||||
exports.Cleanup = function Cleanup(callback) {
|
||||
|
||||
// attach user callback to the process event emitter
|
||||
// if no callback, it will still exit gracefully on Ctrl-C
|
||||
callback = callback || noOp;
|
||||
process.on('cleanup', callback);
|
||||
|
||||
// do app specific cleaning before exiting
|
||||
process.on('exit', function () {
|
||||
process.emit('cleanup');
|
||||
});
|
||||
|
||||
// catch ctrl+c event and exit normally
|
||||
process.on('SIGINT', function () {
|
||||
debug('Ctrl-C...');
|
||||
process.exit(2);
|
||||
});
|
||||
|
||||
//catch uncaught exceptions, trace, then exit normally
|
||||
process.on('uncaughtException', function (e) {
|
||||
debug('Uncaught Exception...', e.stack);
|
||||
process.exit(99);
|
||||
});
|
||||
};
|
||||
@@ -3,6 +3,5 @@
|
||||
"port": 1883,
|
||||
"topic": "tuya/",
|
||||
"mqtt_user": "",
|
||||
"mqtt_pass": "",
|
||||
"qos": 2
|
||||
"mqtt_pass": ""
|
||||
}
|
||||
|
||||
29
devices/generic-device.js
Normal file
29
devices/generic-device.js
Normal file
@@ -0,0 +1,29 @@
|
||||
const TuyaDevice = require('./tuya-device')
|
||||
const debug = require('debug')('tuya-mqtt:device')
|
||||
const utils = require('../lib/utils')
|
||||
|
||||
class GenericDevice extends TuyaDevice {
|
||||
async init() {
|
||||
this.deviceData.mdl = 'Generic Device'
|
||||
|
||||
// Check if custom template in device config
|
||||
if (this.config.hasOwnProperty('template')) {
|
||||
// Map generic DPS topics to device specific topic names
|
||||
this.deviceTopics = this.config.template
|
||||
} else {
|
||||
// Try to get schema to at least know what DPS keys to get initial update
|
||||
const result = await this.device.get({"schema": true})
|
||||
if (!utils.isJsonString(result)) {
|
||||
if (result === 'Schema for device not available') {
|
||||
debug('Device id '+this.config.id+' failed schema discovery and no custom template defined')
|
||||
debug('Cannot get initial DPS state data for device '+this.options.name+' but data updates will be publish')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get initial states and start publishing topics
|
||||
this.getStates()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GenericDevice
|
||||
179
devices/rgbtw-light.js
Normal file
179
devices/rgbtw-light.js
Normal file
@@ -0,0 +1,179 @@
|
||||
const TuyaDevice = require('./tuya-device')
|
||||
const debug = require('debug')('tuya-mqtt:device-detect')
|
||||
const debugDiscovery = require('debug')('tuya-mqtt:discovery')
|
||||
const utils = require('../lib/utils')
|
||||
|
||||
class RGBTWLight extends TuyaDevice {
|
||||
async init() {
|
||||
// If no manual config try to detect device settings
|
||||
if (!this.config.dpsPower) {
|
||||
await this.guessLightInfo()
|
||||
}
|
||||
|
||||
// If detection failed and no manual config return without initializing
|
||||
if (!this.guess.dpsPower && !this.config.dpsPower) {
|
||||
debug('Automatic discovery of Tuya bulb settings failed and no manual configuration')
|
||||
return
|
||||
}
|
||||
|
||||
// Set device specific variables
|
||||
this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : this.guess.dpsPower
|
||||
this.config.dpsMode = this.config.dpsMode ? this.config.dpsMode : this.guess.dpsMode
|
||||
this.config.dpsWhiteValue = this.config.dpsWhiteValue ? this.config.dpsWhiteValue : this.guess.dpsWhiteValue
|
||||
this.config.whiteValueScale = this.config.whiteValueScale ? this.config.whiteValueScale : this.guess.whiteValueScale
|
||||
this.config.dpsColorTemp = this.config.dpsColorTemp ? this.config.dpsColorTemp : this.guess.dpsColorTemp
|
||||
this.config.minColorTemp = this.config.minColorTemp ? this.config.minColorTemp : 154 // ~6500K
|
||||
this.config.maxColorTemp = this.config.maxColorTemp ? this.config.maxColorTemp : 400 // ~2500K
|
||||
this.config.colorTempScale = this.config.colorTempScale ? this.config.colorTempScale : this.guess.colorTempScale
|
||||
this.config.dpsColor = this.config.dpsColor ? this.config.dpsColor : this.guess.dpsColor
|
||||
this.config.colorType = this.config.colorType ? this.config.colorType : this.guess.colorType
|
||||
|
||||
this.deviceData.mdl = 'RGBTW Light'
|
||||
this.isRgbtwLight = true
|
||||
|
||||
// Set white value transform math
|
||||
let whiteValueStateMath
|
||||
let whiteValueCommandMath
|
||||
if (this.config.whiteValueScale === 255) {
|
||||
// Devices with brightness scale of 255 seem to not allow values
|
||||
// less then 25 (10%) without producing timeout errors.
|
||||
whiteValueStateMath = '/2.3-10.86'
|
||||
whiteValueCommandMath = '*2.3+25'
|
||||
} else {
|
||||
// For other scale (usually 1000), 10-1000 seems OK.
|
||||
whiteValueStateMath = '/('+this.config.whiteValueScale+'/100)'
|
||||
whiteValueCommandMath = '*('+this.config.whiteValueScale+'/100)'
|
||||
}
|
||||
|
||||
// Map generic DPS topics to device specific topic names
|
||||
this.deviceTopics = {
|
||||
state: {
|
||||
key: this.config.dpsPower,
|
||||
type: 'bool'
|
||||
},
|
||||
white_brightness_state: {
|
||||
key: this.config.dpsWhiteValue,
|
||||
type: 'int',
|
||||
topicMin: 0,
|
||||
topicMax: 100,
|
||||
stateMath: whiteValueStateMath,
|
||||
commandMath: whiteValueCommandMath
|
||||
},
|
||||
hs_state: {
|
||||
key: this.config.dpsColor,
|
||||
type: this.config.colorType,
|
||||
components: 'h,s'
|
||||
},
|
||||
color_brightness_state: {
|
||||
key: this.config.dpsColor,
|
||||
type: this.config.colorType,
|
||||
components: 'b'
|
||||
},
|
||||
hsb_state: {
|
||||
key: this.config.dpsColor,
|
||||
type: this.config.colorType,
|
||||
components: 'h,s,b'
|
||||
},
|
||||
mode_state: {
|
||||
key: this.config.dpsMode,
|
||||
type: 'str'
|
||||
}
|
||||
}
|
||||
|
||||
// If device supports Color Temperature add color temp device topic
|
||||
if (this.config.dpsColorTemp) {
|
||||
// Values used for tranforming from 1-255 scale to mireds range
|
||||
const rangeFactor = (this.config.maxColorTemp-this.config.minColorTemp)/100
|
||||
const scaleFactor = this.config.colorTempScale/100
|
||||
const tuyaMaxColorTemp = this.config.maxColorTemp/rangeFactor*scaleFactor
|
||||
|
||||
this.deviceTopics.color_temp_state = {
|
||||
key: this.config.dpsColorTemp,
|
||||
type: 'int',
|
||||
topicMin: this.config.minColorTemp,
|
||||
topicMax: this.config.maxColorTemp,
|
||||
stateMath: '/'+scaleFactor+'*-'+rangeFactor+'+'+this.config.maxColorTemp,
|
||||
commandMath: '/'+rangeFactor+'*-'+scaleFactor+'+'+tuyaMaxColorTemp
|
||||
}
|
||||
}
|
||||
|
||||
// Send home assistant discovery data and give it a second before sending state updates
|
||||
this.initDiscovery()
|
||||
await utils.sleep(1)
|
||||
|
||||
// Get initial states and start publishing topics
|
||||
this.getStates()
|
||||
}
|
||||
|
||||
initDiscovery() {
|
||||
const configTopic = 'homeassistant/light/'+this.config.id+'/config'
|
||||
|
||||
const discoveryData = {
|
||||
name: (this.config.name) ? this.config.name : this.config.id,
|
||||
state_topic: this.baseTopic+'state',
|
||||
command_topic: this.baseTopic+'command',
|
||||
brightness_state_topic: this.baseTopic+'color_brightness_state',
|
||||
brightness_command_topic: this.baseTopic+'color_brightness_command',
|
||||
brightness_scale: 100,
|
||||
hs_state_topic: this.baseTopic+'hs_state',
|
||||
hs_command_topic: this.baseTopic+'hs_command',
|
||||
white_value_state_topic: this.baseTopic+'white_brightness_state',
|
||||
white_value_command_topic: this.baseTopic+'white_brightness_command',
|
||||
white_value_scale: 100,
|
||||
availability_topic: this.baseTopic+'status',
|
||||
payload_available: 'online',
|
||||
payload_not_available: 'offline',
|
||||
unique_id: this.config.id,
|
||||
device: this.deviceData
|
||||
}
|
||||
|
||||
if (this.config.dpsColorTemp) {
|
||||
discoveryData.color_temp_state_topic = this.baseTopic+'color_temp_state'
|
||||
discoveryData.color_temp_command_topic = this.baseTopic+'color_temp_command'
|
||||
discoveryData.min_mireds = this.config.minColorTemp
|
||||
discoveryData.max_mireds = this.config.maxColorTemp
|
||||
}
|
||||
|
||||
debugDiscovery('Home Assistant config topic: '+configTopic)
|
||||
debugDiscovery(discoveryData)
|
||||
this.publishMqtt(configTopic, JSON.stringify(discoveryData))
|
||||
}
|
||||
|
||||
async guessLightInfo() {
|
||||
this.guess = new Object()
|
||||
debug('Attempting to detect light capabilites and DPS values...')
|
||||
debug('Querying DPS 2 for white/color mode setting...')
|
||||
|
||||
// Check if DPS 2 contains typical values for RGBTW light
|
||||
const mode2 = await this.device.get({"dps": 2})
|
||||
const mode21 = await this.device.get({"dps": 21})
|
||||
if (mode2 && (mode2 === 'white' || mode2 === 'colour' || mode2.toString().includes('scene'))) {
|
||||
debug('Detected likely Tuya color bulb at DPS 1-5, checking more details...')
|
||||
this.guess = {'dpsPower': 1, 'dpsMode': 2, 'dpsWhiteValue': 3, 'whiteValueScale': 255, 'dpsColorTemp': 4, 'colorTempScale': 255, 'dpsColor': 5}
|
||||
} else if (mode21 && (mode21 === 'white' || mode21 === 'colour' || mode21.toString().includes('scene'))) {
|
||||
debug('Detected likely Tuya color bulb at DPS 20-24, checking more details...')
|
||||
this.guess = {'dpsPower': 20, 'dpsMode': 21, 'dpsWhiteValue': 22, 'whiteValueScale': 1000, 'dpsColorTemp': 23, 'colorTempScale': 1000, 'dpsColor': 24}
|
||||
}
|
||||
|
||||
if (this.guess.dpsPower) {
|
||||
debug('Attempting to detect if bulb supports color temperature...')
|
||||
const colorTemp = await this.device.get({"dps": this.guess.dpsColorTemp})
|
||||
if (colorTemp !== '' && colorTemp >= 0 && colorTemp <= this.guess.colorTempScale) {
|
||||
debug('Detected likely color temperature support')
|
||||
} else {
|
||||
debug('No color temperature support detected')
|
||||
this.guess.dpsColorTemp = 0
|
||||
}
|
||||
debug('Attempting to detect Tuya color format used by device...')
|
||||
const color = await this.device.get({"dps": this.guess.dpsColor})
|
||||
if (this.guess.dpsPower === 1) {
|
||||
this.guess.colorType = (color && color.length === 12) ? 'hsb' : 'hsbhex'
|
||||
} else {
|
||||
this.guess.colorType = (color && color.length === 14) ? 'hsbhex' : 'hsb'
|
||||
}
|
||||
debug ('Detected Tuya color format '+this.guess.colorType.toUpperCase())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RGBTWLight
|
||||
76
devices/simple-dimmer.js
Normal file
76
devices/simple-dimmer.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const TuyaDevice = require('./tuya-device')
|
||||
const debug = require('debug')('tuya-mqtt:device')
|
||||
const debugDiscovery = require('debug')('tuya-mqtt:discovery')
|
||||
const utils = require('../lib/utils')
|
||||
|
||||
class SimpleDimmer extends TuyaDevice {
|
||||
async init() {
|
||||
// Set device specific variables
|
||||
this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : 1
|
||||
this.config.dpsBrightness = this.config.dpsBrightness ? this.config.dpsBrightness : 2
|
||||
this.config.brightnessScale = this.config.brightnessScale ? this.config.brightnessScale : 255
|
||||
|
||||
this.deviceData.mdl = 'Dimmer Switch'
|
||||
|
||||
// Set white value transform math
|
||||
let brightnessStateMath
|
||||
let brightnessCommandMath
|
||||
if (this.config.brightnessScale === 255) {
|
||||
// Devices with brightness scale of 255 seem to not allow values
|
||||
// less then 25 (10%) without producing timeout errors.
|
||||
brightnessStateMath = '/2.3-10.86'
|
||||
brightnessCommandMath = '*2.3+25'
|
||||
} else {
|
||||
// For other scale (usually 1000), 10-1000 seems OK.
|
||||
brightnessStateMath = '/('+this.config.brightnessScale+'/100)'
|
||||
brightnessCommandMath = '*('+this.config.brightnessScale+'/100)'
|
||||
}
|
||||
|
||||
// Map generic DPS topics to device specific topic names
|
||||
this.deviceTopics = {
|
||||
state: {
|
||||
key: this.config.dpsPower,
|
||||
type: 'bool'
|
||||
},
|
||||
brightness_state: {
|
||||
key: this.config.dpsBrightness,
|
||||
type: 'int',
|
||||
topicMin: 0,
|
||||
topicMax: 100,
|
||||
stateMath: brightnessStateMath,
|
||||
commandMath: brightnessCommandMath
|
||||
}
|
||||
}
|
||||
|
||||
// Send home assistant discovery data and give it a second before sending state updates
|
||||
this.initDiscovery()
|
||||
await utils.sleep(1)
|
||||
|
||||
// Get initial states and start publishing topics
|
||||
this.getStates()
|
||||
}
|
||||
|
||||
initDiscovery() {
|
||||
const configTopic = 'homeassistant/light/'+this.config.id+'/config'
|
||||
|
||||
const discoveryData = {
|
||||
name: (this.config.name) ? this.config.name : this.config.id,
|
||||
state_topic: this.baseTopic+'state',
|
||||
command_topic: this.baseTopic+'command',
|
||||
brightness_state_topic: this.baseTopic+'brightness_state',
|
||||
brightness_command_topic: this.baseTopic+'brightness_command',
|
||||
brightness_scale: 100,
|
||||
availability_topic: this.baseTopic+'status',
|
||||
payload_available: 'online',
|
||||
payload_not_available: 'offline',
|
||||
unique_id: this.config.id,
|
||||
device: this.deviceData
|
||||
}
|
||||
|
||||
debugDiscovery('Home Assistant config topic: '+configTopic)
|
||||
debugDiscovery(discoveryData)
|
||||
this.publishMqtt(configTopic, JSON.stringify(discoveryData))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SimpleDimmer
|
||||
49
devices/simple-switch.js
Normal file
49
devices/simple-switch.js
Normal file
@@ -0,0 +1,49 @@
|
||||
const TuyaDevice = require('./tuya-device')
|
||||
const debug = require('debug')('tuya-mqtt:device')
|
||||
const debugDiscovery = require('debug')('tuya-mqtt:discovery')
|
||||
const utils = require('../lib/utils')
|
||||
|
||||
class SimpleSwitch extends TuyaDevice {
|
||||
async init() {
|
||||
// Set device specific variables
|
||||
this.config.dpsPower = this.config.dpsPower ? this.config.dpsPower : 1
|
||||
|
||||
this.deviceData.mdl = 'Switch/Socket'
|
||||
|
||||
// Map generic DPS topics to device specific topic names
|
||||
this.deviceTopics = {
|
||||
state: {
|
||||
key: this.config.dpsPower,
|
||||
type: 'bool'
|
||||
}
|
||||
}
|
||||
|
||||
// Send home assistant discovery data and give it a second before sending state updates
|
||||
this.initDiscovery()
|
||||
await utils.sleep(1)
|
||||
|
||||
// Get initial states and start publishing topics
|
||||
this.getStates()
|
||||
}
|
||||
|
||||
initDiscovery() {
|
||||
const configTopic = 'homeassistant/switch/'+this.config.id+'/config'
|
||||
|
||||
const discoveryData = {
|
||||
name: (this.config.name) ? this.config.name : this.config.id,
|
||||
state_topic: this.baseTopic+'state',
|
||||
command_topic: this.baseTopic+'command',
|
||||
availability_topic: this.baseTopic+'status',
|
||||
payload_available: 'online',
|
||||
payload_not_available: 'offline',
|
||||
unique_id: this.config.id,
|
||||
device: this.deviceData
|
||||
}
|
||||
|
||||
debugDiscovery('Home Assistant config topic: '+configTopic)
|
||||
debugDiscovery(discoveryData)
|
||||
this.publishMqtt(configTopic, JSON.stringify(discoveryData))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SimpleSwitch
|
||||
651
devices/tuya-device.js
Normal file
651
devices/tuya-device.js
Normal file
@@ -0,0 +1,651 @@
|
||||
const TuyAPI = require('tuyapi')
|
||||
const { evaluate } = require('mathjs')
|
||||
const utils = require('../lib/utils')
|
||||
const debug = require('debug')('tuya-mqtt:tuyapi')
|
||||
const debugState = require('debug')('tuya-mqtt:state')
|
||||
const debugCommand = require('debug')('tuya-mqtt:command')
|
||||
const debugError = require('debug')('tuya-mqtt:error')
|
||||
|
||||
class TuyaDevice {
|
||||
constructor(deviceInfo) {
|
||||
this.config = deviceInfo.configDevice
|
||||
this.mqttClient = deviceInfo.mqttClient
|
||||
this.topic = deviceInfo.topic
|
||||
|
||||
// Build TuyAPI device options from device config info
|
||||
this.options = {
|
||||
id: this.config.id,
|
||||
key: this.config.key
|
||||
}
|
||||
if (this.config.name) { this.options.name = this.config.name.toLowerCase().replace(/\s|\+|#|\//g,'_') }
|
||||
if (this.config.ip) {
|
||||
this.options.ip = this.config.ip
|
||||
if (this.config.version) {
|
||||
this.options.version = this.config.version
|
||||
} else {
|
||||
this.options.version = '3.1'
|
||||
}
|
||||
}
|
||||
|
||||
// Set default device data for Home Assistant device registry
|
||||
// Values may be overridden by individual devices
|
||||
this.deviceData = {
|
||||
ids: [ this.config.id ],
|
||||
name: (this.config.name) ? this.config.name : this.config.id,
|
||||
mf: 'Tuya'
|
||||
}
|
||||
|
||||
// Initialize properties to hold cached device state data
|
||||
this.dps = {}
|
||||
this.color = {'h': 0, 's': 0, 'b': 0}
|
||||
|
||||
// Device friendly topics
|
||||
this.deviceTopics = {}
|
||||
|
||||
// Missed heartbeat monitor
|
||||
this.heartbeatsMissed = 0
|
||||
this.reconnecting = false
|
||||
|
||||
// Build the MQTT topic for this device (friendly name or device id)
|
||||
if (this.options.name) {
|
||||
this.baseTopic = this.topic + this.options.name + '/'
|
||||
} else {
|
||||
this.baseTopic = this.topic + this.options.id + '/'
|
||||
}
|
||||
|
||||
// Create the new Tuya Device
|
||||
this.device = new TuyAPI(JSON.parse(JSON.stringify(this.options)))
|
||||
|
||||
// Listen for device data and call update DPS function if valid
|
||||
this.device.on('data', (data) => {
|
||||
if (typeof data === 'object') {
|
||||
debug('Received JSON data from device '+this.options.id+' ->', JSON.stringify(data.dps))
|
||||
this.updateState(data)
|
||||
} else {
|
||||
if (data !== 'json obj data unvalid') {
|
||||
debug('Received string data from device '+this.options.id+' ->', data.replace(/[^a-zA-Z0-9 ]/g, ''))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Attempt to find/connect to device and start heartbeat monitor
|
||||
this.connectDevice()
|
||||
this.monitorHeartbeat()
|
||||
|
||||
// On connect perform device specific init
|
||||
this.device.on('connected', async () => {
|
||||
// Sometimes TuyAPI reports connection even on socket error
|
||||
// Wait one second to check if device is really connected before initializing
|
||||
await utils.sleep(1)
|
||||
if (this.device.isConnected()) {
|
||||
debug('Connected to device ' + this.toString())
|
||||
this.heartbeatsMissed = 0
|
||||
this.publishMqtt(this.baseTopic+'status', 'online')
|
||||
this.init()
|
||||
}
|
||||
})
|
||||
|
||||
// On disconnect perform device specific disconnect
|
||||
this.device.on('disconnected', async () => {
|
||||
this.connected = false
|
||||
this.publishMqtt(this.baseTopic+'status', 'offline')
|
||||
debug('Disconnected from device ' + this.toString())
|
||||
await utils.sleep(5)
|
||||
this.reconnect()
|
||||
})
|
||||
|
||||
// On connect error call reconnect
|
||||
this.device.on('error', async (err) => {
|
||||
debugError(err)
|
||||
await utils.sleep(1)
|
||||
this.reconnect()
|
||||
})
|
||||
|
||||
// On heartbeat reset heartbeat timer
|
||||
this.device.on('heartbeat', () => {
|
||||
this.heartbeatsMissed = 0
|
||||
})
|
||||
}
|
||||
|
||||
// Get and update cached values of all configured/known dps value for device
|
||||
async getStates() {
|
||||
// Suppress topic updates while syncing device state with cached state
|
||||
this.connected = false
|
||||
for (let topic in this.deviceTopics) {
|
||||
const key = this.deviceTopics[topic].key
|
||||
if (!this.dps[key]) { this.dps[key] = {} }
|
||||
try {
|
||||
this.dps[key].val = await this.device.get({"dps": key})
|
||||
this.dps[key].updated = true
|
||||
} catch {
|
||||
debugError('Could not get value for device DPS key '+key)
|
||||
}
|
||||
}
|
||||
this.connected = true
|
||||
// Force topic update now that all states are fully syncronized
|
||||
this.publishTopics()
|
||||
}
|
||||
|
||||
// Update cached DPS values on data updates
|
||||
updateState(data) {
|
||||
if (typeof data.dps != 'undefined') {
|
||||
// Update cached device state data
|
||||
for (let key in data.dps) {
|
||||
// Only update if the received value is different from previous value
|
||||
if (this.dps[key] !== data.dps[key]) {
|
||||
this.dps[key] = {
|
||||
'val': data.dps[key],
|
||||
'updated': true
|
||||
}
|
||||
}
|
||||
if (this.isRgbtwLight) {
|
||||
if (this.config.hasOwnProperty('dpsColor') && this.config.dpsColor == key) {
|
||||
this.updateColorState(data.dps[key])
|
||||
} else if (this.config.hasOwnProperty('dpsMode') && this.config.dpsMode == key) {
|
||||
// If color/white mode is changing, force sending color state
|
||||
// Allows overriding saturation value to 0% for white mode for the HSB device topics
|
||||
this.dps[this.config.dpsColor].updated = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.connected) {
|
||||
this.publishTopics()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Publish device specific state topics
|
||||
publishTopics() {
|
||||
// Don't publish if device is not connected
|
||||
if (!this.connected) return
|
||||
|
||||
// Loop through and publish all device specific topics
|
||||
for (let topic in this.deviceTopics) {
|
||||
const deviceTopic = this.deviceTopics[topic]
|
||||
const key = deviceTopic.key
|
||||
// Only publish values if different from previous value
|
||||
if (this.dps[key] && this.dps[key].updated) {
|
||||
const state = this.getTopicState(deviceTopic, this.dps[key].val)
|
||||
if (state) {
|
||||
this.publishMqtt(this.baseTopic + topic, state, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Publish Generic Dps Topics
|
||||
this.publishDpsTopics()
|
||||
}
|
||||
|
||||
// Publish all dps-values to topic
|
||||
publishDpsTopics() {
|
||||
try {
|
||||
if (!Object.keys(this.dps).length) { return }
|
||||
|
||||
const dpsTopic = this.baseTopic + 'dps'
|
||||
// Publish DPS JSON data if not empty
|
||||
let data = {}
|
||||
for (let key in this.dps) {
|
||||
// Only publish values if different from previous value
|
||||
if (this.dps[key].updated) {
|
||||
data[key] = this.dps[key].val
|
||||
}
|
||||
}
|
||||
data = JSON.stringify(data)
|
||||
const dpsStateTopic = dpsTopic + '/state'
|
||||
debugState('MQTT DPS JSON: ' + dpsStateTopic + ' -> ', data)
|
||||
this.publishMqtt(dpsStateTopic, data, false)
|
||||
|
||||
// Publish dps/<#>/state value for each device DPS
|
||||
for (let key in this.dps) {
|
||||
// Only publish values if different from previous value
|
||||
if (this.dps[key].updated) {
|
||||
const dpsKeyTopic = dpsTopic + '/' + key + '/state'
|
||||
const data = this.dps.hasOwnProperty(key) ? this.dps[key].val.toString() : 'None'
|
||||
debugState('MQTT DPS'+key+': '+dpsKeyTopic+' -> ', data)
|
||||
this.publishMqtt(dpsKeyTopic, data, false)
|
||||
this.dps[key].updated = false
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugError(e);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the friendly topic state based on configured DPS value type
|
||||
getTopicState(deviceTopic, value) {
|
||||
let state
|
||||
switch (deviceTopic.type) {
|
||||
case 'bool':
|
||||
state = value ? 'ON' : 'OFF'
|
||||
break;
|
||||
case 'int':
|
||||
case 'float':
|
||||
state = this.parseNumberState(value, deviceTopic)
|
||||
break;
|
||||
case 'hsb':
|
||||
case 'hsbhex':
|
||||
// Return comma separate array of component values for specific topic
|
||||
state = new Array()
|
||||
const components = deviceTopic.components.split(',')
|
||||
for (let i in components) {
|
||||
// If light is in white mode always report saturation 0%, otherwise report actual value
|
||||
state.push((components[i] === 's' && this.dps[this.config.dpsMode].val === 'white') ? 0 : this.color[components[i]])
|
||||
}
|
||||
state = (state.join(','))
|
||||
break;
|
||||
case 'str':
|
||||
state = value ? value : ''
|
||||
break;
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
// Parse the received state numeric value based on deviceTopic rules
|
||||
parseNumberState(value, deviceTopic) {
|
||||
// Check if it's a number and it's not outside of defined range
|
||||
if (isNaN(value)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
// Perform any required math transforms before returing command value
|
||||
switch (deviceTopic.type) {
|
||||
case 'int':
|
||||
value = (deviceTopic.stateMath) ? parseInt(Math.round(evaluate(value+deviceTopic.stateMath))) : parseInt(value)
|
||||
break;
|
||||
case 'float':
|
||||
value = (deviceTopic.stateMath) ? parseFloat(evaluate(value+deviceTopic.stateMath)) : parseFloat(value)
|
||||
break;
|
||||
}
|
||||
|
||||
return value.toString()
|
||||
}
|
||||
|
||||
// Initial processing of MQTT commands for all command topics
|
||||
processCommand(message, commandTopic) {
|
||||
let command
|
||||
if (utils.isJsonString(message)) {
|
||||
debugCommand('Received MQTT command message is a JSON string')
|
||||
command = JSON.parse(message);
|
||||
} else {
|
||||
debugCommand('Received MQTT command message is a text string')
|
||||
command = message.toLowerCase()
|
||||
}
|
||||
|
||||
// If get-states command, then updates all states and re-publish topics
|
||||
if (commandTopic === 'command' && command === 'get-states') {
|
||||
// Handle "get-states" command to update device state
|
||||
debugCommand('Received command: ', command)
|
||||
this.getStates()
|
||||
} else {
|
||||
// Call device specific command topic handler
|
||||
this.processDeviceCommand(command, commandTopic)
|
||||
}
|
||||
}
|
||||
|
||||
// Process MQTT commands for all device command topics
|
||||
processDeviceCommand(command, commandTopic) {
|
||||
// Determine state topic from command topic to find proper template
|
||||
const stateTopic = commandTopic.replace('command', 'state')
|
||||
const deviceTopic = this.deviceTopics.hasOwnProperty(stateTopic) ? this.deviceTopics[stateTopic] : ''
|
||||
|
||||
if (deviceTopic) {
|
||||
debugCommand('Device '+this.options.id+' received command topic: '+commandTopic+', message: '+command)
|
||||
let commandResult = this.sendTuyaCommand(command, deviceTopic)
|
||||
if (!commandResult) {
|
||||
debugCommand('Command topic '+this.baseTopic+commandTopic+' received invalid value: '+command)
|
||||
}
|
||||
} else {
|
||||
debugCommand('Invalid command topic '+this.baseTopic+commandTopic+' for device id: '+this.config.id)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Process Tuya JSON commands via DPS command topic
|
||||
processDpsCommand(message) {
|
||||
if (utils.isJsonString(message)) {
|
||||
const command = JSON.parse(message)
|
||||
debugCommand('Parsed Tuya JSON command: '+JSON.stringify(command))
|
||||
this.set(command)
|
||||
} else {
|
||||
debugCommand('DPS command topic requires Tuya style JSON value')
|
||||
}
|
||||
}
|
||||
|
||||
// Process text based Tuya commands via DPS key command topics
|
||||
processDpsKeyCommand(message, dpsKey) {
|
||||
if (utils.isJsonString(message)) {
|
||||
debugCommand('Individual DPS command topics do not accept JSON values')
|
||||
} else {
|
||||
const dpsMessage = this.parseDpsMessage(message)
|
||||
debugCommand('Received command for DPS'+dpsKey+': ', message)
|
||||
const command = {
|
||||
dps: dpsKey,
|
||||
set: dpsMessage
|
||||
}
|
||||
this.set(command)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse string message into boolean and number types
|
||||
parseDpsMessage(message) {
|
||||
if (typeof message === 'boolean' ) {
|
||||
return message;
|
||||
} else if (message === 'true' || message === 'false') {
|
||||
return (message === 'true') ? true : false
|
||||
} else if (!isNaN(message)) {
|
||||
return Number(message)
|
||||
} else {
|
||||
return message
|
||||
}
|
||||
}
|
||||
|
||||
// Set state based on command topic
|
||||
sendTuyaCommand(message, deviceTopic) {
|
||||
let command = message.toLowerCase()
|
||||
const tuyaCommand = new Object()
|
||||
tuyaCommand.dps = deviceTopic.key
|
||||
switch (deviceTopic.type) {
|
||||
case 'bool':
|
||||
if (command === 'toggle') {
|
||||
tuyaCommand.set = !this.dps[tuyaCommand.dps].val
|
||||
} else {
|
||||
command = this.parseBoolCommand(command)
|
||||
if (typeof command.set === 'boolean') {
|
||||
tuyaCommand.set = command.set
|
||||
} else {
|
||||
tuyaCommand.set = '!!!INVALID!!!'
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'int':
|
||||
case 'float':
|
||||
tuyaCommand.set = this.parseNumberCommand(command, deviceTopic)
|
||||
break;
|
||||
case 'hsb':
|
||||
this.updateCommandColor(command, deviceTopic.components)
|
||||
tuyaCommand.set = this.parseTuyaHsbColor()
|
||||
break;
|
||||
case 'hsbhex':
|
||||
this.updateCommandColor(command, deviceTopic.components)
|
||||
tuyaCommand.set = this.parseTuyaHsbHexColor()
|
||||
break;
|
||||
default:
|
||||
// If type is not one of the above just use the raw string as is
|
||||
tuyaCommand.set = message
|
||||
}
|
||||
if (tuyaCommand.set === '!!!INVALID!!!') {
|
||||
return false
|
||||
} else {
|
||||
if (this.isRgbtwLight) {
|
||||
this.setLight(deviceTopic, tuyaCommand)
|
||||
} else {
|
||||
this.set(tuyaCommand)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Convert simple bool commands to true/false
|
||||
parseBoolCommand(command) {
|
||||
switch(command) {
|
||||
case 'on':
|
||||
case 'off':
|
||||
case '0':
|
||||
case '1':
|
||||
case 'true':
|
||||
case 'false':
|
||||
return {
|
||||
set: (command === 'on' || command === '1' || command === 'true' || command === 1) ? true : false
|
||||
}
|
||||
default:
|
||||
return command
|
||||
}
|
||||
}
|
||||
|
||||
// Validate/transform set interger values
|
||||
parseNumberCommand(command, deviceTopic) {
|
||||
let value = undefined
|
||||
const invalid = '!!!INVALID!!!'
|
||||
|
||||
// Check if it's a number and it's not outside of defined range
|
||||
if (isNaN(command)) {
|
||||
return invalid
|
||||
} else if (deviceTopic.hasOwnProperty('topicMin') && command < deviceTopic.topicMin) {
|
||||
debugError('Received command value "'+command+'" that is less than the configured minimum value')
|
||||
debugError('Overriding command with minimum value '+deviceTopic.topicMin)
|
||||
command = deviceTopic.topicMin
|
||||
} else if (deviceTopic.hasOwnProperty('topicMax') && command > deviceTopic.topicMax) {
|
||||
debugError('Received command value "'+command+'" that is greater than the configured maximum value')
|
||||
debugError('Overriding command with maximum value: '+deviceTopic.topicMax)
|
||||
command = deviceTopic.topicMax
|
||||
}
|
||||
|
||||
// Perform any required math transforms before returing command value
|
||||
switch (deviceTopic.type) {
|
||||
case 'int':
|
||||
if (deviceTopic.commandMath) {
|
||||
value = parseInt(Math.round(evaluate(command+deviceTopic.commandMath)))
|
||||
} else {
|
||||
value = parseInt(command)
|
||||
}
|
||||
break;
|
||||
case 'float':
|
||||
if (deviceTopic.commandMath) {
|
||||
value = parseFloat(evaluate(command+deviceTopic.commandMath))
|
||||
} else {
|
||||
value = parseFloat(command)
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// Takes Tuya color value in HSB or HSBHEX format and updates cached HSB color state for device
|
||||
// Credit homebridge-tuya project for HSB/HSBHEX conversion code
|
||||
updateColorState(value) {
|
||||
let h, s, b
|
||||
if (this.config.colorType === 'hsbhex') {
|
||||
[, h, s, b] = (value || '0000000000ffff').match(/^.{6}([0-9a-f]{4})([0-9a-f]{2})([0-9a-f]{2})$/i) || [0, '0', 'ff', 'ff'];
|
||||
this.color.h = parseInt(h, 16)
|
||||
this.color.s = Math.round(parseInt(s, 16) / 2.55) // Convert saturation to 100 scale
|
||||
this.color.b = Math.round(parseInt(b, 16) / 2.55) // Convert brightness to 100 scale
|
||||
} else {
|
||||
[, h, s, b] = (value || '000003e803e8').match(/^([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})$/i) || [0, '0', '3e8', '3e8']
|
||||
// Convert from Hex to Decimal and cache values
|
||||
this.color.h = parseInt(h, 16)
|
||||
this.color.s = Math.round(parseInt(s, 16) / 10) // Convert saturation to 100 Scale
|
||||
this.color.b = Math.round(parseInt(b, 16) / 10) // Convert brightness to 100 scale
|
||||
}
|
||||
|
||||
// Initialize the command color values with existing color state
|
||||
if (!this.hasOwnProperty('cmdColor')) {
|
||||
this.cmdColor = {
|
||||
'h': this.color.h,
|
||||
's': this.color.s,
|
||||
'b': this.color.b
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Caches color updates when HSB components have separate device topics
|
||||
// cmdColor property always contains the desired HSB color state based on received
|
||||
// command topic messages vs actual device color state, which may be pending
|
||||
updateCommandColor(value, components) {
|
||||
// Update any HSB component with a changed value
|
||||
components = components.split(',')
|
||||
const values = value.split(',')
|
||||
for (let i in components) {
|
||||
this.cmdColor[components[i]] = Math.round(values[i])
|
||||
}
|
||||
}
|
||||
|
||||
// Returns Tuya HSB format value from current cmdColor HSB values
|
||||
// Credit homebridge-tuya project for HSB conversion code
|
||||
parseTuyaHsbColor() {
|
||||
let {h, s, b} = this.cmdColor
|
||||
const hexColor = h.toString(16).padStart(4, '0') + (10 * s).toString(16).padStart(4, '0') + (10 * b).toString(16).padStart(4, '0')
|
||||
return hexColor
|
||||
}
|
||||
|
||||
// Returns Tuya HSBHEX format value from current cmdColor HSB values
|
||||
// Credit homebridge-tuya project for HSBHEX conversion code
|
||||
parseTuyaHsbHexColor() {
|
||||
let {h, s, b} = this.cmdColor
|
||||
const hsb = h.toString(16).padStart(4, '0') + Math.round(2.55 * s).toString(16).padStart(2, '0') + Math.round(2.55 * b).toString(16).padStart(2, '0');
|
||||
h /= 60;
|
||||
s /= 100;
|
||||
b *= 2.55;
|
||||
const
|
||||
i = Math.floor(h),
|
||||
f = h - i,
|
||||
p = b * (1 - s),
|
||||
q = b * (1 - s * f),
|
||||
t = b * (1 - s * (1 - f)),
|
||||
rgb = (() => {
|
||||
switch (i % 6) {
|
||||
case 0:
|
||||
return [b, t, p];
|
||||
case 1:
|
||||
return [q, b, p];
|
||||
case 2:
|
||||
return [p, b, t];
|
||||
case 3:
|
||||
return [p, q, b];
|
||||
case 4:
|
||||
return [t, p, b];
|
||||
case 5:
|
||||
return [b, p, q];
|
||||
}
|
||||
})().map(c => Math.round(c).toString(16).padStart(2, '0')),
|
||||
hex = rgb.join('');
|
||||
|
||||
return hex + hsb;
|
||||
}
|
||||
|
||||
// Set white/colour mode based on received commands
|
||||
async setLight(topic, command) {
|
||||
let targetMode = undefined
|
||||
|
||||
if (topic.key === this.config.dpsWhiteValue || topic.key === this.config.dpsColorTemp) {
|
||||
// If setting white level or color temperature, light should be in white mode
|
||||
targetMode = 'white'
|
||||
} else if (topic.key === this.config.dpsColor) {
|
||||
// Split device topic HSB components into array
|
||||
const components = topic.components.split(',')
|
||||
|
||||
// If device topic inlucdes saturation check for changes
|
||||
if (components.includes('s')) {
|
||||
if (this.cmdColor.s < 10) {
|
||||
// Saturation changed to < 10% = white mode
|
||||
targetMode = 'white'
|
||||
} else {
|
||||
// Saturation changed to >= 10% = color mode
|
||||
targetMode = 'colour'
|
||||
}
|
||||
} else {
|
||||
// For other cases stay in existing mode
|
||||
targetMode = this.dps[this.config.dpsMode].val
|
||||
}
|
||||
}
|
||||
|
||||
// Send the issued command
|
||||
this.set(command)
|
||||
|
||||
// Make sure the bulb stays in the correct mode
|
||||
if (targetMode) {
|
||||
command = {
|
||||
dps: this.config.dpsMode,
|
||||
set: targetMode
|
||||
}
|
||||
this.set(command)
|
||||
}
|
||||
}
|
||||
|
||||
// Simple function to help debug output
|
||||
toString() {
|
||||
return this.config.name+' (' +(this.options.ip ? this.options.ip+', ' : '')+this.options.id+', '+this.options.key+')'
|
||||
}
|
||||
|
||||
set(command) {
|
||||
debug('Set device '+this.options.id+' -> '+JSON.stringify(command))
|
||||
return new Promise((resolve, reject) => {
|
||||
this.device.set(command).then((result) => {
|
||||
resolve(result)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Search for and connect to device
|
||||
connectDevice() {
|
||||
// Find device on network
|
||||
debug('Search for device id '+this.options.id)
|
||||
this.device.find().then(() => {
|
||||
debug('Found device id '+this.options.id)
|
||||
// Attempt connection to device
|
||||
this.device.connect().catch((error) => {
|
||||
debugError(error.message)
|
||||
this.reconnect()
|
||||
})
|
||||
}).catch(async (error) => {
|
||||
debugError(error.message)
|
||||
debugError('Will attempt to find device again in 60 seconds')
|
||||
await utils.sleep(60)
|
||||
this.connectDevice()
|
||||
})
|
||||
}
|
||||
|
||||
// Retry connection every 10 seconds if unable to connect
|
||||
async reconnect() {
|
||||
if (!this.device.isConnected() && !this.reconnecting) {
|
||||
this.reconnecting = true
|
||||
debugError('Error connecting to device id '+this.options.id+'...retry in 10 seconds.')
|
||||
await utils.sleep(10)
|
||||
if (this.connected) { return }
|
||||
this.connectDevice()
|
||||
this.reconnecting = false
|
||||
}
|
||||
}
|
||||
|
||||
// Republish device discovery/state data (used for Home Assistant state topic)
|
||||
async republish() {
|
||||
const status = (this.device.isConnected()) ? 'online' : 'offline'
|
||||
this.publishMqtt(this.baseTopic+'status', status)
|
||||
await utils.sleep(1)
|
||||
this.init()
|
||||
}
|
||||
|
||||
// Republish device discovery/state data (used for Home Assistant state topic)
|
||||
async republish() {
|
||||
const status = (this.device.isConnected()) ? 'online' : 'offline'
|
||||
this.publishMqtt(this.baseTopic+'status', status)
|
||||
await utils.sleep(1)
|
||||
this.init()
|
||||
}
|
||||
|
||||
// Simple function to monitor heartbeats to determine if
|
||||
monitorHeartbeat() {
|
||||
setInterval(async () => {
|
||||
if (this.connected) {
|
||||
if (this.heartbeatsMissed > 3) {
|
||||
debugError('Device id '+this.options.id+' not responding to heartbeats...disconnecting')
|
||||
this.device.disconnect()
|
||||
await utils.sleep(1)
|
||||
this.connectDevice()
|
||||
} else if (this.heartbeatsMissed > 0) {
|
||||
const errMessage = this.heartbeatsMissed > 1 ? " consecutive heartbeats" : " heartbeat"
|
||||
debugError('Device id '+this.options.id+' has missed '+this.heartbeatsMissed+errMessage)
|
||||
}
|
||||
this.heartbeatsMissed++
|
||||
}
|
||||
}, 10000)
|
||||
}
|
||||
|
||||
// Publish MQTT
|
||||
publishMqtt(topic, message, isDebug) {
|
||||
if (isDebug) { debugState(topic, message) }
|
||||
this.mqttClient.publish(topic, message, { qos: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TuyaDevice
|
||||
213
docs/DEVICES.md
Normal file
213
docs/DEVICES.md
Normal file
@@ -0,0 +1,213 @@
|
||||
# tuya-mqtt - Devices
|
||||
The most powerful feature in tuya-mqtt is the ability to configure devices to use friendly topics. For some devices there exist pre-defined device templates which makes using those devices quite easy, simply add the type information to the devices.conf file and tuya-mqtt automatically creates friendly topics for that device.
|
||||
|
||||
Friendly topics make it easy to communicate with the device in a standard way and thus integrating into various Home Automation platforms. The topic style generally follows that used by the Home Assistant MQTT integration components and the pre-defined devices automatically send Home Assistant style MQTT discovery messages during startup to make integration with Home Assistant, or other platforms which understand Home Assistant MQTT discovery, even easier.
|
||||
|
||||
If the device does not have a pre-defined device template, it's possible to create a template using the [generic device template](#generic-device-templates) feature.
|
||||
|
||||
## Pre-defined Device Templates
|
||||
Pre-defined device templates (except for the Generic Device) will always expose friendly topics for the given device in a consistent manner. Currently the following pre-defined device templates are available:
|
||||
|
||||
| Device Type | Descrition |
|
||||
| --- | --- |
|
||||
| SimpleSwitch | Supports simple on/off devices |
|
||||
| SimpleDimmer | Supports simple devices with on/on and brightness |
|
||||
| RGBTWLight | Supports color/white lights with optional color temerature support |
|
||||
| GenericDevice | Allows defining a custom template for any device |
|
||||
|
||||
To use a device template, simply add the "type" option to the devices.conf similar to the following example:
|
||||
```
|
||||
[
|
||||
{
|
||||
name: 'Tuya Device 1',
|
||||
id: '86435357d8b123456789',
|
||||
key: '8b2a69c9876543210',
|
||||
type: 'RGBTWLight'
|
||||
}
|
||||
]
|
||||
```
|
||||
Once the device type is defined tuya-mqtt will attempt to create friendly topics for that device type on connection to the device. Each device type defines specific defaults for DPS values which are typical for common Tuya devices and some, like RGBTWLight, have logic to attempt to detect different variation by querying the device. The goal is that, in most cases, simply adding the type is all that is needed, however, in many cases it is also possible to override the manual settings for the device. The device friendly topics and options for each device are documented below.
|
||||
|
||||
### SimpleSwitch
|
||||
Simple devices that support only on/off.
|
||||
| Topic | Description | Values |
|
||||
| --- | --- | --- |
|
||||
| state | Power state | on/off |
|
||||
| command | Set power state | on/off, 0/1, true/false |
|
||||
|
||||
Manual configuration options:
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| dpsPower | DPS key for power state | 1 |
|
||||
|
||||
### SimpleDimmer
|
||||
Simple device with on/off and brightness functions (dimmer switches or lights)
|
||||
| Topic | Description | Values |
|
||||
| --- | --- | --- |
|
||||
| state | Power state | on/off |
|
||||
| command | Set power state | on/off, 0/1, true/false |
|
||||
| brightness_state | Brightness in % | 0-100 |
|
||||
| brightness_command | set brightness in % | 0-100 |
|
||||
|
||||
Manual configuration options:
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| dpsPower | DPS key for power state | 1 |
|
||||
| dpsBrightness | DPS key for brightness state | 2 |
|
||||
| brightnessScale | Scale for brightness DPS value | 255 |
|
||||
|
||||
### RGBTWLight
|
||||
The RGBTWLight device support Tuya color lights (bulbs and LEDs). Tuya lights operate in either white or color mode. The RGBTWLight device automatically switches between modes on certain conditions as documented below:
|
||||
| Condition | Mode |
|
||||
| --- | --- |
|
||||
| Changes white brightness | white |
|
||||
| Changes to color temperature (for device with color temp support) | white |
|
||||
| Saturation < 10 % | white |
|
||||
| Saturation >= 10 % | color |
|
||||
| All other changes | current mode |
|
||||
|
||||
This means changing the hue of the light will only switch to color mode if saturation is also >= 10%. Some lights automatically attempt to switch to color mode when any HSB value is updated however, if the saturation setting remains < 10%, tuya-mqtt will force the light back to white mode in this case. This can cause a very quick flicker when chaning hue or color brightness while the saturation remains below the 10% threshold. I expect this not to be a common issue and implemented this in an attempt to make all tuya lights behave in a consistent way.
|
||||
|
||||
When the bulb is in white mode, saturation values in the friendly topics are always reported as 0%. This is true even if the mode is toggled manually from color to white mode using the mode_command topic or the Tuya/SmartLife app. When the light is toggled back to color mode, saturation will be reported at the correct level. This is done primarly as a means to indicate color state to automation platforms that don't have a concept of white/color mode, otherwise a light in white mode may still be represented with a color icon in the platforms UI.
|
||||
|
||||
Not all devices support color temperature and the script attempts to detect this capability and enables the color temperature topics only when found. Color temperature topics report in Mireds (commonly used by automation tools) and the default range supports roughly 2500K-6500K. This works reasonably well for most available Tuya devices, even if they are not exactly in this range, but, if you know a devices specific color range, the limits can be manually specified to more accurately reflect the exact color temperature.
|
||||
|
||||
Tuya bulbs store their HSB color value in a single DPS key using a custom format. Some bulbs use a 14 character format, referred to as HSBHEX, which represents the saturation and brightness values from 0-255 as 2 character hex, while the others use a 12 character format, referred to as HSB, which still uses hex values, but stores saturation and brightness values from 0-1000 as 4 character hex. The code attempts to autodetect the format used by the bulb and perform the proper conversion in all cases, but this can be overridden for cases where the dection method fails.
|
||||
|
||||
| Topic | Description | Values |
|
||||
| --- | --- | --- |
|
||||
| state | Power state | on/off |
|
||||
| command | Set power state | on/off, 0/1, true/false |
|
||||
| white_brightness_state | White mode brightness in % | 0-100 |
|
||||
| white_brightness_command | Set white mode brightness in % | 0-100 |
|
||||
| color_brightness_state | Color mode brightness in % | 0-100 |
|
||||
| color_brightness_command | Set white mode brightness in % | 0-100 |
|
||||
| hs_state | Hue, saturation % | H,S (Hue 0-360, Saturation 0-100) |
|
||||
| hs_command | Set hue, saturation % | H,S (Hue 0-360, Saturation 0-100) |
|
||||
| hsb_state | Hue, saturation %, brightness % | H,S,B (Hue 0-360, Saturation 0-100, Brightness 0-100) |
|
||||
| hsb_command | Set hue, saturation %, brightness % | H,S,B (Hue 0-360, Saturation 0-100, Brightness 0-100) |
|
||||
| mode_state | White/Color mode | 'white', 'colour' (some devices also support scenes here) |
|
||||
| mode_command | Set white/color mode | 'white', 'colour' (some devices also support scenes here) |
|
||||
| color_temp_state | Color temperature in mireds (only available if device support color temp) | 154-400 (defult range, can be overridden) |
|
||||
| color_temp_command | Set color temperature in mireds (only available if device support color temp) | 154-400 (defult range, can be overridden) |
|
||||
|
||||
Manual configuration options:
|
||||
| Option | Description | Default (common detected values) |
|
||||
| --- | --- | --- |
|
||||
| dpsPower | DPS key for power state | Auto Detect (1,20) |
|
||||
| dpsMode | DPS key for white/color mode state | Auto Detect (2,21) |
|
||||
| dpsWhiteValue | DPS key for white mode brightness | Auto Detect (3,22) |
|
||||
| whiteValueScale | White mode brightness DPS scale | Auto Detect (255, 1000) |
|
||||
| dpsColorTemp | DPS key for color temperature | Auto Detect (4,23) |
|
||||
| minColorTemp | Min color temperature in Mireds | 154 (~6500K) |
|
||||
| maxColorTemp | Max color temperature in Mireds | 400 (~2500K) |
|
||||
| colorTempScale | Color temperature DPS key scale | Auto Detect (255, 1000) |
|
||||
| dpsColor | DPS key for HSB color values | Auto Detect (5,24) |
|
||||
| colorType | Tuya color format for color DPS key | Auto Detect (hsb, hsbhex) |
|
||||
|
||||
To use the manual configuration options simply add them to device.conf file after defining the device type like the following example:
|
||||
```
|
||||
[
|
||||
{
|
||||
name: 'Tuya Device 1',
|
||||
id: '86435357d8b123456789',
|
||||
key: '8b2a69c9876543210',
|
||||
type: 'RGBTWLight',
|
||||
dpsPower: 31,
|
||||
dpsMode: 32,
|
||||
dpsWhiteValue: 33,
|
||||
whiteValueScale: 255,
|
||||
dpsColorTemp: 34,
|
||||
minColorTemp: 165,
|
||||
maxColorTemp: 385,
|
||||
colorTempScale: 255,
|
||||
dpsColor: 34,
|
||||
colorType: 'hsbhex'
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## Generic Device Templates
|
||||
If a pre-defined device tempate does not exist for the device, or does not expose all capabilities of the device, there are still mulitple options available to control the devices. One method is to use the DPS topics directly to control the device using either native Tuya JSON commands or via the DPS key values by using the DPS key topics (see [DPS Topics](TOPICS.md#dps-topics)). The second method is to create a template for your device to map DPS key values to friendly topics. The GenericDevice type allows you to manually create a template for any device using the same templating engine as the pre-defined device templates. Once you've created a tempalte for your device, it can be re-used with other, similar devices and you can submit your template to the tuya-mqtt project for other to use, or even for inclusion at a pre-defined device template in the future.
|
||||
|
||||
Creating a device template is relatively straightforward, but first you must know what DPS keys your devices uses. The GenericDevice attempts to query all device DPS states on startup, but some devices to not respond to this command, however, the generic device will ALWAYS report any DPS topics from which it receives upated. The easiest way to determine how your device uses it's DPS topics is to connect to the MQTT broker via a tool like MQTT Explorer or mosquitto_sub, and watch the topics as you manipulate the device with the Tuya/Smartlife app.
|
||||
|
||||
Once you have a reasonable idea of how the device uses it's DPS key values, you can create a template. A simple template for a dimmer looks something like this:
|
||||
```
|
||||
[
|
||||
{
|
||||
name: 'Tuya Device 1',
|
||||
id: '86435357d8b123456789',
|
||||
key: '8b2a69c9876543210',
|
||||
template: {
|
||||
state: {
|
||||
key: 1,
|
||||
type: 'bool'
|
||||
},
|
||||
brightness_state: {
|
||||
key: 2,
|
||||
type: 'int',
|
||||
topicMin: 1,
|
||||
topicMax: 100,
|
||||
stateMath: '/2.55',
|
||||
commandMath: '*2.55'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
The template above defines two topics "state" and "brightness_state", and the template engine automatically creates the corresponding command topics, in this case specifically "command" and "brightness_command".
|
||||
|
||||
The "state" topic maps to DPS key 1, and uses a bool (true/false) value in the DPS key. Now you will be able to see "on/off" state in the state topic instead of having to read the true/false value from the DPS/1 topic
|
||||
|
||||
The the "brightness_state" topic maps to DPS key 2, and this value defines the brightness using an integer in the 1-255 scale. We define the value as an integer (type: 'int') and the stateMath and commandMath values allow transforming the raw DPS value into a more friendly value that will be presented in the topic. In this case the raw DPS value will be divided by 2.55 before being published to the state, and and received commands will be mulitpled by that same value, converting the 1-255 to a simple 1-100 scale. Note that the topicMin and topicMax values set the minimum and maximum values that the state topic will report and that the command topic will accept. These values are "post-math" for state topics, and "pre-math" for command topics.
|
||||
|
||||
The following tables define the available template value types and their options:
|
||||
|
||||
### Boolean values
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'bool' |
|
||||
| key | DPS key of the value |
|
||||
|
||||
### Integer values
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'int' |
|
||||
| key | DPS key of the value |
|
||||
| topicMin | Minumum value allowed for the command topic |
|
||||
| topicMax | Maximum value allowed for the command topic |
|
||||
| stateMath | Simple math applied to the DPS key value before being published to state topic |
|
||||
| commandMath | Simple math applied to command value before being set to DPS key |
|
||||
|
||||
### Floating point values
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'float' |
|
||||
| key | DPS key of the value |
|
||||
| topicMin | Minumum value allowed for the command topic |
|
||||
| topicMax | Maximum value allowed for the command topic |
|
||||
| stateMath | Simple math applied to the DPS key value before being published to state topic |
|
||||
| commandMath | Simple math applied to command value before being set to DPS key |
|
||||
|
||||
### String values
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'str' |
|
||||
| key | DPS key of the value |
|
||||
|
||||
### Tuya HSB values (newer style Tuya, 12 character color value)
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'hsb' |
|
||||
| key | DPS key of the value |
|
||||
| components | Comma separated list of HSB components that should be included in this topic |
|
||||
|
||||
### Tuya HSBHEX values (older style Tuya 14 character color value)
|
||||
| option | value |
|
||||
| --- | --- |
|
||||
| type | 'hsbhex' |
|
||||
| key | DPS key of the value |
|
||||
| components | Comma separated list of HSB components that should be included in this topic |
|
||||
|
||||
Using these value types you can define templates for a wide range of devices. Additional types and options are likely to be included in future versions of tuya-mqtt.
|
||||
142
docs/openHAB.md
Normal file
142
docs/openHAB.md
Normal file
@@ -0,0 +1,142 @@
|
||||
:exclamation: There is a greate Step-By-Step guide from user HolgiHab at openhab community ([Step-By-Step Guide](
|
||||
https://community.openhab.org/t/step-by-step-guide-for-adding-tuya-bulbs-smart-life-to-oh2-using-tuya-mqtt-js-by-agentk/59371)). This guide is not only for light bulbs, but also applies to sockets. :exclamation:
|
||||
|
||||
## Example items for OpenHAB 1.x Bindings (still works with OH > 2.4 but only if legacy 1.x MQTT bindings are enabled)
|
||||
### simple switch on/off
|
||||
```
|
||||
|
||||
Switch tuya_kitchen_coffeemachine_mqtt "Steckdose Kaffeemaschine" <socket> (<GROUPS>) ["Switchable"] {
|
||||
mqtt="<[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state:state:default:.*],
|
||||
>[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/on:command:ON:true],
|
||||
>[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/off:command:OFF:false]"
|
||||
}
|
||||
|
||||
Switch tuya_livingroom_ledstrip_tv "LED Regal" <lightbulb> (<GROUPS>) ["Lighting"] {
|
||||
mqtt="<[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state:state:default:.*],
|
||||
>[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/on:command:ON:true],
|
||||
>[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command/off:command:OFF:false]"
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### change color of lightbulb
|
||||
```
|
||||
|
||||
# .items
|
||||
Group gTuyaLivingColor "Tuya color group" <lightbulb>
|
||||
Color tuya_livingroom_colorpicker "Stehlampe farbe" (LivingDining)
|
||||
|
||||
String tuya_livingroom_ledstrip_tv_color "Set color [%s]" (gTuyaLivingColor, LivingDining) {
|
||||
mqtt=">[broker:tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/color:command:*:default]"
|
||||
}
|
||||
|
||||
|
||||
|
||||
# .rules
|
||||
import org.openhab.core.library.types.HSBType;
|
||||
|
||||
rule "Set HSB value of item RGBLed to RGB color value"
|
||||
when
|
||||
Item tuya_livingroom_colorpicker received command
|
||||
then
|
||||
var appName = "Colorpicker.livingroom"
|
||||
var color = receivedCommand.toString;
|
||||
|
||||
// get all colors and send it via mqtt if light ist enabled
|
||||
gTuyaLivingColor.members.forEach[ i |
|
||||
var name = i.name;
|
||||
var stateName = name.toString.split("_color").get(0);
|
||||
var stateItem = gTuyaLights.allMembers.filter [ conf | conf.name.contains(stateName.toString) ].head;
|
||||
|
||||
if(stateItem.state == ON){
|
||||
logInfo(appName, name + " change to color: " + color);
|
||||
i.sendCommand(color);
|
||||
Thread::sleep(400);
|
||||
}
|
||||
]
|
||||
end
|
||||
|
||||
```
|
||||
|
||||
## Example items for OpenHAB 2.4 Bindings
|
||||
### simple switch on/off
|
||||
|
||||
With OpenHAB 2.X MQTT bindings you can add devices using a generic MQTT Thing via PaperUI or
|
||||
configuration files. For PaperUI simply at the generic MQTT Thing and set the state and
|
||||
command topics as follows:
|
||||
```
|
||||
|
||||
tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state
|
||||
|
||||
tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command
|
||||
|
||||
```
|
||||
|
||||
If you prefer using configuration files vs PaperUI, it should look something like this:
|
||||
See also OpenHAB 2.X MQTT binding [documentation](https://www.openhab.org/v2.4/addons/bindings/mqtt.generic/)
|
||||
|
||||
```
|
||||
|
||||
Bridge mqtt:broker:myUnsecureBroker [ host="localhost", secure=false ]
|
||||
{
|
||||
|
||||
Thing mqtt:topic:myCustomMQTT {
|
||||
Channels:
|
||||
Type switch : tuya_kitchen_coffeemachine_mqtt_channel "Kitchen Coffee Machine MQTT Channel" [
|
||||
stateTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state",
|
||||
commandTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command",
|
||||
|
||||
// optional custom mqtt-payloads for ON and OFF
|
||||
on="{ \"dps\": 1, \"set\": true }",
|
||||
off="0"
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
# *.item Example
|
||||
Switch tuya_kitchen_coffeemachine_mqtt "Kitchen Coffee Machine Switch" <socket> (gKitchen, gTuya) ["Switchable"] {
|
||||
channel="mqtt:topic:myUnsecureBroker:myCustomMQTT:tuya_kitchen_coffeemachine_mqtt_channel"
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
For one RGB bulb you would need a separate channel with the command topic set to
|
||||
`tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/color` and link that to your color item.
|
||||
|
||||
```
|
||||
|
||||
Bridge mqtt:broker:myUnsecureBroker [ host="localhost", secure=false ]
|
||||
{
|
||||
Thing mqtt:topic:myCustomMQTT {
|
||||
Channels:
|
||||
Type colorHSB : livingroom_floorlamp_1_color "Livingroom floorlamp color MQTT Channel" [
|
||||
stateTopic="tuya/05200399bcddc2e02ec9/b58cf92e8bc5c899/192.168.178.49/state",
|
||||
commandTopic="tuya/05200399bcddc2e02ec9/b58cf92e8bc5c899/192.168.178.49/color"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# *.item Example
|
||||
Color tuya_livingroom_colorpicker "Floorlamp colorpicker" (gLivingroom){
|
||||
channel="mqtt:topic:myUnsecureBroker:myCustomMQTT:livingroom_floorlamp_1_color"
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### Basic UI sitemap
|
||||
```
|
||||
|
||||
Switch item=tuya_kitchen_coffeemachine_mqtt
|
||||
|
||||
# turn the color bulb off or on
|
||||
Switch item=tuya_livingroom_colorpicker label="RGB lamp [%s]"
|
||||
|
||||
# pick the color level to send to the color bulb via MQTT color Channel
|
||||
Slider item=tuya_livingroom_colorpicker label="RGB lamp level [%s]" minValue=0 maxValue=100 step=1
|
||||
|
||||
# color picked and sent via MQTT Color channel
|
||||
Colorpicker item=tuya_livingroom_colorpicker label="RGB lamp color [%s]" icon="colorpicker" sendFrequency=30000
|
||||
|
||||
|
||||
```
|
||||
28
lib/utils.js
Normal file
28
lib/utils.js
Normal file
@@ -0,0 +1,28 @@
|
||||
class Utils
|
||||
{
|
||||
|
||||
// Check if data is JSON or not
|
||||
isJsonString(data) {
|
||||
try {
|
||||
const parsedData = JSON.parse(data)
|
||||
if (parsedData && typeof parsedData === "object") {
|
||||
return parsedData
|
||||
}
|
||||
}
|
||||
catch (e) { }
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Simple sleep function for various required delays
|
||||
sleep(sec) {
|
||||
return new Promise(res => setTimeout(res, sec*1000))
|
||||
}
|
||||
|
||||
msSleep(ms) {
|
||||
return new Promise(res => setTimeout(res, ms))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = new Utils()
|
||||
116
merge-devices.js
Normal file
116
merge-devices.js
Normal file
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env node
|
||||
const fs = require('fs');
|
||||
const json5 = require('json5');
|
||||
const utils = require('./lib/utils');
|
||||
|
||||
// Setup Exit Handlers
|
||||
process.on('exit', processExit.bind(0));
|
||||
process.on('SIGINT', processExit.bind(0));
|
||||
process.on('SIGTERM', processExit.bind(0));
|
||||
process.on('uncaughtException', processExit.bind(1));
|
||||
|
||||
async function processExit(exitCode) {
|
||||
if (exitCode || exitCode === 0)
|
||||
console.error('Exit code: ' + exitCode)
|
||||
process.exit();
|
||||
}
|
||||
|
||||
// Main code function
|
||||
const main = async() => {
|
||||
const date = new Date();
|
||||
const dateTimeStr = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2) + '_' + ("0" + date.getHours()).slice(-2) + ("0" + date.getMinutes()).slice(-2) + ("0" + date.getSeconds()).slice(-2);
|
||||
const configDevicesFilename = 'devices.conf';
|
||||
const configDevicesBackupFilename = `${configDevicesFilename}_${dateTimeStr}.bak`;
|
||||
const configNewDevicesFilename = `new-${configDevicesFilename}`;
|
||||
|
||||
let configDevices;
|
||||
let configNewDevices;
|
||||
|
||||
try {
|
||||
console.log(`Loading ${configNewDevicesFilename}...`);
|
||||
configNewDevices = fs.readFileSync(`./${configNewDevicesFilename}`, 'utf8');
|
||||
configNewDevices = json5.parse(configNewDevices);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`Could not parse new devices config file [${configNewDevicesFilename}]!`);
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Loading ${configDevicesFilename}...`);
|
||||
configDevices = fs.readFileSync(`./${configDevicesFilename}`, 'utf8');
|
||||
configDevices = json5.parse(configDevices);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`Could not parse devices config file [${configDevicesFilename}]!`);
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Backing up devices config file [${configDevicesFilename}] to [${configDevicesBackupFilename}]...`);
|
||||
fs.copyFileSync(`./${configDevicesFilename}`, `./${configDevicesBackupFilename}`);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`Could not make backup of devices config file [${configDevicesFilename}] to [${configDevicesBackupFilename}].`);
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('Indexing devices...');
|
||||
|
||||
// Create a dictionary for faster lookups with many devices
|
||||
const configDevicesDictionary = {};
|
||||
for (let configDevice of configDevices) {
|
||||
configDevicesDictionary[configDevice.id] = configDevice;
|
||||
}
|
||||
|
||||
console.log('Merging devices...');
|
||||
|
||||
// Add new devices and update existing devices
|
||||
for (let configNewDevice of configNewDevices) {
|
||||
let configDevice = configDevicesDictionary[configNewDevice.id];
|
||||
if (configDevice == null) {
|
||||
// Add new device
|
||||
console.log(`Adding device: ${configNewDevice.name} (id: ${configNewDevice.id})...`);
|
||||
configDevices.push(configNewDevice);
|
||||
configDevicesDictionary[configNewDevice.id] = configNewDevice;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (configDevice.allowMerge === false)
|
||||
continue; // No merge updates allowed for this device
|
||||
|
||||
// Update existing device
|
||||
if (configDevice.name !== configNewDevice.name) {
|
||||
console.log(`Updating device name: '${configDevice.name}' to '${configNewDevice.name}' (device id: ${configDevice.key})...`);
|
||||
configDevice.name = configNewDevice.name;
|
||||
}
|
||||
if (configDevice.key !== configNewDevice.key) {
|
||||
console.log(`Updating device key for: '${configDevice.name}' (device id: ${configDevice.key})...`);
|
||||
configDevice.key = configNewDevice.key;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the devices by name
|
||||
configDevices.sort((a, b) => a.name < b.name ? -1 : 1);
|
||||
const configDevicesJson = json5.stringify(configDevices, { space: ' ', quote: '"' });
|
||||
|
||||
//console.log(configDevicesJson);
|
||||
|
||||
try {
|
||||
console.log(`Saving devices config file [${configDevicesFilename}]...`);
|
||||
fs.writeFileSync(`./${configDevicesFilename}`, configDevicesJson, { encoding: 'utf8' });
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`Could not write devices config file [${configDevicesFilename}]!`)
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log('Done!');
|
||||
}
|
||||
|
||||
// Call the main code
|
||||
main();
|
||||
2287
package-lock.json
generated
2287
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
26
package.json
26
package.json
@@ -1,18 +1,26 @@
|
||||
{
|
||||
"name": "tuya-api",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "tuya.js",
|
||||
"name": "tuya-mqtt",
|
||||
"version": "3.0.2",
|
||||
"description": "Control Tuya devices locally via MQTT",
|
||||
"homepage": "https://github.com/TheAgentK/tuya-mqtt#readme",
|
||||
"main": "tuya-mqtt.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"author": {
|
||||
"name": "TheAgentK",
|
||||
"email": "lulattsch22@googlemail.com"
|
||||
},
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"color-convert": "^1.9.3",
|
||||
"debug": "^3.2.6",
|
||||
"mqtt": "^2.18.8",
|
||||
"tuyapi": "^3.2.3"
|
||||
"@tuyapi/cli": "^1.13.6",
|
||||
"color-convert": "^2.0.1",
|
||||
"debug": "^4.3.1",
|
||||
"json5": "^2.1.3",
|
||||
"mqtt": "^4.2.6",
|
||||
"supports-color": "^8.1.0",
|
||||
"tuyapi": "^6.1.2",
|
||||
"mathjs": "8.1.1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
247
tuya-color.js
247
tuya-color.js
@@ -1,247 +0,0 @@
|
||||
const convert = require('color-convert');
|
||||
const debug = require('debug')('TuyaColor');
|
||||
|
||||
/**
|
||||
* Class to calculate settings for Tuya colors
|
||||
*/
|
||||
function TuyaColorLight() {
|
||||
|
||||
this.colorMode = 'white'; // or 'colour'
|
||||
this.brightness = 100; // percentage value use _convertValToPercentage functions below.
|
||||
|
||||
this.color = {
|
||||
H: 130,
|
||||
S: 100,
|
||||
L: 50
|
||||
};
|
||||
|
||||
this.hue = this.color.H;
|
||||
this.saturation = this.color.S;
|
||||
this.lightness = this.color.L;
|
||||
|
||||
this.colorTemperature = 255;
|
||||
this.colorTempMin = 153;
|
||||
this.colorTempMax = 500;
|
||||
|
||||
this.dps = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* calculate color value from given percentage
|
||||
* @param {Integer} percentage 0-100 percentage value
|
||||
* @returns {Integer} color value from 0-255
|
||||
*/
|
||||
TuyaColorLight.prototype._convertPercentageToVal = function (percentage) {
|
||||
var tmp = Math.round(255 * (percentage / 100));
|
||||
debug('Converted ' + percentage + ' to: ' + tmp);
|
||||
return tmp;
|
||||
};
|
||||
|
||||
/**
|
||||
* calculate percentage from color value
|
||||
* @param {Integer} val 0-255 color value
|
||||
* @returns {Integer} HK-Value
|
||||
*/
|
||||
TuyaColorLight.prototype._convertValToPercentage = function (val) {
|
||||
var tmp = Math.round((val / 255) * 100);
|
||||
debug('Converted ' + val + ' to: ' + tmp);
|
||||
return tmp;
|
||||
};
|
||||
|
||||
/**
|
||||
* converts color value to color temperature
|
||||
* @param {Integer} val
|
||||
* @returns {Integer} percentage from 0-100
|
||||
*/
|
||||
TuyaColorLight.prototype._convertColorTemperature = function (val) {
|
||||
var tmpRange = this.colorTempMax - this.colorTempMin;
|
||||
var tmpCalc = Math.round((val / this.colorTempMax) * 100);
|
||||
|
||||
debug('HK colorTemp Value: ' + val);
|
||||
debug('HK colorTemp scale min : ' + this.colorTempMin);
|
||||
debug('HK colorTemp scale max : ' + this.colorTempMax);
|
||||
debug('HK colorTemp range (tmpRange): ' + tmpRange);
|
||||
debug('HK colorTemp % tmpCalc: ' + tmpCalc);
|
||||
|
||||
var tuyaColorTemp = this._convertPercentageToVal(tmpCalc);
|
||||
|
||||
debug('HK tuyaColorTemp: ' + tuyaColorTemp);
|
||||
|
||||
return tuyaColorTemp;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert color temperature to HK
|
||||
* @param {Integer} val
|
||||
* @returns {Integer} HK-Value
|
||||
*/
|
||||
TuyaColorLight.prototype._convertColorTemperatureToHK = function (val) {
|
||||
|
||||
var tuyaColorTempPercent = this._convertValToPercentage(this.colorTemperature);
|
||||
var tmpRange = this.colorTempMax - this.colorTempMin;
|
||||
var tmpCalc = Math.round((tmpRange * (tuyaColorTempPercent / 100)) + this.colorTempMin);
|
||||
var hkValue = Math.round(tmpCalc);
|
||||
|
||||
debug('Tuya color Temperature : ' + val);
|
||||
debug('Tuya color temp Percent of 255: ' + tuyaColorTempPercent + '%');
|
||||
|
||||
debug('HK colorTemp scale min : ' + this.colorTempMin);
|
||||
debug('HK colorTemp scale max : ' + this.colorTempMax);
|
||||
|
||||
debug('HK Color Temp Range: ' + tmpRange);
|
||||
debug('HK range %: ' + tuyaColorTempPercent);
|
||||
debug('HK Value: ' + hkValue);
|
||||
|
||||
return hkValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* check if given String is HEX
|
||||
* @param {String} h
|
||||
* @returns {boolean}
|
||||
*/
|
||||
TuyaColorLight.prototype._ValIsHex = function (h) {
|
||||
debug("Check if value is hex", h);
|
||||
return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(h)
|
||||
};
|
||||
|
||||
/**
|
||||
* get AlphaHex from percentage brightness
|
||||
* @param {Integer} brightness
|
||||
* @return {string} brightness as HEX value
|
||||
*/
|
||||
TuyaColorLight.prototype._getAlphaHex = function (brightness) {
|
||||
var i = brightness / 100;
|
||||
var alpha = Math.round(i * 255);
|
||||
var hex = (alpha + 0x10000).toString(16).substr(-2);
|
||||
var perc = Math.round(i * 100);
|
||||
|
||||
debug('alpha percent: ' + perc + '% hex: ' + hex + ' alpha: ' + alpha);
|
||||
return hex;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set saturation from value
|
||||
* @param {Integer} value
|
||||
*/
|
||||
TuyaColorLight.prototype.setSaturation = function (value) {
|
||||
this.color.S = value;
|
||||
this.saturation = value;
|
||||
this.colorMode = 'colour';
|
||||
|
||||
debug('SET SATURATION: ' + value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Set Brightness
|
||||
* @param {Integer} value
|
||||
*/
|
||||
TuyaColorLight.prototype.setBrightness = function (value) {
|
||||
this.brightness = value;
|
||||
var newValue = this._convertPercentageToVal(value);
|
||||
debug("BRIGHTNESS from UI: " + value + ' Converted from 100 to 255 scale: ' + newValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {} value
|
||||
*/
|
||||
TuyaColorLight.prototype.setHue = function (value) {
|
||||
debug('SET HUE: ' + value);
|
||||
debug('Saturation Value: ' + this.color.S);
|
||||
this.color.H = value;
|
||||
|
||||
//check color and set colormode if necessary
|
||||
debug("colormode", value, this.color.S);
|
||||
if (value === 0 && this.color.S === 0) {
|
||||
this.colorMode = 'white';
|
||||
debug('SET Color Mode: \'white\'');
|
||||
} else {
|
||||
this.colorMode = 'colour';
|
||||
debug('SET Color Mode: \'colour\' -- dahhhhhh british spelling \'coulour\' really is annoying... why you gotta be special?');
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
color: this.color,
|
||||
colorMode: this.colorMode,
|
||||
hue: this.color.H,
|
||||
saturation: this.saturation
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Set HSL color
|
||||
* @param {Integer} hue
|
||||
* @param {Integer} saturation
|
||||
* @param {Integer} brightness
|
||||
*/
|
||||
TuyaColorLight.prototype.setHSL = function (hue, saturation, brightness) {
|
||||
this.setSaturation(saturation);
|
||||
this.setBrightness(brightness);
|
||||
this.setHue(hue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set color from given string
|
||||
* @param {String} colorValue could be HEX or HSL color type
|
||||
* @returns {Object} dps settings for given color
|
||||
*/
|
||||
TuyaColorLight.prototype.setColor = function (colorValue) {
|
||||
debug("Recieved color", colorValue);
|
||||
|
||||
if (this._ValIsHex(colorValue)) {
|
||||
debug("Color is Hex");
|
||||
var color = convert.hex.hsl(colorValue);
|
||||
} else {
|
||||
debug("Color is HSL");
|
||||
var color = colorValue.split(",");
|
||||
// convert strings to numbers
|
||||
color.forEach(function (element, key) {
|
||||
color[key] = parseInt(element, 10);
|
||||
});
|
||||
}
|
||||
debug("Converted color as HSL", {
|
||||
0: color[0] + " - " + typeof color[0],
|
||||
1: color[1] + " - " + typeof color[1],
|
||||
2: color[2] + " - " + typeof color[2]
|
||||
})
|
||||
|
||||
this.setHSL(color[0], color[1], color[2]);
|
||||
return this.getDps();
|
||||
}
|
||||
|
||||
/**
|
||||
* get dps settings for current color
|
||||
* @returns {Object} dps settings
|
||||
*/
|
||||
TuyaColorLight.prototype.getDps = function () {
|
||||
var color = this.color;
|
||||
|
||||
var lightness = Math.round(this.brightness / 2);
|
||||
var brightness = this.brightness;
|
||||
var apiBrightness = this._convertPercentageToVal(brightness);
|
||||
var alphaBrightness = this._getAlphaHex(brightness);
|
||||
|
||||
var hexColor1 = convert.hsl.hex(color.H, color.S, lightness);
|
||||
|
||||
var hexColor2 = convert.hsl.hex(0, 0, lightness);
|
||||
|
||||
var colorTemperature = this.colorTemperature;
|
||||
|
||||
var lightColor = (hexColor1 + hexColor2 + alphaBrightness).toLowerCase();
|
||||
|
||||
var temperature = (this.colorMode === 'colour') ? 255 : this._convertColorTemperature(colorTemperature);
|
||||
|
||||
dpsTmp = {
|
||||
'1': true,
|
||||
'2': this.colorMode,
|
||||
'3': apiBrightness,
|
||||
'4': temperature,
|
||||
'5': lightColor
|
||||
// '6' : hexColor + hexColor + 'ff'
|
||||
};
|
||||
debug("dps", dpsTmp);
|
||||
return dpsTmp;
|
||||
}
|
||||
|
||||
module.exports = TuyaColorLight;
|
||||
229
tuya-device.js
229
tuya-device.js
@@ -1,229 +0,0 @@
|
||||
const TuyAPI = require('tuyapi');
|
||||
const TuyColor = require('./tuya-color');
|
||||
const debug = require('debug')('TuyAPI-device');
|
||||
const debugColor = require('debug')('TuyAPI-device-color');
|
||||
const debugTimer = require('debug')('TuyAPI-device-timer');
|
||||
|
||||
/**
|
||||
*
|
||||
var steckdose = new TuyaDevice({
|
||||
id: '03200240600194781244',
|
||||
key: 'b8bdebab418f5b55',
|
||||
ip: '192.168.178.45',
|
||||
type: "socket"
|
||||
});
|
||||
*/
|
||||
|
||||
var TuyaDevice = (function () {
|
||||
var devices = [];
|
||||
var events = {};
|
||||
|
||||
var autoTimeout = undefined;
|
||||
|
||||
function checkExisiting(id) {
|
||||
var existing = false;
|
||||
// Check for existing instance
|
||||
devices.forEach(device => {
|
||||
if (device.hasOwnProperty("options")) {
|
||||
if (id === device.options.id) {
|
||||
existing = device;
|
||||
}
|
||||
}
|
||||
});
|
||||
return existing;
|
||||
}
|
||||
|
||||
function resetTimer() {
|
||||
return;
|
||||
debugTimer("Reset timer for auto disconnect all devices");
|
||||
clearTimeout(autoTimeout);
|
||||
autoTimeout = setTimeout(() => {
|
||||
debugTimer("Auto disconnect all devices");
|
||||
TuyaDevice.disconnectAll();
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
function TuyaDevice(options) {
|
||||
var device = this;
|
||||
// Check for existing instance
|
||||
if (existing = checkExisiting(options.id)) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (!(this instanceof TuyaDevice)) {
|
||||
return new TuyaDevice(options);
|
||||
}
|
||||
|
||||
options.type = options.type || "socket";
|
||||
options.persistentConnection = true;
|
||||
|
||||
Object.defineProperty(this, 'type', {
|
||||
value: options.type
|
||||
});
|
||||
|
||||
Object.defineProperty(this, 'options', {
|
||||
value: options
|
||||
});
|
||||
|
||||
Object.defineProperty(this, 'device', {
|
||||
value: new TuyAPI(this.options)
|
||||
});
|
||||
|
||||
this.device.on('connected', () => {
|
||||
debug('Connected to device.');
|
||||
device.triggerAll('connected');
|
||||
});
|
||||
|
||||
this.device.on('disconnected', () => {
|
||||
debug('Disconnected from device.');
|
||||
device.triggerAll('disconnected');
|
||||
});
|
||||
|
||||
this.device.on('data', data => {
|
||||
debug('Data from device:', data);
|
||||
device.triggerAll('data', data);
|
||||
});
|
||||
|
||||
this.device.on('error', (err) => {
|
||||
debug('Error: ' + err);
|
||||
device.triggerAll('error', err);
|
||||
});
|
||||
|
||||
this.device.connect();
|
||||
devices.push(this);
|
||||
resetTimer();
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.triggerAll = function (name, argument) {
|
||||
var device = this;
|
||||
var e = events[name] || [];
|
||||
e.forEach(event => {
|
||||
event.call(device, argument);
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.on = function (name, callback) {
|
||||
var device = this;
|
||||
this.device.on(name, function () {
|
||||
callback.apply(device, arguments);
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.get = function (options) {
|
||||
resetTimer();
|
||||
return this.device.get(options);
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.set = function (options, callback) {
|
||||
var device = this;
|
||||
debug('Setting status:', options);
|
||||
return this.device.set(options).then(result => {
|
||||
device.get().then(status => {
|
||||
debug('Result of setting status to', status);
|
||||
if (callback != undefined) {
|
||||
callback.call(device, status);
|
||||
}
|
||||
return;
|
||||
});
|
||||
});
|
||||
resetTimer();
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.switch = function (newStatus, callback) {
|
||||
newStatus = newStatus.toLowerCase();
|
||||
debug("switch: " + newStatus);
|
||||
if (newStatus == "on") {
|
||||
this.switchOn(callback);
|
||||
}
|
||||
if (newStatus == "off") {
|
||||
this.switchOff(callback);
|
||||
}
|
||||
if (newStatus == "toggle") {
|
||||
this.toggle(callback);
|
||||
}
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.switchOn = function (callback) {
|
||||
var device = this;
|
||||
debug("switch -> ON");
|
||||
device.get().then(status => {
|
||||
device.set({
|
||||
set: true
|
||||
}, callback);
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.switchOff = function (callback) {
|
||||
var device = this;
|
||||
debug("switch -> OFF");
|
||||
device.get().then(status => {
|
||||
device.set({
|
||||
set: false
|
||||
}, callback);
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.toggle = function (callback) {
|
||||
var device = this;
|
||||
device.get().then(status => {
|
||||
device.set({
|
||||
set: !status
|
||||
}, callback);
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.setColor = function (hexColor, callback) {
|
||||
debugColor("Set color to: ", hexColor);
|
||||
var device = this;
|
||||
var tuya = this.device;
|
||||
var color = new TuyColor(tuya);
|
||||
var dps = color.setColor(hexColor);
|
||||
debugColor("dps values:", dps);
|
||||
|
||||
device.get().then(status => {
|
||||
device.set({
|
||||
multiple: true,
|
||||
data: dps
|
||||
}, callback);
|
||||
});
|
||||
resetTimer();
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.connect = function (callback) {
|
||||
this.device.connect(callback);
|
||||
}
|
||||
|
||||
TuyaDevice.prototype.disconnect = function (callback) {
|
||||
this.device.disconnect(callback);
|
||||
}
|
||||
|
||||
Object.defineProperty(TuyaDevice, 'devices', {
|
||||
value: devices
|
||||
});
|
||||
|
||||
TuyaDevice.connectAll = function () {
|
||||
devices.forEach(device => {
|
||||
device.connect();
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.disconnectAll = function () {
|
||||
devices.forEach(device => {
|
||||
device.disconnect();
|
||||
});
|
||||
}
|
||||
|
||||
TuyaDevice.onAll = function (name, callback) {
|
||||
if (events[name] == undefined) {
|
||||
events[name] = [];
|
||||
}
|
||||
events[name].push(callback);
|
||||
devices.forEach(device => {
|
||||
device.triggerAll(name);
|
||||
});
|
||||
}
|
||||
|
||||
return TuyaDevice;
|
||||
}());
|
||||
|
||||
module.exports = TuyaDevice;
|
||||
425
tuya-mqtt.js
425
tuya-mqtt.js
@@ -1,248 +1,177 @@
|
||||
const mqtt = require('mqtt');
|
||||
const TuyaDevice = require('./tuya-device');
|
||||
const debug = require('debug')('tuya-mqtt');
|
||||
const debugColor = require('debug')('color');
|
||||
const debugMqtt = require('debug')('mqtt');
|
||||
const debugTuya = require('debug')('tuyAPI-Events');
|
||||
const debugError = require('debug')('error');
|
||||
var cleanup = require('./cleanup').Cleanup(onExit);
|
||||
|
||||
function bmap(istate) {
|
||||
return istate ? 'ON' : "OFF";
|
||||
}
|
||||
|
||||
function boolToString(istate) {
|
||||
return istate ? 'true' : "false";
|
||||
}
|
||||
|
||||
var connected = undefined;
|
||||
var CONFIG = undefined;
|
||||
|
||||
try {
|
||||
CONFIG = require("./config");
|
||||
} catch (e) {
|
||||
console.error("Configuration file not found")
|
||||
debugError(e)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (typeof CONFIG.qos == "undefined") {
|
||||
CONFIG.qos = 2;
|
||||
}
|
||||
if (typeof CONFIG.retain == "undefined") {
|
||||
CONFIG.retain = false;
|
||||
}
|
||||
|
||||
const mqtt_client = mqtt.connect({
|
||||
host: CONFIG.host,
|
||||
port: CONFIG.port,
|
||||
username: CONFIG.mqtt_user,
|
||||
password: CONFIG.mqtt_pass,
|
||||
});
|
||||
|
||||
mqtt_client.on('connect', function (err) {
|
||||
debugMqtt("Verbindung mit MQTT-Server hergestellt");
|
||||
connected = true;
|
||||
var topic = CONFIG.topic + '#';
|
||||
mqtt_client.subscribe(topic, {
|
||||
retain: CONFIG.retain,
|
||||
qos: CONFIG.qos
|
||||
});
|
||||
});
|
||||
|
||||
mqtt_client.on("reconnect", function (error) {
|
||||
if (connected) {
|
||||
debugMqtt("Verbindung mit MQTT-Server wurde unterbrochen. Erneuter Verbindungsversuch!");
|
||||
} else {
|
||||
debugMqtt("Verbindung mit MQTT-Server konnte nicht herrgestellt werden.");
|
||||
}
|
||||
connected = false;
|
||||
});
|
||||
|
||||
mqtt_client.on("error", function (error) {
|
||||
debugMqtt("Verbindung mit MQTT-Server konnte nicht herrgestellt werden.", error);
|
||||
connected = false;
|
||||
});
|
||||
|
||||
/**
|
||||
* execute function on topic message
|
||||
*/
|
||||
function boolToString(istate) {
|
||||
return istate == 1 ? 'on' : "off";
|
||||
}
|
||||
|
||||
function convertMessage(message) {
|
||||
var status = message.toString();
|
||||
status = boolToString(status);
|
||||
status = status.toLowerCase();
|
||||
return status;
|
||||
}
|
||||
|
||||
mqtt_client.on('message', function (topic, message) {
|
||||
try {
|
||||
var cMessage = convertMessage(message);
|
||||
var topic = topic.split("/");
|
||||
var options = {
|
||||
type: topic[1],
|
||||
id: topic[2],
|
||||
key: topic[3],
|
||||
ip: topic[4],
|
||||
};
|
||||
var exec = topic[5];
|
||||
|
||||
if (options.type == "socket" || options.type == "lightbulb") {
|
||||
debug("device", options);
|
||||
debug("message", cMessage);
|
||||
var device = new TuyaDevice(options);
|
||||
|
||||
if (exec == "command") {
|
||||
var status = topic[6];
|
||||
if (status == null) {
|
||||
device.switch(cMessage);
|
||||
} else {
|
||||
device.switch(status);
|
||||
}
|
||||
}
|
||||
if (exec == "color") {
|
||||
var color = message.toString();
|
||||
color = color.toLowerCase();
|
||||
debugColor("topic: ", topic);
|
||||
debugColor("onColor: ", color);
|
||||
device.setColor(color);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugError(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Publish current TuyaDevice state to MQTT-Topic
|
||||
* @param {TuyaDevice} device
|
||||
* @param {boolean} status
|
||||
*/
|
||||
function publishStatus(device, status) {
|
||||
if (mqtt_client.connected == true) {
|
||||
try {
|
||||
var type = device.type;
|
||||
var tuyaID = device.options.id;
|
||||
var tuyaKey = device.options.key;
|
||||
var tuyaIP = device.options.ip;
|
||||
|
||||
if (typeof tuyaID != "undefined" && typeof tuyaKey != "undefined" && typeof tuyaIP != "undefined") {
|
||||
var topic = CONFIG.topic + type + "/" + tuyaID + "/" + tuyaKey + "/" + tuyaIP + "/state";
|
||||
mqtt_client.publish(topic, status, {
|
||||
retain: CONFIG.retain,
|
||||
qos: CONFIG.qos
|
||||
});
|
||||
debugTuya("mqtt status updated to:" + topic + " -> " + status);
|
||||
} else {
|
||||
debugTuya("mqtt status not updated");
|
||||
}
|
||||
} catch (e) {
|
||||
debugError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function publishColorState(device, state) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* publish all dps-values to topic
|
||||
* @param {TuyaDevice} device
|
||||
* @param {Object} dps
|
||||
*/
|
||||
function publishDPS(device, dps) {
|
||||
if (mqtt_client.connected == true) {
|
||||
try {
|
||||
var type = device.type;
|
||||
var tuyaID = device.options.id;
|
||||
var tuyaKey = device.options.key;
|
||||
var tuyaIP = device.options.ip;
|
||||
|
||||
if (typeof tuyaID != "undefined" && typeof tuyaKey != "undefined" && typeof tuyaIP != "undefined") {
|
||||
var topic = CONFIG.topic + type + "/" + tuyaID + "/" + tuyaKey + "/" + tuyaIP + "/dps";
|
||||
var data = JSON.stringify(dps);
|
||||
debugTuya("mqtt dps updated to:" + topic + " -> ", data);
|
||||
mqtt_client.publish(topic, data, {
|
||||
retain: CONFIG.retain,
|
||||
qos: CONFIG.qos
|
||||
});
|
||||
|
||||
Object.keys(dps).forEach(function (key) {
|
||||
var topic = CONFIG.topic + type + "/" + tuyaID + "/" + tuyaKey + "/" + tuyaIP + "/dps/" + key;
|
||||
var data = JSON.stringify(dps[key]);
|
||||
debugTuya("mqtt dps updated to:" + topic + " -> dps[" + key + "]", data);
|
||||
mqtt_client.publish(topic, data, {
|
||||
retain: CONFIG.retain,
|
||||
qos: CONFIG.qos
|
||||
});
|
||||
});
|
||||
} else {
|
||||
debugTuya("mqtt dps not updated");
|
||||
}
|
||||
} catch (e) {
|
||||
debugError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* event fires if TuyaDevice sends data
|
||||
* @see TuyAPI (https://github.com/codetheweb/tuyapi)
|
||||
*/
|
||||
TuyaDevice.onAll('data', function (data) {
|
||||
try {
|
||||
debugTuya('Data from device ' + this.type + ' :', data);
|
||||
var status = data.dps['1'];
|
||||
if (typeof status != "undefined") {
|
||||
publishStatus(this, bmap(status));
|
||||
}
|
||||
publishDPS(this, data.dps);
|
||||
} catch (e) {
|
||||
debugError(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* MQTT connection tester
|
||||
*/
|
||||
function MQTT_Tester() {
|
||||
this.interval = null;
|
||||
|
||||
function mqttConnectionTest() {
|
||||
if (mqtt_client.connected != connected) {
|
||||
connected = mqtt_client.connected;
|
||||
if (connected) {
|
||||
debugMqtt('MQTT-Server verbunden.');
|
||||
} else {
|
||||
debugMqtt('MQTT-Server nicht verbunden.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.destroy = function () {
|
||||
clearInterval(this.interval);
|
||||
this.interval = undefined;
|
||||
}
|
||||
|
||||
this.connect = function () {
|
||||
this.interval = setInterval(mqttConnectionTest, 1500);
|
||||
mqttConnectionTest();
|
||||
}
|
||||
|
||||
var constructor = (function (that) {
|
||||
that.connect.call(that);
|
||||
})(this);
|
||||
}
|
||||
var tester = new MQTT_Tester();
|
||||
|
||||
/**
|
||||
* Function call on script exit
|
||||
*/
|
||||
function onExit() {
|
||||
TuyaDevice.disconnectAll();
|
||||
if (tester) tester.destroy();
|
||||
};
|
||||
#!/usr/bin/env node
|
||||
const fs = require('fs')
|
||||
const mqtt = require('mqtt')
|
||||
const json5 = require('json5')
|
||||
const debug = require('debug')('tuya-mqtt:info')
|
||||
const debugCommand = require('debug')('tuya-mqtt:command')
|
||||
const debugError = require('debug')('tuya-mqtt:error')
|
||||
const SimpleSwitch = require('./devices/simple-switch')
|
||||
const SimpleDimmer = require('./devices/simple-dimmer')
|
||||
const RGBTWLight = require('./devices/rgbtw-light')
|
||||
const GenericDevice = require('./devices/generic-device')
|
||||
const utils = require('./lib/utils')
|
||||
|
||||
var CONFIG = undefined
|
||||
var tuyaDevices = new Array()
|
||||
|
||||
// Setup Exit Handlers
|
||||
process.on('exit', processExit.bind(0))
|
||||
process.on('SIGINT', processExit.bind(0))
|
||||
process.on('SIGTERM', processExit.bind(0))
|
||||
process.on('uncaughtException', processExit.bind(1))
|
||||
|
||||
// Disconnect from and publish offline status for all devices on exit
|
||||
async function processExit(exitCode) {
|
||||
for (let tuyaDevice of tuyaDevices) {
|
||||
tuyaDevice.device.disconnect()
|
||||
}
|
||||
if (exitCode || exitCode === 0) debug('Exit code: '+exitCode)
|
||||
await utils.sleep(1)
|
||||
process.exit()
|
||||
}
|
||||
|
||||
// Get new deivce based on configured type
|
||||
function getDevice(configDevice, mqttClient) {
|
||||
const deviceInfo = {
|
||||
configDevice: configDevice,
|
||||
mqttClient: mqttClient,
|
||||
topic: CONFIG.topic
|
||||
}
|
||||
switch (configDevice.type) {
|
||||
case 'SimpleSwitch':
|
||||
return new SimpleSwitch(deviceInfo)
|
||||
break;
|
||||
case 'SimpleDimmer':
|
||||
return new SimpleDimmer(deviceInfo)
|
||||
break;
|
||||
case 'RGBTWLight':
|
||||
return new RGBTWLight(deviceInfo)
|
||||
break;
|
||||
}
|
||||
return new GenericDevice(deviceInfo)
|
||||
}
|
||||
|
||||
function initDevices(configDevices, mqttClient) {
|
||||
for (let configDevice of configDevices) {
|
||||
const newDevice = getDevice(configDevice, mqttClient)
|
||||
tuyaDevices.push(newDevice)
|
||||
}
|
||||
}
|
||||
|
||||
// Republish devices 2x with 30 seconds sleep if restart of HA is detected
|
||||
async function republishDevices() {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
debug('Resending device config/state in 30 seconds')
|
||||
await utils.sleep(30)
|
||||
for (let device of tuyaDevices) {
|
||||
device.republish()
|
||||
}
|
||||
await utils.sleep(2)
|
||||
}
|
||||
}
|
||||
|
||||
// Main code function
|
||||
const main = async() => {
|
||||
let configDevices
|
||||
let mqttClient
|
||||
|
||||
try {
|
||||
CONFIG = require('./config')
|
||||
} catch (e) {
|
||||
console.error('Configuration file not found!')
|
||||
debugError(e)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (typeof CONFIG.qos == 'undefined') {
|
||||
CONFIG.qos = 1
|
||||
}
|
||||
if (typeof CONFIG.retain == 'undefined') {
|
||||
CONFIG.retain = false
|
||||
}
|
||||
|
||||
try {
|
||||
configDevices = fs.readFileSync('./devices.conf', 'utf8')
|
||||
configDevices = json5.parse(configDevices)
|
||||
} catch (e) {
|
||||
console.error('Devices file not found!')
|
||||
debugError(e)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!configDevices.length) {
|
||||
console.error('No devices found in devices file!')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
mqttClient = mqtt.connect({
|
||||
host: CONFIG.host,
|
||||
port: CONFIG.port,
|
||||
username: CONFIG.mqtt_user,
|
||||
password: CONFIG.mqtt_pass,
|
||||
})
|
||||
|
||||
mqttClient.on('connect', function (err) {
|
||||
debug('Connection established to MQTT server')
|
||||
let topic = CONFIG.topic + '#'
|
||||
mqttClient.subscribe(topic)
|
||||
mqttClient.subscribe('homeassistant/status')
|
||||
mqttClient.subscribe('hass/status')
|
||||
initDevices(configDevices, mqttClient)
|
||||
})
|
||||
|
||||
mqttClient.on('reconnect', function (error) {
|
||||
if (mqttClient.connected) {
|
||||
debug('Connection to MQTT server lost. Attempting to reconnect...')
|
||||
} else {
|
||||
debug('Unable to connect to MQTT server')
|
||||
}
|
||||
})
|
||||
|
||||
mqttClient.on('error', function (error) {
|
||||
debug('Unable to connect to MQTT server', error)
|
||||
})
|
||||
|
||||
mqttClient.on('message', function (topic, message) {
|
||||
try {
|
||||
message = message.toString()
|
||||
const splitTopic = topic.split('/')
|
||||
const topicLength = splitTopic.length
|
||||
const commandTopic = splitTopic[topicLength - 1]
|
||||
const deviceTopicLevel = splitTopic[1]
|
||||
|
||||
if (topic === 'homeassistant/status' || topic === 'hass/status' ) {
|
||||
debug('Home Assistant state topic '+topic+' received message: '+message)
|
||||
if (message === 'online') {
|
||||
republishDevices()
|
||||
}
|
||||
} else if (commandTopic.includes('command')) {
|
||||
// If it looks like a valid command topic try to process it
|
||||
debugCommand('Received MQTT message -> ', JSON.stringify({
|
||||
topic: topic,
|
||||
message: message
|
||||
}))
|
||||
|
||||
// Use device topic level to find matching device
|
||||
const device = tuyaDevices.find(d => d.options.name === deviceTopicLevel || d.options.id === deviceTopicLevel)
|
||||
switch (topicLength) {
|
||||
case 3:
|
||||
device.processCommand(message, commandTopic)
|
||||
break;
|
||||
case 4:
|
||||
device.processDpsCommand(message)
|
||||
break;
|
||||
case 5:
|
||||
const dpsKey = splitTopic[topicLength-2]
|
||||
device.processDpsKeyCommand(message, dpsKey)
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugError(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Call the main code
|
||||
main()
|
||||
Reference in New Issue
Block a user