Step-by-Step guide for adding Tuya-bulbs, Wi-Fi smart LED (Smart Life app) to OH2 using tuya-mqtt.js by AgentK

FYI you can us JS to transform the data being sent out. TransformationPattern formats data in and TransformationPatternOut formats data going out.

That’s incorrect in 2.4 the binding does not have that. That is only in 2.5 M1

Hello :slight_smile: I have several TECKIN and several Emylo SS-8839-03. No problem with TECKIN, all work fine. But with Emylo SS-8839-03, no command work. Any ideas ? I use MQTT-Binding 2.4 configuration . Thank you very much :slight_smile: (and sorry for my bad english)

Primarily, my post handles the control of colors of my hama WIFI Bulbs @HolgiHab I am very grateful for this tutorial and therefore I want to share my configuration.

The tutorial and those who wrote comments helped me to control the lamps (on, off, brightness). For the colors I had to think for myself :stuck_out_tongue_winking_eye:

My problem is already quite aptly described by @GadgetAngel

I tested the configuration with lamps on which the manufacturer “hama” has stuck his logo. Product Name: “WiFi-LED-Lampe, E27” or “WiFi LED-Bulp, E27” Product Number: 176550 (dimmable, warm white to daylight), 176547 (free color selection, dimmable)

There is no thing needed to control the colors. For completeness, I still post the things file.

tuyamqtt.things
Bridge mqtt:broker:e8dc2f1c "Tuya MQTT Broker" @ "Tuya" [ 
  host="127.0.0.1",
  secure=false,
  port=1883,
  qos=0,
  retain=false,
  clientid="paho3304251554845",
  //certificate="",
  //certificatepin=false,
  //publickey="",
  //publickeypin=false,
  keep_alive_time=30000,
  reconnect_time=60000,
  //lastwill_message="",
  //lastwill_qos=1,
  //lastwill_topic="",
  username="username",
  password="password"
]
{
    Thing mqtt:topic:HAMAColorBulbTwo "HAMABulbSwitch" @ "Tuya"  {
        Channels:
        Type switch : SWITCH 	[ 
            stateTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state", 
            commandTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command",
            on="ON", 
            off="OFF"
        ]
        Type dimmer : DIMMER 	[ 
             stateTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/dps/3", 
             commandTopic="tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/color", 
             min=1, 
             max=255, 
             step=1, 
             formatBeforePublish="0,0,%s" 
         ]
    }
}

colorbulbs.items

Switch HAMAColorBulbSwitchTwo   "HAMABulbSwitch"        <switch>    ["Switchable"]             {channel="mqtt:topic:HAMAColorBulbTwo:SWITCH"} 
Dimmer HAMAColorBulbDimmerTwo 	"Dimmer" 	            <dimmer>		                       {channel="mqtt:topic:HAMAColorBulbTwo:DIMMER" }
Color HAMAColorBulb_colorTwo    "Colorpicker"

colorbulb.rules

var HSBType hsbValue

rule "LEDColorChangingTwo"

when 
Item HAMAColorBulb_colorTwo received command
then 
    hsbValue = receivedCommand
              
    var red = hsbValue.red.intValue * 255 / 100
    var green = hsbValue.green.intValue * 255 / 100
    var blue = hsbValue.blue.intValue * 255 / 100   

    var String redValue = Long.toHexString(red)
    if (red < 16) redValue = "0" + redValue

    var String greenValue = Long.toHexString(green)
    if (green < 16) greenValue = "0" + greenValue

    var String blueValue = Long.toHexString(blue)
    if (blue < 16) blueValue = "0" + blueValue

    var rgbString = redValue + greenValue + blueValue
   
    val mqttActions = getActions("mqtt", "mqtt:broker:e8dc2f1c")
    mqttActions.publishMQTT("tuya/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command","{ \"multiple\": true, \"data\": { \"1\": true, \"2\": \"colour\", \"5\": \""+rgbString+"002effff\" } }")
    end

I have freed the rule from logging. Feel free to log what you want.

I use the Habpanel to control the lamps. For the MQTT-things a simple switch and the dimmer can be used. The colors I have controlled so far with the ready-made widget (colorpicker).

1 Like

Hi people,
I’m new to this so i’m trying to this step by step, and link some TUYA wall touch switches and PIR sensors.

Did managed to do some installations and obtain the tuya keys, but having issues running the following script:
/usr/bin/node /etc/openhab2/scripts/tuyaapi_mqtt/tuya-mqtt.js

$ /usr/bin/node /etc/openhab2/scripts/tuyaapi_mqtt/tuya-mqtt.js
module.js:549
    throw err;
    ^

    Error: Cannot find module '/etc/openhab2/scripts/tuyaapi_mqtt/tuya-mqtt.js'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

Will appreciate any help.

Many thanks

Hello , update for tuya devise.

tsightler has updated the script of TheAgentK ,now it work with device who used the 3.3 protocol. the script is here : https://github.com/tsightler/tuya-mqtt , but in few days it will be update the script on the officiel page. There is also the discovery ip, no need to put ip on the state topic and command topic.

Example :

tuya/<tuyAPI-id>/<tuyAPI-key>/discover/state
tuya/<tuyAPI-id>/<tuyAPI-key>/discover/command

If you want to put the ip , don"t forget to put ver3.3 between tuya and tuyAPI-id , example :

tuya/ver3.3/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/state
tuya/ver3.3/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/command

With the version 3.3 protocol you need also tu put on on/open value : 1 or ON and off/closed value : 0 or OFF

For device with DPS, as 2 ways device :

On/open value : { "dps": 1, "set": true }
Off/closed value : { "dps": 1, "set": false } 

and in state topic :
tuya/ver3.3/<tuyAPI-id>/<tuyAPI-key>/<tuyAPI-ip>/dps/1
or
tuya/<tuyAPI-id>/<tuyAPI-key>/discover/dps/1
but here i have a problem, because the tuyapi return true or false value for the state and openhab don’t know true or false state, but work with on or off…

2 Likes

So…after beating my head against the wall for about a fortnight over this it turns out there was a version mismatch.

At least it works now?

Thank you tsightler for the work and Fiftiz for the update! What resources are there around that I can access to improve my knowledge of his this works? I’d like to improve in this area, perhaps even contribute eventually.

Hello, Don’t forget to install the version of today (V2.0.3), there was a leak of memory because of “resolver” in the tuyapi code . but now it’s good. I will try today this new code.

All good.

I randomly stumbled back across this thread after shelving this project last month.

I installed the most current and it seems good.

Hi everyone,
I recently accidentally upgraded my smart plugs from Costco (CE Smart home smart plug) from version 0.1.3 to version 1.0.9 and it failed to connect to openhab 2.4. So I searched and almost gave up hope, thinking may be I needed to hack with Tasmota. Since these plugs are cheaply made with glue in, it makes the job very difficult. So I read this guide again and found the upgrade from tsightler. After many days of trial and error, I finally were able to make it work. Thank you for the great work from @Fiftiz and @tsightler.

It took me a while to figure out a series steps of upgrading tuya-mqtt to version 3.3 protocal and here belows are slightly modified steps from the original post:

To start with, I assumed you already have openhab 2.4 running AgentK tuya-mqtt node and the following is simply showing how to upgrade:

Step 1:
Remove old version of tuya-mqtt:
cd /etc/openhab2/scripts
sudo rm -rf tuyaapi_mqtt

Step 2:
Get version 3.3
sudo git clone https://github.com/tsightler/tuya-mqtt.git
cd tuya-mqtt
sudo npm install

Step 3:
sudo cp config.json.sample config.json

Step 4:
Modify node service assuming you already have that with the old version, you will need to modify the file /lib/systemd/system/tuyaapi-mqtt.service as the tuya-mqtt.js is in the different folder (/etc/openhab2/scripts/tuya-mqtt/tuya-mqtt.js). Please make a careful inspection as version 3.3 have a differently directory name as compare with the one from @AgentK .

Step 5:
Kill the old service.
sudo ps aux | grep node
sudo kill -9 process_id

Step 6:
reload service.
sudo systemctl daemon-reload
sudo systemctl enable tuyaapi-mqtt.service
sudo systemctl start tuyaapi-mqtt.service

Step 7:
modify your device state and command according @Fiftiz

Step 8:
restart openhab2
sudo systemctl restart openhab2.service

That should do it. You may have to redo Step 8 and Step 5 twice to register your devices.

Hi guys,

I do not know if I have read correctly, but is it now possible to change the dps values? in my case: temperature of the thermostat (dps: 2), for example, set to the value of 250? is that possible ? if yes how? I hope someone can help me. Thanks in advance and sorry for my bad english

Hoi Rik,

Tegen welke problemen liep jij aan?

Ik krijg het niet voor elkaar om de action led-lamp zelf te besturen.
Heb veel data afgevangen, tijdens actieveren en aanmelden. Dus heb de ids en de keys.
Wat ik zie ik dat de data vanuit het script plaintext wordt verzonden en niet versleuteld. Weet niet of dat het probleem is?
Zie data naar lamp en een antwoord van de lamp. Maar bij het verzenden van het id zie ik dat het nogmaals wordt verzonden maar geen response vanuit de lamp.

Groet,
Kees

I have add dps 2 and dps 3 in the sample on.js. 2 is for the dimming and 3 the color (between the two pair leds). With njstuya you can do the same I gues. (only njstuya will not work on my ubuntu)

device.get({schema: true}).then(data => {
console.log(data);
});
let status = await device.get();
console.log(Current status: ${status}.);

await device.set( { dps:‘1’, set: true });
await device.set( { dps:‘2’, set: 200});
await device.set( { dps:‘3’, set: 0});
status = await device.get();

node on.js
{ devId: ‘01408602840d8e220e95’, dps: { ‘1’: true, ‘2’: 100, ‘3’: 0 } }
Current status: true.
New status: true.

Thank you to you.
I have been stuck for weeks.

I am using Wi-fi switch : https://www.aliexpress.com/item/33001282012.html?spm=a2g0s.9042311.0.0.2c594c4dHWKc2t

Once, I applied new script for version 3.3 now my switch now work perfect for me!

1 Like

Hi,

I’m after a little help if possible.

I have obtained the key and ID from some light globes.

Installed the latest version of tsightler tuya-mqtt and setup the service. I’ve installed the generic broker and added the thing, I’ve added a thing for generic MQTT and bridged to the broker.

I have added in a channel for an on off switch and added the appropriately formatted topic for command and state however I am unable to control the bulb.

If I use a MQTT client and subscribe to the state, it does not see any changes in the globe nor can I push commands using a MQTT client.

Am I missing a step here? I am a bit lost with how to troubleshoot this as well.

Thanks in advance

edit: even if I subscribe to the generic MQTT thing channel that is linked to a switch item, toggling the switch item doesn’t not reflect in a subscription?

I am very new to MQTT so please be gentle

edit: running the tuya-mqtt script manually rather than the service has worked. I can control the lights with the switch item created and linked. Will have to work out why the service isn’t working. cheers

edit: the file path in the system had changed per the steps, I just have no attention to detail and missed the underscore changing to a dash. I’m all up and running, thanks

Hi all,

I have Teckin SB50 blubs, trying to control through openHAB using this solution. I think I did all the setup as instructed.

I got and used the ID, keys and IP address of the device. I can do the tuya-cli get command and get a successful payload from the bulb:

[root@telegramhost tuya-mqtt]# DEBUG=* tuya-cli get --ip 192.168.8.109 --id xxxxxxxxxxxxxxxxxx --key xxxxxxxxxxx --all
TuyAPI IP and ID are already both resolved. +0ms
TuyAPI Connecting to 192.168.8.109… +3ms
TuyAPI Socket connected. +79ms
TuyAPI GET Payload: +1ms
TuyAPI { gwId: ‘xxxxxxxxxxxxxxxx’, devId: ‘xxxxxxxxxxxxxxxxx’ } +0ms
TuyAPI Pinging 192.168.8.109 +10s
TuyAPI Received data: 000055aa00000000000000090000000c00000000b051bb030000ab45 +34ms
TuyAPI Parsed: +0ms
TuyAPI { payload: false, leftover: false, commandByte: 9, sequenceN: 0 } +0ms
TuyAPI Pong from 192.168.8.109 +1ms

However, when I run the DEBUG=* node tuya-mqtt.js and send mqtt commands whether through openHAB items from the control tab or mqtt.fx app using the manual method, it keep failing as shown in the debug below:

TuyAPI:mqtt receive settings {“topic”:“tuya/xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxx/192.168.8.109/command”,“action”:“command”,“message”:“OFF”,“options”:{“id”:“xxxxxxxxxxxxxxxxx”,“key”:“xxxxxxxxxxxxxxx”,“ip”:“192.168.8.109”}} +23s
TuyAPI:device Search device in network +23s
TuyAPI IP and ID are already both resolved. +23s
TuyAPI:device Device found in network +1ms
TuyAPI Connecting to 192.168.8.109… +0ms
TuyAPI Socket connected. +121ms
TuyAPI:device Connected to device. undefined (192.168.8.109, xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxx) +122ms
TuyAPI:device GET Payload: +0ms
TuyAPI:device { gwId: ‘xxxxxxxxxxxxxxxxx’, devId: ‘xxxxxxxxxxxxxxxxx’ } +0ms
TuyAPI:mqtt receive command { set: false } +124ms
TuyAPI:device set: { set: false } +1ms
TuyAPI SET Payload: +2ms
TuyAPI {
TuyAPI devId: ‘xxxxxxxxxxxxxxxxx’,
TuyAPI gwId: ‘xxxxxxxxxxxxxxxxx’,
TuyAPI uid: ‘’,
TuyAPI t: 1567712880,
TuyAPI dps: { ‘1’: false }
TuyAPI } +0ms
TuyAPI Pinging 192.168.8.109 +10s
TuyAPI Error event from socket. 192.168.8.109 Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:201:27) {
errno: ‘ECONNRESET’,
code: ‘ECONNRESET’,
syscall: ‘read’
} +46ms
TuyAPI:device:error Error: Error from socket
TuyAPI:device:error at Socket. (/etc/openhab2/scripts/tuya-mqtt/node_modules/tuyapi/index.js:365:30)
TuyAPI:device:error at Socket.emit (events.js:209: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 processTicksAndRejections (internal/process/task_queues.js:80:21) +34s
TuyAPI Socket closed: 192.168.8.109 +1ms
TuyAPI:device Disconnected from device. undefined (192.168.8.109, xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxx) +10s
TuyAPI:device delete Device undefined (192.168.8.109, xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxx) +0ms

Things I tried so far:

  • restarted openHAB
  • restarted the bulb
  • closed the Smart Life app as some other people recommends
  • tried to remove the light from the Smart Life app
  • factory reset the bulb and reconfigure it which renewed the key then I reused the new key in openHAB thing and try again.

I think I’m in a rabbit hole now. Appreciate your help here.

Thanks.

Hello, When you try the tuya-cli get command, I don’t see the list of DPS… try to put in MQTT : tuya/Tuya-id/tuya-localkey/discover/state and tuya/Tuya-id/tuya-localkey/discover/command

work or not ?

Make sure you kill the tuya app on any devices that may have it open.
That caught me out with a similar error
Cheers

Hi Fiftiz, thank you for your comment.

I tried and failed. When I used the MQTT style you shared, I receive this:

TuyAPI:mqtt receive settings {"topic":"tuya/xxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx/discover/command","action":"command","message":"OFF","options":{"id":"xxxxxxxxxxxxxxxxxxxx","key":"xxxxxxxxxxxxxxxx","ip":"discover"}} +8s
  TuyAPI:device Search device in network +8s
  TuyAPI IP and ID are already both resolved. +8s
  TuyAPI:device Device found in network +0ms
  TuyAPI Connecting to discover... +0ms
(node:120583) UnhandledPromiseRejectionWarning: Error: connection timed out
    at Socket.<anonymous> (/etc/openhab2/scripts/tuya-mqtt/node_modules/tuyapi/index.js:305:18)
    at Object.onceWrapper (events.js:298:28)
    at Socket.emit (events.js:209:13)
    at Socket._onTimeout (net.js:468:8)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)
(node:120583) 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: 15)
  TuyAPI Socket closed: discover +5s
  TuyAPI:device Disconnected from device. undefined (discover, xxxxxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxx) +5s
  TuyAPI:device delete Device undefined (discover, xxxxxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxx) +0ms
  TuyAPI:mqtt:error { status: 'disconnect', device: null } +13s

However, you mentioned about the tuya-cli command, I did the get option and manged to receive the dps.

[root@telegramhost tuya-mqtt]# tuya-cli get  --id xxxxxxxxxxxxxxxxxxxx--key xxxxxxxxxxxxxxxx -a 
{
  devId: 'xxxxxxxxxxxxxxxxxxxx',
  dps: {
    '1': true,
    '2': 'scene',
    '3': 255,
    '4': 184,
    '5': 'f0f8ff00d00fff',
    '6': 'fffcf70168ffff',
    '7': 'ffff500100ff00',
    '8': 'ffff8003ff000000ff000000ff000000000000000000',
    '9': 'ffff5001ff0000',
    '10': 'ffff0505ff000000ff00ffff00ff00ff0000ff000000'
  }
}

Also managed to use it to control the bulb from the CLI, weird and good news at the same time, the tuya-cli set command succeeded to control the bulb!

tuya-cli set --set true --id xxxxxxxxxxxxxxxxxxxx --key xxxxxxxxxxxxxxxx

Any idea what I’m facing here, do you think the tuya repo I used has some issue like compatibility or missing thing on my machine?

I used this one which is mentioned in the post

Well, that’s part of the troubleshooting list I tried as mentioned in my comment. Same problem :pensive: