Giter Site home page Giter Site logo

tuya-mqtt's People

Contributors

gadgetangel avatar michael-c-hoffman avatar theagentk avatar tsightler avatar vkoop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tuya-mqtt's Issues

Disconnected from device and never connects again ...

Hi,

Today I've upgraded tuya-api to 6.1.4 and tuya-mqtt to 3.03 ... Everything works fine except: The connection to the device is closed after a random time after startup and never comes back up again. This is what it says in the logs:

2021-01-25T10:34:43.928Z tuya-mqtt:state MQTT DPS JSON: tuya/aiibot_air_purifier/dps/state -> {"2":5}
2021-01-25T10:34:43.929Z tuya-mqtt:state MQTT DPS2: tuya/aiibot_air_purifier/dps/2/state -> 5
2021-01-25T10:34:43.955Z tuya-mqtt:error Error: Error from socket
at Socket.client.on.err (/home/fhem/tuya-mqtt/node_modules/tuyapi/index.js:388:30)
at Socket.emit (events.js:193:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at processTicksAndRejections (internal/process/task_queues.js:81:17)
2021-01-25T10:34:43.958Z tuya-mqtt:tuyapi Disconnected from device Aiibot Air Purifier (10.10.1.42, xxxxxxx, yyyyyy)
2021-01-25T10:34:44.956Z tuya-mqtt:error Error connecting to device id xxxxxxx ....retry in 10 seconds.

I suppose that it would log something when it retries the connection, but it stays quiet, so I suppose it does not retry to establish the connection at all.

And the other question is why it disconnects anyway?

Note: When I restart the "node tuya-mqtt.js" process, the connection is established right away ...

Thanks // Tom

What mqtt broker

Hello I'm new to all this js codding so not sure if i have just missed something.
What MQTT broker mentioned here

Is that where the login info for the smart life app goes?
Also on a side note does anyone know why i seem to have different password for the iot.tuya dev web page and the smartlife app ?
But more importantly what mqtt info do i use ?

Switch w/ Energy: DPS values reported only once at tuya-mqtt startup

I realize this project is in maintenance mode, but I thought I'd ask a question to see if any of the followers would know the answer.

I have a switches which have energy monitoring capability. There are a lot of DPS values associated with the device.
One of these switches used to work just fine with tuya-mqtt, configured as a SimpleSwitch and the energy values are reported as DPS values when they changed.

That switch broke, and I replaced it with the same model switch (which I purchased at the same time as the one which failed as part of a multi-pack).

This new switch works fine when changing the on/off power switch - that DPS value is reported by tuya-mqtt (along with the interpreted state) whenever it changes.

However, none of the other DPS values are ever reported, except when tuya-mqtt starts up initially (those reported values are correct by the way). After that initial publish at program start, there are no further DPS updated values except for DPS 1 (the main power state) when it changes.

I can query all of the DPS values with tuya-cli and they are all reported and are correct. But in the tuya-mqtt app, nothing ever comes out after the initial report when tuya-mqtt starts.

The strange thing is that the identical switch (purchased as part of a multi-pack) used to work reliably just fine.

I've done all the usual things, restarting the app and even rebooting the RPi that is running tuya-mqtt. No difference.

Has anyone seen this type of behavoir?

dps topic does not work as described (see my pull request: fa22807), label:bug

Describe the bug
your description of using the "dps" topic does not work because the device does not respond to a dps/1 topic or any dps/index topic because the current state of tuya-mqtt.exe has the case statement falls thru if the command is neither "command" or "color". There is no case statement for "dps".

To Reproduce
Steps to reproduce the behavior:

  1. if one goes to MQTT and publishes to the following topic, the tuya device will just ignore the request:
    tuya/tuyaAPI-id/tuyaAPI-key/tuyaAPI-ip/dps

  2. if one goes to MQTT and publishes to the following topic, the tuya device will just ignore the request:
    tuya/tuyaAPI-id/tuyaAPI-key/tuyaAPI-ip/dps/7

  3. if one goes to MQTT and publishes to the following topic, the tuya device will just ignore the request:
    tuya/tuyaAPI-id/tuyaAPI-key/tuyaAPI-ip/command/{"schema": true}

Expected behavior

  1. I expect that the device would respond to the dps query and tell me the current state of all the dps

  2. I expect that the device would respond to the dps query and tell me the current state of dps 7

  3. I expected this query to fail but I would really like to see this query added to the command topic

Screenshots
If applicable, add screenshots to help explain your problem.

If you look at the DEBUG output you will see that I published to the dps topic

tuya/3543376268c63ae3f978/25f1f8c229dacaa6/192.168.0.38/dps

and got nothing back from the device.

I also published to the dps/1 topic and got nothing back from the tuya device.

BUT if I published to the command topic with {"schema": true} , which uses ( the pull request #21 code), I do get a response back from the tuya device with all the dps values

screen shots:

output from mqtt.fx

mqtt fx subscribe and publish output

DEBUG output from tuya-mqtt.exe

code debug output 1 of 7
code debug output 2 of 7
code debug output 3 of 7
code debug output 4 of 7
code debug output 5 of 7
code debug output 6 of 7
code debug output 7 of 7

Desktop (please complete the following information):

  • OS: [e.g. iOS] Windows 10 Pro, Intel Core i3-2100 CPU @ 3.10GHz
  • Browser [e.g. chrome, safari] Chrome
  • Version [e.g. 22] Version 73.0.3683.103

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
I want a forced response from the device when I ask for a dps request. I know the device will respond after a command is given to change the state of the device. I want to see a response from the device even if the state of the device has NOT changed. That is why I would like to see {"schema": true} implemented as a command under the command TOPIC. {"schema": true} is the ONLY command in the TuyAPI that does not require the device to change its state to get a response from the device.
#21

TypeError: Cannot set property 'updated' of undefined

Describe the bug
Running DEBUG=tuya-mqtt:* node tuya-mqtt.js ends in the following output/exception and the program exits:

tuya-mqtt:info Connection established to MQTT server +0ms
  tuya-mqtt:tuyapi Search for device id xxx +0ms
  tuya-mqtt:tuyapi Found device id xxx +1ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +19ms
  tuya-mqtt:tuyapi Connected to device Stehlampe (xxx, xxx, xxx) +986ms
  tuya-mqtt:device-detect Attempting to detect light capabilites and DPS values... +0ms
  tuya-mqtt:device-detect Querying DPS 2 for white/color mode setting... +0ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +52ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +11ms
  tuya-mqtt:device-detect Detected likely Tuya color bulb at DPS 20-24, checking more details... +62ms
  tuya-mqtt:device-detect Attempting to detect if bulb supports color temperature... +0ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +10ms
  tuya-mqtt:device-detect Detected likely color temerature support +10ms
  tuya-mqtt:device-detect Attempting to detect Tuya color format used by device... +1ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +12ms
  tuya-mqtt:device-detect Detected Tuya color format HSBHEX +11ms
  tuya-mqtt:discovery Home Assistant config topic: homeassistant/light/xxx/config +0ms
  tuya-mqtt:discovery {
  tuya-mqtt:discovery   name: 'Stehlampe',
  tuya-mqtt:discovery   state_topic: 'tuya/stehlampe/state',
  tuya-mqtt:discovery   command_topic: 'tuya/stehlampe/command',
  tuya-mqtt:discovery   brightness_state_topic: 'tuya/stehlampe/color_brightness_state',
  tuya-mqtt:discovery   brightness_command_topic: 'tuya/stehlampe/color_brightness_command',
  tuya-mqtt:discovery   brightness_scale: 100,
  tuya-mqtt:discovery   hs_state_topic: 'tuya/stehlampe/hs_state',
  tuya-mqtt:discovery   hs_command_topic: 'tuya/stehlampe/hs_command',
  tuya-mqtt:discovery   white_value_state_topic: 'tuya/stehlampe/white_brightness_state',
  tuya-mqtt:discovery   white_value_command_topic: 'tuya/stehlampe/white_brightness_command',
  tuya-mqtt:discovery   white_value_scale: 100,
  tuya-mqtt:discovery   availability_topic: 'tuya/stehlampe/status',
  tuya-mqtt:discovery   payload_available: 'online',
  tuya-mqtt:discovery   payload_not_available: 'offline',
  tuya-mqtt:discovery   unique_id: 'xxx',
  tuya-mqtt:discovery   device: {
  tuya-mqtt:discovery     ids: [ 'xxx' ],
  tuya-mqtt:discovery     name: 'Stehlampe',
  tuya-mqtt:discovery     mf: 'Tuya',
  tuya-mqtt:discovery     mdl: 'RGBTW Light'
  tuya-mqtt:discovery   },
  tuya-mqtt:discovery   color_temp_state_topic: 'tuya/stehlampe/color_temp_state',
  tuya-mqtt:discovery   color_temp_command_topic: 'tuya/stehlampe/color_temp_command',
  tuya-mqtt:discovery   min_mireds: 154,
  tuya-mqtt:discovery   max_mireds: 400
  tuya-mqtt:discovery } +0ms
  tuya-mqtt:tuyapi Received JSON data from device xxx -> {"20":true,"21":"white","22":300,"23":500,"26":0} +1s
  tuya-mqtt:info Exit code: TypeError: Cannot set property 'updated' of undefined +2s
  tuya-mqtt:tuyapi Disconnected from device Stehlampe (xxx, xxx, xxx) +3ms
  tuya-mqtt:info Exit code: 0 +1s

tuya-cli works fine inside and outside of the docker container:

tuya-cli set --id xxx--key xxx--dps 20 --set false
Set succeeded.

And the lamp turns off.

Software:

Additional context
It worked fine a week ago, coming back to this project and now it throws this error.

ECONNREFUSED Error when trying to change lightbulb state

Hello! So, I posted this issue to tuyapi, and from the way thy saw this it looked like this could potentially be an error within the tuya-mqtt script, so I'll post my issue here below.

Currently, I've been working on getting my tuya wifi bulbs from feit electric to connect to my openhab system. I feel like I'm VERY close to getting it all good to go, but this is my last hurdle I'm not sure how to get working properly.
When I start up tuya-mqtt.js, things seem relatively fine, however when i try to switch the lightbulb on/off using the basicUI from the items and sitemap i configured, this is the debug error I get from tuya-mqtt.js:
TuyAPI:mqtt MQTT-Server nicht verbunden. +0ms TuyAPI:mqtt Verbindung mit MQTT-Server hergestellt +12ms TuyAPI:mqtt receive settings {"topic":"tuya/lightbulb/XXX/XXX/XXX/command","action":"command","message":"OFF","options":{"id":"XXX","key":"XXX","ip":"XXX","type":"lightbulb"}} +8s TuyAPI:device Search device in network +0ms TuyAPI IP and ID are already both resolved. +0ms TuyAPI:device Device found in network +9ms TuyAPI Connecting to XXX... +14ms TuyAPI Error event from socket. XXX { Error: connect ECONNREFUSEDXXX:6668 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) errno: 'ECONNREFUSED', code: 'ECONNREFUSED', syscall: 'connect', address: 'XXX', port: 6668 } +10ms TuyAPI:device:error Error: Error from socket TuyAPI:device:error at Socket.client.on.err (/etc/openhab2/scripts/tuya-mqtt/node_modules/tuyapi/index.js:365:30) TuyAPI:device:error at Socket.emit (events.js:198:13) TuyAPI:device:error at emitErrorNT (internal/streams/destroy.js:91:8) TuyAPI:device:error at emitErrorAndCloseNT (internal/streams/destroy.js:59:3) TuyAPI:device:error at process._tickCallback (internal/process/next_tick.js:63:19) +0ms TuyAPI:mqtt:error { error: TuyAPI:mqtt:error Error: Error from socket TuyAPI:mqtt:error at Socket.client.on.err (/etc/openhab2/scripts/tuya-mqtt/node_modules/tuyapi/index.js:365:30) TuyAPI:mqtt:error at Socket.emit (events.js:198:13) TuyAPI:mqtt:error at emitErrorNT (internal/streams/destroy.js:91:8) TuyAPI:mqtt:error at emitErrorAndCloseNT (internal/streams/destroy.js:59:3) TuyAPI:mqtt:error at process._tickCallback (internal/process/next_tick.js:63:19), TuyAPI:mqtt:error device: TuyAPI:mqtt:error TuyaDevice { TuyAPI:mqtt:error type: 'lightbulb', TuyAPI:mqtt:error options: TuyAPI:mqtt:error { id: 'XXX', TuyAPI:mqtt:error key: 'XXX', TuyAPI:mqtt:error ip: 'XXX', TuyAPI:mqtt:error type: 'lightbulb' } } } +0ms TuyAPI Socket closed: XXX +24ms TuyAPI:device Disconnected from device. lightbulb (XXX,XXX, XXX) +41ms TuyAPI:device delete Device lightbulb (XXX, XXX, XXX) +0ms
I changed the tuyapi to the most current version in package.json, or at least i think i did, but this error still pops up.
From what this looks like, I think the bulb is refusing a connection with the tuya-mqtt for some reason?
all my bulbs are no longer configured to any tuya-related app. I had to do tuya-cli link along with the tuya developer instructions to get the localkeys. They seem to be connected to my wifi fine i believe since they're not blinking... I did have to specifically run that on a seperate computer from the machine OpenHAB is currently running on, as it's important to note my system has ethernet connection only. does the tuya-mqtt script only function proerly on wifi?

If there's any other details you need I'm happy to provide them! I'm still brand new at all of this, and new to linux as well, so there's a lot i'm trying to learn on the fly, and I wouldn't be surprised if this was caused by some mistake down the line. I think I Xed out all the private info, but if i missed something let me know as well. Regardless, thank you for your patience!

Current Specs that is running the processes:
Linux Mint 20 v.4.6.6
intel core 2 duo CPU E6400 @ 2.13Ghz x 2
3.8GB RAM
1TB HDD
intel corp. 82q963/q965 integrated graphics controller

Problem installing on Synology RS914

When trying to install on RS914 (npm install) I get the following:

`ash-4.3# npm install
audited 322 packages in 17.975s

45 packages are looking for funding
run npm fund for details

found 2 vulnerabilities (1 low, 1 high)
run npm audit fix to fix them, or npm audit for details

ash-4.3#`

running npm audit, I get the following:
`ash-4.3# npm audit

                   === npm audit security report ===

┌──────────────────────────────────────────────────────────────────────────────┐
│ Manual Review │
│ Some vulnerabilities require your attention to resolve │
│ │
│ Visit https://go.npm.me/audit-guide for additional guidance │
└──────────────────────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low │ Prototype Pollution │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ minimist │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in │ >=0.2.1 <1.0.0 || >=1.2.3 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ @tuyapi/cli │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ @tuyapi/cli > http-mitm-proxy > optimist > minimist │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://npmjs.com/advisories/1179
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High │ Prototype Pollution in node-forge │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ node-forge │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in │ >= 0.10.0 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ @tuyapi/cli │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ @tuyapi/cli > http-mitm-proxy > node-forge │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://npmjs.com/advisories/1561
└───────────────┴──────────────────────────────────────────────────────────────┘
found 2 vulnerabilities (1 low, 1 high) in 322 scanned packages
2 vulnerabilities require manual review. See the full report for details.
ash-4.3#`

Running npm audit fix, I get the following:
`ash-4.3# npm audit fix
up to date in 15.732s

45 packages are looking for funding
run npm fund for details

fixed 0 of 2 vulnerabilities in 322 scanned packages
2 vulnerabilities required manual review and could not be updated
ash-4.3#`

Sending command from MQTT prints the following:
(node:7616) UnhandledPromiseRejectionWarning: Error: No connection has been made to the device. at TuyaDevice._send (/volume1/homes/admin/tuya-mqtt-master/node_modules/tuyapi/index.js:269:13) at pTimeout._setResolver (/volume1/homes/admin/tuya-mqtt-master/node_modules/tuyapi/index.js:242:14) at new Promise (<anonymous>) at /volume1/homes/admin/tuya-mqtt-master/node_modules/tuyapi/index.js:238:46 at run (/volume1/homes/admin/tuya-mqtt-master/node_modules/p-queue/dist/index.js:153:104) at PQueue._tryToStartAnother (/volume1/homes/admin/tuya-mqtt-master/node_modules/p-queue/dist/index.js:101:38) at /volume1/homes/admin/tuya-mqtt-master/node_modules/p-queue/dist/index.js:167:18 at new Promise (<anonymous>) at PQueue.add (/volume1/homes/admin/tuya-mqtt-master/node_modules/p-queue/dist/index.js:148:16) at TuyaDevice.set (/volume1/homes/admin/tuya-mqtt-master/node_modules/tuyapi/index.js:238:27) (node:7616) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2) (node:7616) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any idea?
Thanks for the greate work - it works fine on my Raspberry pi but not on Synology. I have checked the configurations files and the cli.

Possible Memory Leak

Hello, think there a memory leak with tuya-mqtt with 3.3 protocol. tested on 2 raspberry with openhab (one zero and one 3B+)

In 8 hours tuya-mqtt.js needed 186MB of memory and it continues to increase

openhab+ 359 0.2 18.7 291472 186996 ? Ssl Jul25 2:55 /usr/bin/node /etc/openhab2/scripts/tuyaapi_mqtt

During my test with DEBUG. I saw that, randomly, the socket wasn't disconnected but there is an infinity of ping pong.
More we use the tuya-mqtt command,, more the memory usage increases exponentially.

8:35AM i kill the process tuya-mqtt.js , 38MB , it's ok , 577MB available
openhab+ 13179 19.6 3.8 131740 38376 ? Ssl 08:27 0:00 /usr/bin/node /etc/openhab2/scripts/tuyaapi_mqtt/tuya-mqtt.js

01:52 PM 564MB available and I launch some command on tuya devices.

09:16 PM 519 MB available
openhab+ 13179 0.1 7.6 179136 75928 ? Ssl 08:27 0:48 /usr/bin/node /etc/openhab2/scripts/tuyaapi_mqtt/tuya-mqtt.js

Thank you

TuyaApi Issue

Hi,

I am struggling since last few days to implement tuyaapi . My scenario is very simple - I want to control tuya smart plug through raspberry pi( openhab2)
I am following the steps exactly as you suggested.

Step 1 : I download the code from https://github.com/TheAgentK/tuyaapi_openhab
$ git clone [email protected]:codetheweb/tuyapi.git
As per the instruction it should create a folder tuyaapi_openhab but post git extraction I am seeing tuyapi folder - under my script folder (/etc/openhab2/scripts)

Step 2 : npm i @tuyapi/cli -g ( successfully executed)

Step 3 : tuya-cli link-wizard ( failing) ( I got the Access ID and Access key from Tuya. Also validated from $Tuyapi cli -list command._

Step 4: node tuya.js --ip=DEVICEIP --id=DEVICEID --key=DEVICEKEY COMMAND
ERROR : I don’t find any tuya.js file anywhere inmy folder . I have the ip,I’d and the key.
Am I missing anything ?

Appreciate your quick help.

Feature tuya shutter motor control

Hi,

is it possible to control shutter motors? And if yes, which mqtt topic do i have to use? I already have all keys that I need to send the message to the correct topic. The only thing I´m missing is the right topic for this type of device.

Thanks

Empty Data Returned After Publishing get-states

Describe the bug
First off - this may be me! Apologies if it is 😞.

I have tuya-mqtt up and running, it's working well overall. Thanks! My issue is when I send the command get-states, it doesn't seem to "trigger the device to send an immediate update of all known device DPS topics". Rather, I get an immediate reply, but it's empty.

To Reproduce
Steps to reproduce the behavior:

  1. Start up the tuya-mqtt server
  2. Subscribe to the Tuya device
  3. Send the get-states command
  4. Check the data sent back -> always getting,
Client mosq-RF6Yundi0OZUPWQAdg received PUBLISH (d0, q1, r0, m6, 'tuya/emfrontswitch/dps/state', ... (2 bytes))
Client mosq-RF6Yundi0OZUPWQAdg sending PUBACK (m6, rc0)
{}

Expected behavior
Expecting to trigger the device to send current dps states / date.

Desktop (please complete the following information):\

  • OS: Ubuntu Linux, v20.10
  • Version: master branch

npm install not working

Describe the bug
Calling the "npm install" to download codetheweb/tuyapi fails with log :

npm ERR! git clone [email protected]:github:codetheweb/tuyapi fatal: remote error:
npm ERR! git clone [email protected]:github:codetheweb/tuyapi    is not a valid repository name
npm ERR! git clone [email protected]:github:codetheweb/tuyapi   Email [email protected] for help
npm ERR! notarget No compatible version found: tuyapi@'github:codetheweb/tuyapi'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.1.0","0.1.1","0.1.2","1.0.0","1.0.1","1.0.2","1.1.0","1.1.1","1.1.2","2.0.0","2.0.1","2.0.2","2.0.3","3.0.0","3.0.1","3.0.2","3.1.0","3.1.1","3.1.2","3.1.3","3.1.4","3.1.5","3.2.0","3.2.1","3.2.2","3.2.3"]
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

Desktop :

  • OS: Raspbian

tuya-mqtt publishes states only when app is opened.

Describe the bug
First off, I have a feeling this is due to my device and not tuya-mqtt but I thought you might know what's going on.
I'm loving tuya-mqtt and it's working well, so thank you for this great piece of software.

I'm using a power monitoring socket (Elivco 16A). When I'm in the SmartLife app, all the data (e.g. power usage DPS 19) is being pushed nicely to my mqtt broker (refresh rate approx. 5 sec). However, when I close the app, or even look at another device in the app, the power usage is no longer updated. Even when pushing 'get-states' every 5 seconds, I'm not getting back updated results. Only when I open the device in the SmartLife app it updated with current values. Any idea / workarounds how to get real time data?

Expected behavior
Power usage changes to bu pushed to the mqtt broker in real time, even when app is not in use.

Desktop (please complete the following information):\

  • OS: [Raspberry OS]
  • Version: master branch

MQTT disconnect loop if the device name contains '+' or '#' characters

Description
When the devices.conf contains a device name with characters not legal in a Mqtt topic name, e.g. name: 'T2 candle 5W RGB+CW' -> upon first attempt of publishing data to device's topic, the script enters endless reconnect loop it can not recover from.
Broker-side (Mosquitto) this is seen as a connection-->socket error-->connection-->...

Notes:

  1. This happens when using either '+' or '#' in the device name, though if a '/' is used in the name - it also gets passed into Mqtt, creating unnecessary subtopics.
  2. The name T2 candle 5W RGB+CW is a real-world default device name of a lightbulb I have (generated by Tuya app). It was copy-pasted from tuya-cli wizard

To Reproduce
Originally observed when using Mosquitto as a broker (did not check behavior of other brokers)

  1. Edit devices.json and put a device with a name containing either a '+' or a # - e.g. name: 'T2 candle 5W RGB+CW'
  2. Run DEBUG=tuya-mqtt:* node tuya-mqtt.js
  3. Observe (logs) that the MQTT connection is established first, but the moment there is an attempt to publish anything on the device's channel (technically: when [devices/tuya-device.js::626] this.mqttClient.publish(topic, message, { qos: 1 }) is hit) - the script enters an endless reconnect loop, with 'reconnect' event firing every second.
  4. Effectively - no data gets published to the MQTT server

Expected behavior

  1. Device name should be canonized, not to include any of # + /
    It might suffice to extend the filter here and update the readme (unfortunately don't have time today, to submit a PR for this myself, though it should be fairly trivial)
  2. Additionally - If such class of errors happens - logging should be expanded to indicate the origin (hopefully mqtt module allows for catching these errors). While it seems trivial now, without looking at source code it was impossible for me to figure out what is happening.

System info/logs

Click to expand!
tuya-mqtt:info Connection established to MQTT server +0ms
tuya-mqtt:tuyapi Search for device id 00000000deadbeef0000 +0ms
tuya-mqtt:tuyapi Found device id 00000000deadbeef0000 +9ms
tuya-mqtt:tuyapi Received JSON data from device 00000000deadbeef0000 -> 
(... device communication omitted for brevity ...)
tuya-mqtt:discovery Home Assistant config topic: homeassistant/light/00000000deadbeef0000/config +0ms
tuya-mqtt:discovery { name: 'T2 candle 5W RGB+CW',
tuya-mqtt:discovery   state_topic: 'tuya/t2_candle_5w_rgb+cw/state',
(... cut ...)
tuya-mqtt:discovery   max_mireds: 400 } +2ms
tuya-mqtt:info Unable to connect to MQTT server +2s
tuya-mqtt:tuyapi Received JSON data from device 00000000deadbeef0000 -> {"20":true,"21":"white" ...
(... a few of these follow ...)
tuya-mqtt:state tuya/t2_candle_5w_rgb+cw/state ON +0ms
(... rest of tuya-mqtt:state omitted ...)
tuya-mqtt:info Unable to connect to MQTT server +1s
tuya-mqtt:info Unable to connect to MQTT server +1s
tuya-mqtt:info Unable to connect to MQTT server +1s
tuya-mqtt:info Unable to connect to MQTT server +1s
tuya-mqtt:info Unable to connect to MQTT server +1s
tuya-mqtt:info Unable to connect to MQTT server +1s
(...)
  • From /var/log/mosquitto/mosquitto.log:

1604644221: New connection from 127.0.0.1 on port 1883.
1604644221: New client connected from 127.0.0.1 as mqttjs_4ca70238 (p2, c1, k60).
1604644221: Socket error on client mqttjs_4ca70238, disconnecting.
1604644222: New connection from 127.0.0.1 on port 1883.
1604644222: New client connected from 127.0.0.1 as mqttjs_4ca70238 (p2, c1, k60).
1604644222: Socket error on client mqttjs_4ca70238, disconnecting.
1604644223: New connection from 127.0.0.1 on port 1883.
1604644223: New client connected from 127.0.0.1 as mqttjs_4ca70238 (p2, c1, k60).
1604644223: Socket error on client mqttjs_4ca70238, disconnecting.
1604644224: New connection from 127.0.0.1 on port 1883.
1604644224: New client connected from 127.0.0.1 as mqttjs_4ca70238 (p2, c1, k60).
1604644224: Socket error on client mqttjs_4ca70238, disconnecting.
(...)

Single payload numbers expected as strings not processed properly.

Hi,

First of all, thanks for providing this piece of software. I use it to connect an AiiBot Air Purifier (model A500) to my FHEM home control system via MQTT.

Now I have a strange problem: I can turn the Purifier On and Off, I can change the mode from Auto to Manual etc. all without problems. However: I cannot change the speed, even though I use exactly the same mechanisms.

Via MQTT, I try to

$ mosquitto_pub -t tuya/aiibot_air_purifier/dps/4/command -m \"1\"

BTW: I need the ", otherwise, it would not react at all (don't hear a beep from the device).

Now the strange thing I found out is: The only way to properly control the speed is to use the "--raw-value" option for tuya-cli. So this works:

fhem@ha:~$ tuya-cli set --ip 10.10.1.42 --id xxxxxxxxxxxxx --key yyyyyyyyyyy --protocol-version 3.3 --dps 4 --set 4 --raw-value
Set succeeded.

while this does not work and tuya-cli even throws an error:

fhem@ha:~$ tuya-cli set --ip 10.10.1.42 --id xxxxxxxxxxxxxxx --key yyyyyyyyyyyyy --protocol-version 3.3 --dps 4 --set 4
events.js:170
      throw er; // Unhandled 'error' event
      ^

Error: Error from socket
    at Socket.client.on.err (/usr/lib/node_modules/@tuyapi/cli/node_modules/tuyapi/index.js:351:30)
    at Socket.emit (events.js:193:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at processTicksAndRejections (internal/process/task_queues.js:81:17)
Emitted 'error' event at:
    at Socket.client.on.err (/usr/lib/node_modules/@tuyapi/cli/node_modules/tuyapi/index.js:351:16)
    at Socket.emit (events.js:193:13)
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:81:17)

Ok, I know that this sounds more like a tuya-api problem, but how can --raw-value be supported by tuya-mqtt?? What's the difference anyway?

Thanks // Tom

BTW: The --raw-value option apparently avoids that someone messes with the quotes. See here: codetheweb/tuyapi#254 ...

PS .. this is my devices.conf:

[
  {
    name: 'Aiibot Air Purifier',
    id: 'xxxxxxxxx',
    key: 'yyyyyyyy',
    ip: '10.10.1.42',
    version: '3.3',
    type: 'GenericDevice',
        template: {
            power: {
              key: '1',
              type: 'bool'
            },
            pm25: {
              key: '2',
              type: 'int'
            },
            mode: {
              key: '3',
              type: 'string'
            },
            speed: {
              key: '4',
              type: 'string'
            }
        }
  }
]

Problem with Emylo SS-8839-03 and openhabian

Hello,

I have a problem with tuya-mqtt (with mqtt binding version 2.4). I follow this guide on the openhab forum : Step-by-Step guide for adding Tuya-bulbs, Wi-Fi smart LED (Smart Life app) to OH2 using tuya-mqtt.js by AgentK. After installation and configuration all my Teckin SP21 work fine. But my Emylo SS-8839-03 dont work (local key , dev ID, ip… all is good) … impossible to find the solution. Any ideas ? thank you very much and sorry for my english :)

my EleLight tuya bulb will not work with the present TuyaColorLight.prototype.setColor method because this tuya Bulb ignores dps 5 if you set dps 3 or dps 4 while setting dps 5, label:bug

Describe the bug
the tuya Bulb ignores dps 5 if you set dps 3 and/or dps 4 while setting dps 5

To Reproduce
Steps to reproduce the behavior:

  1. get yourself a EleLight from URL: https://www.amazon.com/Dimmable-Multicolored-Controlled-Compatible-Assistant/dp/B07FY6V4QJ
  2. try to set the color using your software where it sets dps 1, dps 2, dps 3, dps 4, and dps 5
  3. The color on the light will go from color to White. Even if dps 2 is set to colour.

Expected behavior
I expected the bulb to change to the color I choose, not to turn white

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS] Window 10
  • Browser [e.g. chrome, safari] Chrome
  • Version [e.g. 22]

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
I added a new update to my pull request that takes care of this problem and also gives you the correct linear equations to use for brightness conversion to 255 scale and the correct conversion equations for color temperature scale and saturation scales. I also discovered the correct format for dps 5 14 hex digit setting. Please see my comments on my current pull request number: fa22807

As far as I can determine, the correct format for dps 5 is as follows:

If the bulb is in 'colour' mode than the dps 3 and dps 4 are ignored but if you set them now some tuya bulbs will ignore dps 5 because you set dps 3 or dps 4. The tuya bulb will get the saturation settings and the brightness setting from (dps 5) hex digits.

A. FOR 'colour' mode the bulb looks at dps 1, dps 2, and dps 5.
i. DPS 5 is in the following format:
ii. HSL to HEX format are the leftmost hex digits (hex digits 14 - 9). This is as you did it before.
iii. hex digits 8 - 5 are the HSB/HSL Hue value in HEX format. Four HEX digits needed here.
iv. hex digits 4 - 3 are the HSB/HSL Saturation percentage as a value (converted to "0 - 255" scale) in HEX format.
v. hex digits 2 - 1 are the HSB Brightness percentage as a value (converted to "25 - 255" scale) in HEX format.

B. if the bulb is in 'white' mode then the dps 5 value is ignored by the bulb, FOR 'white' mode the bulb looks at dps 1, dps 2, dps 3 and dps 4
i. DPS 3 is the HSB/HSL Brightness percentage converted to a value; "25 to 255" in decimal format.
ii. DPS 4 is the HSB/HSL Saturation percentage converted to a value; "0 to 255" in decimal format.

So to give the software more flexibility, please do not automatically set dps 3 and dps 4, only set them when the bulb really needs them set.

zombe state reconnecting issue?

Hi,

I have been testing tuya-mqtt for a while and I am still convinced that this is something I could use in my home. Unfortunately there are issues, and you stopped developing the project, but maybe you could give me some hints, so that I can try to fix myself or find another workaround…

My point is similar to some I already read about here, but I am not completely sure if it is really the same. My setup is like follows

  • Smart LED Tuya Moodlight ZM H21054
  • Connected via wifi to fritzbox 7560 and blocked internet access.
  • DNS is not done by fritzbox itself, but a pihole, which is configured to block DNS requests from the moodlights local ip to to m2.tuyaeu.com, a3.tuyaeu.com, tpm.tuyacn.com.

What I discovered:

  • If moodlight is running with open internet access, everything is fine.
  • If I close internet access during runtime, moodlight does no longer reply on ping requests.
  • Restarting moodlight it starts working again. Ping works, and the device sends out packages like this:
170	2022-02-22 15:23:03,860717	192.168.2.87	0.0.0.0	TCP	76	[TCP Out-Of-Order] 40470 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
171	2022-02-22 15:23:03,860836	192.168.2.87	0.0.0.0	TCP	76	[TCP Out-Of-Order] 40470 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
7221	2022-02-22 15:23:05,857960	192.168.2.87	0.0.0.0	TCP	76	[TCP Retransmission] 40470 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
7222	2022-02-22 15:23:05,858074	192.168.2.87	0.0.0.0	TCP	76	[TCP Retransmission] 40470 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
7223	2022-02-22 15:23:05,858310	192.168.2.87	0.0.0.0	TCP	76	[TCP Retransmission] 40470 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
8612	2022-02-22 15:23:06,337255	192.168.2.87	255.255.255.255	UDP	232	59727 → 6667 Len=172
8613	2022-02-22 15:23:06,337397	192.168.2.87	255.255.255.255	UDP	232	59727 → 6667 Len=172
8614	2022-02-22 15:23:06,337555	192.168.2.87	255.255.255.255	UDP	232	59727 → 6667 Len=172
97289	2022-02-22 15:23:31,348172	192.168.2.87	192.168.2.47	DNS	91	Standard query 0x1dff A m2.tuyaeu.com
97290	2022-02-22 15:23:31,348215	192.168.2.87	192.168.2.47	DNS	91	Standard query 0x1dff A m2.tuyaeu.com
97291	2022-02-22 15:23:31,350665	192.168.2.47	192.168.2.87	DNS	109	Standard query response 0x1dff A m2.tuyaeu.com A 0.0.0.0
97697	2022-02-22 15:23:31,465734	192.168.2.87	0.0.0.0	TCP	76	40788 → 8886 [SYN] Seq=0 Win=4380 Len=0 MSS=1460
  • Pihole seems to be working, as I can see blocked requests to m2.tuyaeu.com, which means IP is given as 0.0.0.0.
  • My test script is pinging moodlight cyclically every 60s.
  • But after some hours working moodlight no longer replies to one of this pings, but continues working the next minute.
  • Now start running tuya-mqtt works quite fine.
  • But after some hours working moodlight no longer replies to pings again, which causes connection error messages in tuya-mqtt debug output.
  • It seems that sometimes tuya-mqtt is not able to reconnect correctly again.

My questions:

  • Is that what I whatched the so-called zombie state? If so, is something wrong in my configuration with fritzbox and pihole? I thought, in this configuration the zombie state should already be avoided.
  • Did you ever discover a state, the tuya device stops answering pings, but can be “awaked” somehow?
  • Do you have a tip, what could make the reconnect of tuya-mqtt more stable? If you give me some hints I could try myself and let you know if I succeed.

This is how tuya_mqtt starts working:

  tuya-mqtt:tuyapi Search for device id bfxxxxxxxxxxxxxxxxsoqx +0ms
  tuya-mqtt:tuyapi Found device id bfxxxxxxxxxxxxxxxxsoqx +7ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"20":false,"26":0} +197ms
  tuya-mqtt:tuyapi Connected to device LSC Moodlight RGB+CCT (192.168.2.87, bfxxxxxxxxxxxxxxxxsoqx, 924213fa9a2161fb) +882ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/21/command","message":"colour"} +0ms
  tuya-mqtt:command Received command for DPS21:  colour +0ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"21","set":"colour"} +77ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/22/command","message":"920"} +17ms
  tuya-mqtt:command Received command for DPS22:  920 +14ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"22","set":920} +14ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/23/command","message":"625"} +3ms
  tuya-mqtt:command Received command for DPS23:  625 +4ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"23","set":625} +3ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/24/command","message":"000003e803e8"} +2ms
  tuya-mqtt:command Received command for DPS24:  000003e803e8 +2ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"24","set":"000003e803e8"} +2ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/25/command","message":"19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000"} +3ms
  tuya-mqtt:command Received command for DPS25:  19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000 +3ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"25","set":"19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000"} +3ms
  tuya-mqtt:command Received MQTT message ->  {"topic":"tuya/lsc_moodlight_rgb_cct/DPS/20/command","message":"false"} +3ms
  tuya-mqtt:command Received command for DPS20:  false +2ms
  tuya-mqtt:tuyapi Set device bfxxxxxxxxxxxxxxxxsoqx -> {"dps":"20","set":false} +2ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"20":false,"26":0} +71ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"20":false,"26":0} +0ms
  tuya-mqtt:state MQTT DPS20: tuya/lsc_moodlight_rgb_cct/dps/20/state ->  false +2ms
  tuya-mqtt:state MQTT DPS26: tuya/lsc_moodlight_rgb_cct/dps/26/state ->  0 +1ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"21":"colour"} +361ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"21":"colour"} +356ms
  tuya-mqtt:state MQTT DPS21: tuya/lsc_moodlight_rgb_cct/dps/21/state ->  colour +2ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"21":"white","22":920} +205ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"21":"white","22":920} +203ms
  tuya-mqtt:state MQTT DPS21: tuya/lsc_moodlight_rgb_cct/dps/21/state ->  white +0ms
  tuya-mqtt:state MQTT DPS22: tuya/lsc_moodlight_rgb_cct/dps/22/state ->  920 +1ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"21":"white","23":625} +206ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"21":"white","23":625} +204ms
  tuya-mqtt:state MQTT DPS21: tuya/lsc_moodlight_rgb_cct/dps/21/state ->  white +1ms
  tuya-mqtt:state MQTT DPS23: tuya/lsc_moodlight_rgb_cct/dps/23/state ->  625 +1ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"21":"white","24":"000003e803e8"} +204ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"21":"white","24":"000003e803e8"} +203ms
  tuya-mqtt:state MQTT DPS21: tuya/lsc_moodlight_rgb_cct/dps/21/state ->  white +1ms
  tuya-mqtt:state MQTT DPS24: tuya/lsc_moodlight_rgb_cct/dps/24/state ->  000003e803e8 +1ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"21":"white","25":"19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000"} +307ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"21":"white","25":"19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000"} +305ms
  tuya-mqtt:state MQTT DPS21: tuya/lsc_moodlight_rgb_cct/dps/21/state ->  white +1ms
  tuya-mqtt:state MQTT DPS25: tuya/lsc_moodlight_rgb_cct/dps/25/state ->  19464601007803e803e800000000464602006e0320025800000000464602005a038403e800000000 +0ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"20":false} +208ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"20":false} +207ms
  tuya-mqtt:state MQTT DPS20: tuya/lsc_moodlight_rgb_cct/dps/20/state ->  false +1ms
  tuya-mqtt:tuyapi Received JSON data from device bfxxxxxxxxxxxxxxxxsoqx -> {"20":false,"26":0} +3ms
  tuya-mqtt:state MQTT DPS JSON: tuya/lsc_moodlight_rgb_cct/dps/state ->  {"20":false,"26":0} +2ms
  tuya-mqtt:state MQTT DPS20: tuya/lsc_moodlight_rgb_cct/dps/20/state ->  false +1ms
  tuya-mqtt:state MQTT DPS26: tuya/lsc_moodlight_rgb_cct/dps/26/state ->  0 +1ms

But after a while, sometimes after minutes only, sometimes after hours:

 tuya-mqtt:tuyapi Found device id bfxxxxxxxxxxxxxxxxsoqx +1ms
 tuya-mqtt:error Error: Error from socket
 tuya-mqtt:error     at Socket.client.on.err (/opt/tuya-mqtt/node_modules/tuyapi/index.js:399:30)
 tuya-mqtt:error     at Socket.emit (events.js:198:13)
 tuya-mqtt:error     at emitErrorNT (internal/streams/destroy.js:91:8)
 tuya-mqtt:error     at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
 tuya-mqtt:error     at process._tickCallback (internal/process/next_tick.js:63:19) +12s
 tuya-mqtt:error connect EHOSTUNREACH 192.168.2.87:6668 +2ms
 tuya-mqtt:error Error connecting to device id bfxxxxxxxxxxxxxxxxsoqx...retry in 10 seconds. +0ms

Its really a pity that tuya devices are so complicated. In principle everything works, but I really hate the continued sending of something into the internet, this is really a no-go for me. The idea of blocking devices internet access is ok for me, but does not seem to be without negative consequences for the systems stability, or maybe I made a mistake in my blocking setup. I also thought about changing to tasmota, even if I had to open the device for connecting to flash the alternative firmware. But even this is no option for the moodlight as I contains CB3S module instead of ESP-12 or similar. Obviously there is no tasmota firmware for CB3S, so I would need to open, dissolder the old module with a heat gun and solder a new module with new firmware https://templates.blakadder.com/lsc_smart_connect_3004154.html. This seems to be possible… but unfortunately not for me. So I still hope to find an option how to use the device with original firmware. Any ideas or hints appreciated…

Unhandled exception if Tuya device is removed

The script is working wonderful for me, but I found one issue:

When removing a controlled tuya device physically (e.g. removing a bulb from the socket), the script ends with a uncaught exception.

So far I worked around this issue with a Shell-Script checking every 5 minutes if the script is running, and if not start it again, but it would be nice if the script catches the exception and handles it when device is removed.

Roller Shutter doesn't work

HI

I have problem with RollerShutter
When I use command from NJSTuya - is no problem
node Njstuja -id xxxxxxxxx -keyxxxxxxxxxxxxx -ipxxxxxxxxxxxxx -set '{"set":"1"}'
\But I can't use in similar way tuya-mqtt
Whhn I setup "Open" as a {"set":"1") close {"set":"2"} or stop {"set":"3"} I can't manage it ;( for Rollershutter
But when I use "Switch" object I can setup using on-{"set":"1") off-{"set":"2"} but I have no third otpion to stop it;(
May i ak you where is the problem
I have OpenHab2.4
and MQtt broker 2.4
I testes on tuya-mqtt from TheAgentK and from tsightler
on both the same error
(if u want Received data in details - let me know I can generate it but i don't want any data on the portal ;)

12:34:01] openhabian@openhab:/etc/openhab2/scripts/tuya-mqtt3$ DEBUG=* node tuya-mqtt.js
TuyAPI:mqtt Connection established to MQTT server +0ms
TuyAPI:mqtt receive settings {"topic":"tuya/xxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx/192.168.x.xxx/command","action":"command","message":"100","options":{"id":"xxxxxxxxxxxxxxxxxxxx","key":"xxxxxxxxxxxxxxxxxxxx","ip":"192.168.x.xxx"}} +4s
TuyAPI:device Search device in network +0ms
TuyAPI IP and ID are already both resolved. +0ms
TuyAPI:device Device found in network +7ms
TuyAPI Connecting to 192.168.x.xxx... +10ms
TuyAPI Socket connected. +8ms
TuyAPI:device Connected to device. (192.168.x.xxx, xxxxxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxxxxxx) +14ms
TuyAPI GET Payload: +3ms
TuyAPI { gwId: 'xxxxxxxxxxxxxxxxxxxx', devId: 'xxxxxxxxxxxxxxxxxxxx' } +1ms
TuyAPI:mqtt command is JSON +55ms
TuyAPI:mqtt receive command 100 +0ms
TuyAPI:device set: 100 +29ms
(node:31548) UnhandledPromiseRejectionWarning: TypeError: No arguments were passed.
at TuyaDevice.set (/etc/openhab2/scripts/tuya-mqtt3/node_modules/tuyapi/index.js:158:13)
at Promise (/etc/openhab2/scripts/tuya-mqtt3/tuya-device.js:158:25)
at new Promise ()
at TuyaDevice.set (/etc/openhab2/scripts/tuya-mqtt3/tuya-device.js:157:16)
at /etc/openhab2/scripts/tuya-mqtt3/tuya-mqtt.js:346:33
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:31548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:31548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
TuyAPI Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +35ms
TuyAPI Parsed: +7ms
TuyAPI { payload: 'json obj data unvalid',
TuyAPI leftover: false,
TuyAPI commandByte: 10,
TuyAPI sequenceN: 1 } +0ms
TuyAPI:device:error Data from device not encrypted: json obj data unvalid +0ms
(node:31548) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '1' of undefined
at _send.then.data (/etc/openhab2/scripts/tuya-mqtt3/node_modules/tuyapi/index.js:122:29)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:31548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
TuyAPI Pinging 192.168.x.xxx +10s
TuyAPI Received data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+5ms
TuyAPI Parsed: +1ms
TuyAPI { payload: false, leftover: false, commandByte: 9, sequenceN: 0 } +1ms

get-states not fully using templates in devices.conf

I've tried to use the "get-states" command to get all DPS from a device. In addition, I have a template defined in devices.conf. Now it seems as the template is not fully used in this case.

Here's the devices.conf file:

[
  {
    name: 'Aiibot Air Purifier',
    id: 'xxxxxxxxxxxxxxxxx',
    key: 'yyyyyyyyyyyyyyy',
    ip: '10.10.1.42',
    version: '3.3',
    type: 'GenericDevice',
        template: {
            power_state: {
              key: '1',
              type: 'bool'
            },
            pm25_state: {
              key: '2',
              type: 'int'
            },
            mode_state: {
              key: '3',
              type: 'string'
            },
            speed_state: {
              key: '4',
              type: 'string'
            }
        }
  }
]

and here's what happens when I issue the get-states command:

tuya/aiibot_air_purifier/command get-states
tuya/aiibot_air_purifier/power_state ON
tuya/aiibot_air_purifier/pm25_state 8
tuya/aiibot_air_purifier/dps/state {"1":true,"2":8,"3":"auto","4":"1","7":false,"19":"0","22":"1"}
tuya/aiibot_air_purifier/dps/1/state true
tuya/aiibot_air_purifier/dps/2/state 8
tuya/aiibot_air_purifier/dps/3/state auto
tuya/aiibot_air_purifier/dps/4/state 1
tuya/aiibot_air_purifier/dps/7/state false
tuya/aiibot_air_purifier/dps/19/state 0
tuya/aiibot_air_purifier/dps/22/state 1

I would have expected to get the topics:

tuya/aiibot_air_purifier/power_state
tuya/aiibot_air_purifier/pm25_state
tuya/aiibot_air_purifier/mode_state  
tuya/aiibot_air_purifier/speed_state

Instead I only get values for the first two (power_state and pm25_state) and mode_state and speed_state are missing.

Use MQTT message payload rather than topic to set switch state

Is your feature request related to a problem? Please describe.
The 2.4 OpenHAB MQTT bindings have entries for only a single state topic, and a single command topic. This makes sense as it's normal for the command channel to act on the message payload rather than on the topic itself. The current tuya-mqtt is not easily usable with the 2.4 since it requires two command topics and completely ignores the message payload.

Describe the solution you'd like
Instead of using separate topics for on/off, use a single topic and act on the message payload. For the case of example, if using the mosquitto_pub cmdline tool today I have to run:
mosquitto_pub -t '<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/on' -m '' mosquitto_pub -t '<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command/off' -m ''

I can literally put anything I want in the message field but it ignores it, only the topic matters. I'm an MQTT newbie, but this seems unusual and not how other devices work. Most have a command topic, and you can publish any number of commands there via the message like this:

mosquitto_pub -t '<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command' -m 'on' mosquitto_pub -t '<tuyaAPI-type>/<tuyaAPI-id>/<tuyaAPI-key>/<tuyaAPI-ip>/command' -m 'off'

This is what the OpenHAB 2.4 MQTT bindings expect.

I have tested the following patch, which maintains the existing behavior, so it shouldn't break existing bindings, but, if you including only the /command topic, it instead acts on the message. Simple replace:

        if (exec == "command") {
            var status = topic[6];
            device.onoff(status);
        }

With the following:

        if (exec == "command") {
            var status = topic[6];
            if ( status == null ) {
                device.onoff(message);
            } else {
                device.onoff(status);
            }
        }

I've tested this small change with both the only 1.X bindings configured as they worked previously, and the new 2.4 using a single command topic and both seem to work properly.

Describe alternatives you've considered
I could keep using the 1.X bindings, which worked fine, but can't be configured via Paper UI (not a huge deal). With the 2.4 bindings I had bound a status only thing (left command topic blank) and used a rule which directly called publishMQTT to the different topics based on the received ON/OFF command. This also worked fine but required a rule for every device, which seemed ugly and also couldn't be configured via the Paper UI. With the fix above, just add an MQTT Generic Thing with the proper state and command topics, link it to an item, and you're done.

Constant off states after start

Great project!
I tried the wrapper in a small linux test environment and it seems to work and detect device switches correctly. Unfortunately right after the first correct state, i get a constant stream of 'off' state messages from the state topic.

Ubuntu 18.04
Mosquito in a docker 1.5
nodejs v8.10.0

I am using a TECKIN WLAN Smart socket.

Steps to reproduce the behavior:

  1. Start local freshly mosquitto (deleted mosquitto.db)
  2. Starting tuya-mqtt.js in degug
  3. Log shows connect to mqqt broker
  4. Connect to broker with mqqt.fx client (broker status shows two clients connected)
  5. subscribe to device state topic (tuya/socket/022000606001946fedd5/9b278320e6e41c83/192.168.180.104/state)
    the device id and localkey were tested with the tuyaapi work switching the device
  6. send 'on' paload to device command topic
  7. devices witches on
  8. state topic switches to 'on'
  9. a second later state topic switches to 'off' while the device is still on and repeates sending this indefinitely

I would expect the wrapper to send the current status. Maybe I'm understanding mqqt wrong and this is a retained message? Any idea how to solve this? I would attach the debug output, but I don#t have a lot of experience in nodejs and don#t know how to pipe the node console outputin a file.

thanks for any help

Can't get version 3 to work

I'm certainly missing somthing dumb, version 2 was working fine with somewhat the same setup.

Here is my config :

Dockerfile

FROM node

RUN git clone --single-branch --branch dev https://github.com/TheAgentK/tuya-mqtt.git && \
    cd tuya-mqtt && \
    npm install

WORKDIR /tuya-mqtt

COPY config.json .

ENV DEBUG=*

ENTRYPOINT ["node", "tuya-mqtt.js"]

relevant docker-compose conf:

  tuya-mqtt:
    container_name: tuya-mqtt
    image: tromatik/tuya-mqtt
    depends_on:
      - mqtt-broker
    volumes:
      - ./tuya-mqtt/config.json:/tuya-mqtt/config.json
      - ./tuya-mqtt/devices.conf:/tuya-mqtt/devices.conf
    restart: always
    environment:
      - TZ=Europe/Paris
      - DEBUG=-*
    networks:
      backend:
      physical:
        ipv4_address: 192.168.0.4

config.json

{
    "host": "192.168.0.10",
    "port": 1883,
    "topic": "tuya/",
    "mqtt_user": "",
    "mqtt_pass": "",
    "qos": 2
}

device.conf

[
  {
    name: 'LED SMART 2',
    id: 'bff590a2c25cf0a2bazufd',
    key: '607663889df63108',
    version: '3.3'
  },
  {
    name: 'Smart Switch 1',
    id: 'bf84deb2a2b0c4496bsrsf',
    key: '9f95ebd825dbac96',
    version: '3.3'
  },
  {
    name: 'Smart Plug',
    id: 'bf22ba559b69252a12fldr',
    key: '473fac1b23a77103',
    version: '3.3'
  }
]

Test OK with tuya-cli : tuya-cli set --id bff590a2c25cf0a2bazufd --key 607663889df63108 --dps 1 --set true/false

Test KO when publishing tuya/bff590a2c25cf0a2bazufd/dps/1/command true

Logs when publishing to mqtt :

2020-10-09T22:06:43.696Z mqttjs:client writable stream :: parsing buffer
2020-10-09T22:06:43.696Z mqtt-packet:parser parse: current state: _parseHeader
2020-10-09T22:06:43.697Z mqtt-packet:parser _parseHeader: packet: Packet { cmd: 'publish', retain: false, qos: 0, dup: false, length: -1, topic: null, payload: null }
2020-10-09T22:06:43.697Z mqtt-packet:parser parse: state complete. _stateCounter is now: 1
2020-10-09T22:06:43.697Z mqtt-packet:parser parse: packet.length: -1, buffer list length: 49
2020-10-09T22:06:43.697Z mqtt-packet:parser _parseVarByteNum
2020-10-09T22:06:43.697Z mqtt-packet:parser parse: packet.length: 48, buffer list length: 48
2020-10-09T22:06:43.699Z mqtt-packet:parser _parsePayload: payload BufferListStream {
  _bufs: [
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
2020-10-09T22:06:56.041Z mqttjs:client _checkPing :: checking ping...
2020-10-09T22:06:56.046Z mqttjs:client _checkPing :: ping response received. Clearing flag and sending `pingreq`
2020-10-09T22:06:56.048Z mqttjs:client _sendPacket :: (mqttjs_57bc5e7b) ::  start
2020-10-09T22:06:56.050Z mqttjs:client sendPacket :: packet: { cmd: 'pingreq' }
2020-10-09T22:06:56.051Z mqttjs:client sendPacket :: emitting `packetsend`
2020-10-09T22:06:56.052Z mqttjs:client sendPacket :: writing to stream
2020-10-09T22:06:56.052Z mqtt-packet:writeToStream generate called
2020-10-09T22:06:56.053Z mqtt-packet:writeToStream generate: packet.cmd: pingreq
2020-10-09T22:06:56.054Z mqttjs:client sendPacket :: writeToStream result true
2020-10-09T22:06:56.055Z mqttjs:client writable stream :: parsing buffer
2020-10-09T22:06:56.055Z mqtt-packet:parser parse: current state: _parseHeader
2020-10-09T22:06:56.056Z mqtt-packet:parser _parseHeader: packet: Packet { cmd: 'pingresp', retain: false, qos: 0, dup: false, length: -1, topic: null, payload: null }
2020-10-09T22:06:56.057Z mqtt-packet:parser parse: state complete. _stateCounter is now: 1
2020-10-09T22:06:56.058Z mqtt-packet:parser parse: packet.length: -1, buffer list length: 1
2020-10-09T22:06:56.058Z mqtt-packet:parser _parseVarByteNum
2020-10-09T22:06:56.059Z mqtt-packet:parser _parseVarByteNum: result: { bytes: 1, value: 0 }
2020-10-09T22:06:56.060Z mqtt-packet:parser _parseLength 0
2020-10-09T22:06:56.060Z mqtt-packet:parser parse: state complete. _stateCounter is now: 2
2020-10-09T22:06:56.061Z mqtt-packet:parser parse: packet.length: 0, buffer list length: 0
2020-10-09T22:06:56.062Z mqtt-packet:parser _parsePayload: payload BufferListStream {
  _bufs: [],
    needDrain: false,
    ending: false,
    ended: false,
2020-10-09T22:06:56.067Z mqtt-packet:parser _parsePayload complete result: true
2020-10-09T22:06:56.068Z mqtt-packet:parser parse: state complete. _stateCounter is now: 3
2020-10-09T22:06:56.069Z mqtt-packet:parser parse: packet.length: 0, buffer list length: 0
2020-10-09T22:06:56.069Z mqtt-packet:parser _newPacket
2020-10-09T22:06:56.070Z mqtt-packet:parser _newPacket: parser emit packet: packet.cmd: pingresp, packet.payload: null, packet.length: 0
2020-10-09T22:06:56.070Z mqttjs:client parser :: on packet push to packets array.
2020-10-09T22:06:56.071Z mqtt-packet:parser _newPacket: new packet
2020-10-09T22:06:56.071Z mqtt-packet:parser parse: state complete. _stateCounter is now: 4
2020-10-09T22:06:56.072Z mqtt-packet:parser parse: packet.length: -1, buffer list length: 0
2020-10-09T22:06:56.072Z mqtt-packet:parser parse: exited while loop. packet: -1, buffer list length: 0
2020-10-09T22:06:56.073Z mqttjs:client work :: getting next packet in queue
2020-10-09T22:06:56.073Z mqttjs:client work :: packet pulled from queue
2020-10-09T22:06:56.074Z mqttjs:client _handlePacket :: emitting packetreceive

Manually turning on the Tuya device will receive both on and off

image
I'll receive on and off at the same time when I manually turn on the Tuya device, and I'll receive off and off when I turn off the device.

I don't know if I'm the only one with this error, here's the code I found the problem with:

TuyaDevice.onAll('data', function (data) {
    try {
        debugTuya('Data from device ' + this.type + ' :', data);
        var status = data.dps['1'];
        if (this.type == "lightbulb" && status == undefined) {
            status = true;
        }
        publishStatus(this, bmap(status));
        publishDPS(this, data.dps);
    } catch (e) {
        debugError(e);
    }
});

data will receive two times the metadata {"1": true} and {"11": 0}, which will cause the status to produce a undefined

When I judge status as undefined, I do nothing to solve the above problems.

Support for Tuya dimmer switches

Does tuya-mqtt currently support dimmer switches (other than on/off control)? If so, are there any instructions/examples available?
In the dimmers I have, dps 1 is a bool for on/off and dps 2 is a number (0-255) for the brightness.
It would be great if there were topics that increased/decreased the brightness (dps 2), that could then be configured in openhab.
Thanks for considering this request.

Samples for nodejs script

I'm sorry, but I can't find any sample or the real API documentation for controlling my RGB Led Device using this library. Or am I missing something? Thanks for your work on the library, btw.

Could not read from remote repository

$ git clone [email protected]:TheAgentK/tuya-mqtt.git

Cloning into 'tuya-mqtt'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Version 3.0 Discussion

I pushed v2.1.0 yesterday, which is mostly a backlog of small fixes and support for 3.3, but I think it's time to perform a more significant revamp with the goal of simplifying the use of tuya-mqtt with various home automation tools, based off my experience building and maintaining the ring-mqtt project. Below is a current list of things I'm thinking, it's somewhat of a major shift, but I think it will make using this project a LOT easier for many users as the barrier is already quite high with the need to create accounts with Tuya and get keys I think it would at least be good to make using this tool as easy as possible.

Open to hear all thoughts on the below ideas.

Use devices configuration file instead of requiring set to MQTT topic to establish initial connection

  • Format is exactly the same as tuya-cli wizard option produces for output
  • Validates and connects to devices on startup and sends state updates

Simplify topics -- topics would be of the following formats:
tuya/<friendly_name_or_device_id>/state <-- String (ON/OFF)
tuya/<friendly_name_or_device_id>/command <-- String (ON/OFF, 0/1, true/false, etc)
tuya/<friendly_name_or_device_id>/brightness_state <-- Value (1-255)
tuya/<friendly_name_or_device_id>/brightness_command <-- Value (1-255)
tuya/<friendly_name_or_device_id>/color_state
tuya/<friendly_name_or_device_id>/color_command
tuya/<friendly_name_or_device_id>/dps/state <-- Get raw TuyAPI JSON
tuya/<friendly_name_or_device_id>/dps/command <-- Set raw TuyAPI JSON
tuya/<friendly_name_or_device_id>/dps/1/state <-- String (get DPS value)
tuya/<friendly_name_or_device_id>/dps/1/command <-- String (set DPS value)

Friendly name would be based on output of devices from tuya-cli, which includes device name from Tuya app, for example "Kitchen Lights" becomes tuya/kitchen_lights. Simply delete friendly name from device config to use device ID instead.

The state/color/brightness states and commands would use the format of Home Assistant, which I believe is also easily consumable for OpenHAB and other home automation tools (standard format use by, for example, Tasmota).

Overall I believe implementing simple command for state/brightness/color will make integration of those devices easier, and allowing individual DPS states to be set without JSON templates will make other setups easier as well, although it will still be possible to get/set via tuya based raw JSON values using dps and dps/set

Ideally implement Home Assistant style MQTT discovery (this is a stretch goal)
This will make it easier to integrate into other tools (like OpenHAB) that also support Home Assistant style MQTT discovery. Initially probably only for sockets/lights/switches since I don't have other devices.

Setting switch state of a smart switch (custom template)

Hoping someone can help. Just go my first tuya devices and are trying to get them going in openhab.

template: {
      state: {
        key: 1,
        type: 'bool'
      },
      power_state: {
        key: 1,
        type: 'bool'
      }
}

With the following partial template, for a smart switch with power monitoring (excluded the volts etc) I can get the volts fine (dp2/20).

But i can't get the power/state command to work to set the power on or off.
I've left state as is and have tried:

sensors/tuya/kogan-02/dps/1/state 1
sensors/tuya/kogan-02/dps/1/state 0
sensors/tuya/kogan-02/DPS/1/state 0
sensors/tuya/kogan-02/dps/1/state false
sensors/tuya/kogan-02/dps/1/command 1
sensors/tuya/kogan-02/dps/1/command false
sensors/tuya/kogan-02/dps/1/command Off
sensors/tuya/kogan-02/dps/1/command OFF
sensors/tuya/kogan-02/dps/1/command off
sensors/tuya/kogan-02/state/command off
sensors/tuya/kogan-02/power/command OFF
sensors/tuya/kogan-02/power_state/command OFF

What am I doing wrong?

Protocol version 3.3 how to add this to mqtt

I really like your script and used it the past year, then I do an update on my sockets damn

Now I got it working again with newest versions, but only with tuya-cli and not with mqtt anymore, due to missing command, might be you can help me getting it working again. This is my command to toogle the socket:
tuya-cli set --ip '192.168.178.75' --id '68282475600194c05b0a' --key '5e72b8aeb3baa470' --dps 1 --set 'true' --protocol-version 3.3

Not sure when you went into Maintenance mode

!!! 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
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

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):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

The Tuya API project was updated with support for DP-Refresh - are you supporting this in your current implementation ?

I have done an install as of 13/5/21 and hence have the latest versions of tuyaapi and your great stuff.

I have this successfully working - but my heatpump does not send out periodic refreshes - as such i need to query it on a regular basis to see various operating parameters.

I am not a coder (can hack around bash scripts and Powershell) so can not take on maintenance of this project unfortunately. But am loving what you have done and being able to feed it into Node Red through MQTT is brilliant.

Craig

"parse data error" when requesting /state before 1st command

I did some tracing as sometimes everything works fine and sometimes it doesn't work at all. First of all I realized that when using protocol version 3.3 the state-response will be on the non "ver3.3"-topic.

mosquitto_pub -t tuya/ver3.3/bf0751f4b74d39cXXXXXXX/eacb979dbXXXXXXX/192.168.103.14/command -m "ON"

updates this topic:

tuya/bf0751f4b74d39cXXXXXXX/eacb979dbXXXXXXX/192.168.103.14/state

Ok, so as a workaround I tried to use tuya/ver3.3 for commands and tuya/ as state topic. With this config I had a 50/50 chance to work :-) I restarted tuya-mqtt and tried:

mosquitto_pub -t tuya/bf0751f4b74d39cXXXXXXX/eacb979dbXXXXXXX/192.168.103.14/state -n

Result:

  TuyAPI Parsed: +13ms
  TuyAPI {
  TuyAPI   payload: 'parse data error',
  TuyAPI   leftover: false,
  TuyAPI   commandByte: 10,
  TuyAPI   sequenceN: 1
  TuyAPI } +

Next try: Restart tuya-mqtt and send:

mosquitto_pub -t tuya/ver3.3/bf0751f4b74d39cXXXXXXX/eacb979dbXXXXXXX/192.168.103.14/command -m "ON"

Result: No parse data error => everything works fine!
Now I can even query the state-topic and the result is ok:

TuyAPI:mqtt receive settings {"topic":"tuya/bf0751f4b74d39cXXXXXXX/eacb979dbXXXXXXX/192.168.103.14/state","action":"state","message":"","options":{"id":"bf0751f4b74d39cXXXXXXX","key":"eacb979dbXXXXXXX","ip":"192.168.103.14"}} +11ms

I did many other tests but the result is always the same: If you don't send a valid (ver3.3) command after starting tuya-mqtt, you will receive parse-errors for any following command. Even if you send a command to non "ver3.3" first, you will hit the same problem. Instead: If you send a valid command first, you can do whatever you want and everything works like a charme...

convertMessage function breaks on/off for switch

Perhaps this is not a bug but I'm really struggling to understand what the latest patch was intended to do, and, for my simple environment (just switches and plugs) it completely broke a setup that worked perfectly before. Was there intentionally a change in behavior?

Specifically I don't understand this code:

function boolToString(istate) {
    return istate == 1 ? 'on' : "off";
}

function convertMessage(message) {
    var status = message.toString();
    status = boolToString(status);
    status = status.toLowerCase();
    return status;
}

Typically the message is either "ON" or "OFF", at least, it was, and the examples are still written this way, however, the code above will always return off in this case. It will work if you pass it 1/0 or maybe somehow true/false, although true/false as a string will not work. Even more confusing, earlier in the code there was already a function call boolToString which behaved differently:

function boolToString(istate) {
    return istate ? 'true' : "false";
}

Just having two functions with the same name that do different things seems incorrect. I'd submit a patch to try to fix it, but I'm not sure what the intended behavior of this patch was supposed to be.

Permission denied (publickey).

Describe the bug
The git clone is failing

To Reproduce
Steps to reproduce the behavior:
openhabian@openhabian:/etc/openhab2/scripts $ git clone [email protected]:TheAgentK/tuya-mqtt.git
Clonage dans 'tuya-mqtt'...
Permission denied (publickey).

image

commandTopic not working as described with MQTT 2.4 Binding

Installed the actual script with OH MQTT-binding 2.4, stateTopic is working, commandTopic not:

mqtt.things:

Bridge mqtt:broker:myUnsecureBroker [ host="127.0.0.1", secure=false ] { Thing mqtt:topic:mything { Channels: Type switch : Tuya_Bulb_1_mqtt "LED1 MQTT" [ stateTopic="tuya/lightbulb/12204702807d3a49b2ae/dd28170cbf5dcd08/192.168.75.118/state", commandTopic="tuya/lightbulb/12204702807d3a49b2ae/dd28170cbf5dcd08/192.168.75.118/command" ] } }

item:

Switch tuya_OG_Schlafzimmer1_mqtt "LED1 MQTT 1" <light> {channel="mqtt:topic:mything:Tuya_Bulb_1_mqtt"}

sitemap:

Switch item=tuya_OG_Schlafzimmer1_mqtt label="LED1 MQTT 1"

Expected:

Switching switches light on and off

Behaviour:

When switching light with external app, change of state is reflected. But switching with commandTopic does not work.

Changing commandTopic to

commandTopic="tuya/lightbulb/12204702807d3a49b2ae/dd28170cbf5dcd08/192.168.75.118/command/on" ]

at least switches light on, like before last update.

Home Assistant integration how?

I read in Issue #55 about Home Assistant Integration being possible, but I'm not sure if you mean running this instead of the built in MQTT broker? or something else? I think I'm missing some knowledge or understanding.

I have 2 smart bulbs that are geeni, which is based on Tuya like so many of them. I have registered these bulbs as instructed in the TuyaAPI setup pages, and they are retrieved with the tuya-cli wizard. However, I'm not sure how to make the next step of getting this step into Home Assistant. It appears as though by default the Home Assistant MQTT connector for Tuya only works with Tuya App, Smart life and Jinvoo, which do not require the cloud app setup as described. So I'm not sure how this all fits together. I would like to use this project as it implies I might be able to send requests to the bulbs directly.

Thanks

New Maintainer Needed

As I have decided to rid myself of Tuya devices, I'm going to be stepping away from maintaining this project. I've enjoyed developing this project and have actively used it to control my Tuya devices for the last few years and I'm happy to see that this project is still widely used. Unfortunately it takes up too much time, mostly due to the sheer number and variation of Tuya devices and the fact that Tuya continues to make it more and more difficult for users to control those devices locally.

There's nothing inherently wrong with this, and they certainly have that right, it simply means that Tuya devices do not align with my personal goals for my home automation devices and thus I won't be purchasing any more of them and will actively work to remove the last few Tuya devices I have.

If you are interested in maintaining this project going forward, please feel free to post a note below. In the interim, I will try to at least keep this project working.

Multi-switch support

Support switch devices that contain multiple switches.

Moving the discussion from: PR #49 (unrelated code)

Summary:
I added support for multi-switches in my fork of this repo but did not realize the config schema was based on homebridge-tuya (thanks @tsightler for pointing this out). My solution works but likely does not conform to any previously established standards since I made it up.

I am sure some of my code can still be used but it will need to be modified. I also added device type guessing and mdl guessing logic which I hope can be kept as well since it helps simplify the devices.conf file for common configurations.

This is my working implementation for multi-switches here: https://github.com/dkrahmer/tuya-mqtt/pull/2/files

All MQTT messages are published with {qos:1, retain:false}

See this:

tuya-mqtt/tuya-mqtt.js

Lines 87 to 92 in 8f8d4fb

if (typeof CONFIG.qos == 'undefined') {
CONFIG.qos = 1
}
if (typeof CONFIG.retain == 'undefined') {
CONFIG.retain = false
}

And compare with:

  • // Publish MQTT
    publishMqtt(topic, message, isDebug) {
    if (isDebug) { debugState(topic, message) }
    this.mqttClient.publish(topic, message, { qos: 1 });
    }

    and:
  • tuya-mqtt/tuya-mqtt.js

    Lines 108 to 113 in 8f8d4fb

    mqttClient = mqtt.connect({
    host: CONFIG.host,
    port: CONFIG.port,
    username: CONFIG.mqtt_user,
    password: CONFIG.mqtt_pass,
    })

Observations / remarks:

  1. CONFIG.qos and CONFIG.retain is essentially dead code (either to restore or delete entirely)
  2. IMHO at least the availability topic (<device>/status) should be published with retain: true by default

Command Syntax for friendly topics

I cannot figure out how to send commands to friendly topics that I have defined with a Generic Device Template. There is no clue in the documentation either.

First of all, I have set up a Fairland Inverter Heat Pump (for my pool) and this is my devices.conf file:

[
  {
    name: 'Waermepumpe',
    id: 'xxxxx',
    key: 'xxxxx',
    template: {
      state: {
        key: 1,
        type: 'bool'
      },
      mode: {
        key: 2,
        type: 'str'
      },
      WInTemp: {
        key: 102,
        type: 'int'
      },
      change_tem: {
        key: 103,
        type: 'bool'
      },
      SpeedPercentage: {
        key: 104,
        type: 'int'
      },
      SetMode: {
        key: 105,
        type: 'str'
      },
      SetTemp: {
        key: 106,
        type: 'int',
        topicMin: 18,
        topicMax: 40
      },
      SetDnLimit: {
        key: 107,
        type: 'int'
      },
      SetUpLimit: {
        key: 108,
        type: 'int'
      },
      fault1: {
        key: 115,
        type: 'str'
      },
      fault2: {
        key: 116,
        type: 'str'
      }
    }
  }
]

What is working:

  • I get all the DPS-readings of the device
  • Sending message "On" or "Off" to topic tuya/waermepumpe/command (gets translated to {"dps":1,"set":false})
  • Sending message {"dps":106,"set":25} to topic tuya/waermepumpe/dps/command
  • Reading topic tuya/waermepumpe/SetTemp

What is not working:

  • Sending a command to topic tuya/waermepumpe/SetTemp
  • I tried e.g. tuya/waermepumpe/SetTemp/command with message "25", which simply does nothing.

So is this a bug? I had a look into the code and the function processDeviceCommand is only called when topicLength is 3 AND there is the word "command" in the command topic. I cannot figure out how to do this with topicLength 3. "tuya/waermepumpe/SetTemp/command" has a length of 4 ...

Btw. sorry to hear that this project is in maintenance mode. I am quite new to Tuya devices and I really appreciate this for communicating to my heat pump and integrating into FHEM - it already works quite well! I am aware that this project depends on tuyapi - but as long as it is working I will stick to it (I tried cloud API, but my device does not support all functions yet) and appreciate all the work done! Thank's a a lot!

Maintainer wanted!

Hello folks,

Unfortunately I have to inform you that I will not develop this project any further at the moment.
I've completely switched to Tasmota devices, so I don't need this interface anymore.

Please feel free to develop and use the project further!

Best regards
TheAgentK

tuyq-mqtt hangs ...

After running tuya-mqtt for about 2 weeks, I've noticed that tuya-mqtt published "offline" to the "status" topic even though the "node tuya-mqtt.js" process was running. The last message in the logfile (stdout) is:

(node:2422) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 126)
(node:2422) UnhandledPromiseRejectionWarning: Error: No connection has been made to the device.
    at TuyaDevice._send (/home/fhem/tuya-mqtt/node_modules/tuyapi/index.js:269:13)
    at Promise (/home/fhem/tuya-mqtt/node_modules/tuyapi/index.js:242:14)
    at new Promise (<anonymous>)
    at _setQueue.add (/home/fhem/tuya-mqtt/node_modules/tuyapi/index.js:238:46)
    at run (/home/fhem/tuya-mqtt/node_modules/p-queue/dist/index.js:153:104)
    at PQueue._tryToStartAnother (/home/fhem/tuya-mqtt/node_modules/p-queue/dist/index.js:101:38)
    at Promise (/home/fhem/tuya-mqtt/node_modules/p-queue/dist/index.js:167:18)
    at new Promise (<anonymous>)
    at PQueue.add (/home/fhem/tuya-mqtt/node_modules/p-queue/dist/index.js:148:16)
    at TuyaDevice.set (/home/fhem/tuya-mqtt/node_modules/tuyapi/index.js:238:27)
(node:2422) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 129)

strace says this:

$ strace -p 2422
strace: Process 2422 attached
epoll_pwait(13, [], 1024, 2338, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 5814, NULL, 8) = 0
write(18, "\300\0", 2)                  = 2
epoll_ctl(13, EPOLL_CTL_MOD, 18, {EPOLLIN, {u32=18, u64=18}}) = 0
epoll_pwait(13, [{EPOLLIN, {u32=18, u64=18}}], 1024, 4184, NULL, 8) = 1
read(18, "\320\0", 65536)               = 2
epoll_pwait(13, [], 1024, 4181, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, [], 1024, 10000, NULL, 8) = 0
epoll_pwait(13, ^Cstrace: Process 2422 detached
 <detached ...>

After restarting the "node tuya-mqtt.js" process, everything is good again.

Support for non numeric device id

Is your feature request related to a problem? Please describe.
All the examples I find assume the device id is a number, e.g. 1234567890ABCDEF, however, I have two lights where the device id is not a number e.g. : bff339668eb83f6350kkah
lsc

Describe the solution you'd like
Don't want it to crash on the non-numeric device id

tuya-mqtt correctly publishes state, but fails on command messages

I'm having some errors and general issues sending messages to a device using 'command'. Either it is acknowledged and nothing happens, or there is an error reported during debug.

tuya-mqtt acknowledges commands with debug logging, but does not actually perform any action when using the dps commands. Additionally, it receives an error when using the higher level command, or when calling the higher level state to query the device.

I can interact with the device via tuya-cli without problems, so these issues are localized to tuya-mqtt specifically. I can also use the dps state command, and verify states are changing, so it does not seem to be a mqtt sever issue either.

The device in question is a humidifier/oil diffuser, which is named 'Office Diffuser' (office_diffuser). I can provide more information on it if needed, but it seems to be at least correctly recognized by tuya-mqtt since it can publish state changes.


Issue 1 - high level command causes an error

I redacted the full file path for a heads up

tuya-mqtt:command Received MQTT message ->  {"topic":"device/tuya/office_diffuser/command","message":"{'dps':1,'set':'false'}"} +1s
tuya-mqtt:error TypeError: Cannot read property 'processDpsCommand' of undefined
tuya-mqtt:error     at MqttClient.<anonymous> (tuya-mqtt/tuya-mqtt.js:163:32)
tuya-mqtt:error     at MqttClient.emit (events.js:198:13)
tuya-mqtt:error     at MqttClient._handlePublish (tuya-mqtt/node_modules/mqtt/lib/client.js:1271:12)
tuya-mqtt:error     at MqttClient._handlePacket (tuya-mqtt/node_modules/mqtt/lib/client.js:410:12)
tuya-mqtt:error     at work (tuya-mqtt/node_modules/mqtt/lib/client.js:321:12)
tuya-mqtt:error     at Writable.writable._write (tuya-mqtt/node_modules/mqtt/lib/client.js:335:5)
tuya-mqtt:error     at doWrite (tuya-mqtt/node_modules/readable-stream/lib/_stream_writable.js:428:64)
tuya-mqtt:error     at writeOrBuffer (tuya-mqtt/node_modules/readable-stream/lib/_stream_writable.js:417:5)
tuya-mqtt:error     at Writable.write (tuya-mqtt/node_modules/readable-stream/lib/_stream_writable.js:334:11)
tuya-mqtt:error     at Socket.ondata (_stream_readable.js:710:20) +1s

Issue 2 - DPS command is received, but nothing happens

The following message is logged, but the device does not shut off like it is supposed to. Additionally, tuya-cli can correctly turn it on and off.

tuya-mqtt:command Received MQTT message ->  {"topic":"device/tuya/office_diffuser/dps/1/command","message":"false"} +3m

Issue 3 - State/subscription works (but only at DPS level)

I can correctly subscribe to the device and get messages back. Here, I turned it on and off via an app. However, using the higher level "/device/tuya/office_diffuser/state does not do anything

mosquitto_sub -L mqtts://name:pass@ip:port/device/tuya/office_diffuser/dps/1/state
false
true

Here is my devices.conf file too, with actual data redacted. However it does not seem to be the problem since tuya-mqtt does see the device and correctly publishes power on/off changes for the device.

[
 {
    name: 'Office Diffuser',
    id: 'xxxxxxxxx',
    key: 'xxxxxxxx',
    ip: '10.0.x.xx',
    version: '3.3'
  }
]

Let me know if you'd like to see anything else reported from the debug logging or if I can provide anything else. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.