Tuya Switch Control (Jinvoo, Smart Life)

Tags: #<Tag:0x00007f38816ed208> #<Tag:0x00007f38816ecec0> #<Tag:0x00007f38816ecd08>

Here is a simple script, items and rules to control Tuya switches. Quite a few Chinese switches are simply re-branded Tuya devices.

Update
Now with Cloud support. You can simply use your email/pass for the Tuya/Smart Life app used to register your devices.

Local ON/OFF commands should now be pretty much instant.

I’ve used an existing nodejs script and just added a wrapper so you can more easily use it from openhab. The existing example is a Temperature control setup. When it’s too cold the switch turns on, etc.
It’s all relatively easy except for the configuration part where you need to perform a MITM attack to get the key. (And that was way easier than I expected).

Install Instructions:

If nodejs and npm are installed, install the package from npm (otherwise obtain nodejs and npm first):

openhab=/etc/openhab2
cd $openhab/scripts
sudo npm install unparagoned/njsTuya

Test Install

Run the following which should find all devices on your network and return their state.

node node_modules/njstuya

Configuration

To use create a rule which sends a command to the script

var resp = executeCommandLine("node /etc/openhab2/scripts/node_modules/njstuya" + command, 50000)
logInfo("Tuya", "Run Command: [{}] Result {}", command, resp)

To use the following items and rule as an example copy the files to Openhab configuration directories:

cp node_modules/njstuya/items/* $openhab/items/
cp node_modules/njstuya/rules/* $openhab/rules/

Cloud setup

You can pass the cloud email and arguments through the cli, or complete the key.json.rename and rename it to key.json

It is reccomended to put the details into key.json in the folder ./scripts/node_modules/njstuya/

 {
   "userName" : "d@yahoo.com",
  "password": "yourpassword",
  "countryCode": "44",
  "bizType": "smart_life",
  "region": "EU"
 }

bizType can be ‘tuya’, ‘smart_life’

Then you just need to run

node njstuya.js -mode cloud -id DEVICEID COMMAND

Otherwise to pass all arugments without config enter the email/pass/international phone code/region

node njstuya.js -mode cloud -user email -pass password -biz smart_life -code 44 -region eu -id DEVICEID COMMAND

TO USE
To use just have a rule run
node njstuya.js -ip DEVICEIP -id DEVICEID -key DEVICEKEY COMMAND
Commands are ON, OFF, TOGGLE, STATE, -get, -set
e.g.
node njstuya.js -ip 10.0.0.2 -id 213klj349sdfjl324po32 -key 342kljerw98 ON
All commands return the state of the switch.
Now with full dps support as below with set arg

node njstuya.js -ip 10.0.0.2 -id 213klj349sdfjl324po32 -key 342kljerw98 -set "{ \"dps\":1, \"set\": true }"

Alternatives
The tuyapi/cli has borowed most of the commands from nsjtuya, so kind of makes my script redundant, since you can just use tuyapi and it’s cli. I had problems getting it working but if you can get it working it’s probably a more streamlined method and it shouldn’t take much effort converting the rules/items to work with tuyapi

Here is a very detailed step by step mqtt setup with pictures if that’s your thing [MQTT] (Step-by-Step guide for adding Tuya-bulbs, Wi-Fi smart LED (Smart Life app) to OH2 using tuya-mqtt.js by AgentK)

Here is a new node rest server that’s fasttuyasvr

Hi, I’m new to openHAB. Have it running on a Pi3 with openhabian.

I use ifttt to control a tuya smart plug but I’d like to cut the middle man.

How can this be used as a binding if at all? (no Eclipse running). Can I just add the script(s) to my openHAB and find things?
Thank you!

I would like to make a binding. I haven’t made one before but if there is demand I’ll give it a try. The big hurdle at the moment is getting the localkey for each device. Only developers get a secret key they can use to set or get the private key for the device(it changes each time it’s set up). So at the moment we have to perform a MITMA to get the key or install an android app to to find the key in the jinvoo or whatever app.

I’m not sure how user friendly that would be and if it would meet the standards of a binding. There might be ways we emulate the apps to set/get the key but the main developers are hesitant of going that route since it would be a serious breach in TOS and likely illegal.

As long as you don’t have too many devices it’s not too hard to use the current setup. Just copy the files to the right folders and you should be on your way. The only config is setting the ip, id and key which is fully explained. Although it’s kind of buggy atm. The api it uses is bugging out. Hopefully I can add a loop that actually works and will keep on trying until it succeeds.

Thank you, I might give it a try! Please keep me/us posted about any improvements :slight_smile: Thanks!
For me the ifttt works as expected atm, so there’s not much pressure to change it.

Binding would be great. I do same than kalesco, via IFTTT…but not really comfortable and fast…so…i played a little bit with “Packet-Capture” App on my android phone, listening to the data exchange of SMART-LIFE-APP…and can see, that the local-key not seem to be change…hmmm…keep us informed about your progress

by the way…does anybody have a working script-, rule- solution to control the bulbs with send command-method in OH2.2?

The local key changes on each setup. So should be fixed once setup. So it’s not something we can hardcode in.We need to somehow ideally setup and get/set the local key without using one of the apps. Or even if you use an app a way to get the local key without installing software on the phone to perform MitM attacks or read the key from the smart-life-app cache. Essentially once someone can “legally” emulate and setup a device getting the private key in the process all the pieces will be there to create an automated binding.

Also the codetheweb/tuyapi keeps on changing which means my binding sometimes stops working if you update the core program. Also there are lots of errors with the tuyapi, so I need to add in a loop which keeps on trying until it works or move to another port. Apparently the python port is pretty good, I might try switching over when I have a chance.

Otherwise my scripts, rules, etc. should work on the bulbs although I’ve never tried bulbs.In terms of send it would be

>BedroomHeather.sendCommand("ON")

hi unparagoned…cannot install tuyapi, any ideas?

[21:23:15] openhabian@openHABianPi:~$ npm install codetheweb/tuyapi
/home/openhabian
└── tuyapi@2.0.1 (git://github.com/codetheweb/tuyapi.git#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)

npm WARN enoent ENOENT: no such file or directory, open '/home/openhabian/package.json’
npm WARN openhabian No description
npm WARN openhabian No repository field.
npm WARN openhabian No README data
npm WARN openhabian No license field.

I vaguely recall those warnings and can’t remember what I did. I think they are just warnings and tuyapi has installed fine. Try continuing as if it was installed and see if you get errors.

In the future I’m probably going to try and move to the python backend since it might be more reliable. It also gives you much better feedback in terms of errors.

thx 4 response…here my issues:

python-script runs…shows me devices, by firing command-line-statement in putty:

[07:04:23] openhabian@openHABianPi:~$ python /etc/openhab2/scripts/njstuyamonitor.py
{ Devices: [ { -ip 192.168.220.112 -id 0120061060019464f9a5 -key } ] }

but,

JS-throws errors:

[07:05:12] openhabian@openHABianPi:~$ /usr/bin/node /etc/openhab2/scripts/njstuya.js -ip 192.168.220.122 -id 02200095dc4f2212d7d5 -key dsf456sdf OFF
module.js:472
throw err;
^

Error: Cannot find module 'tuyapi’
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object. (/etc/openhab2/scripts/njstuya.js:11:20)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)

OK. So tuyapi hasn’t installed properly. It sounds like a basic environmental issue. I just did a few things on google, but can’t remember which worked. I think this might just be it.

npm init --yes

Try from the folder njstuya.js is located in. I put it in the scripts folder so if you have done the same.

cd /etc/openhab2/scripts/
npm install codetheweb/tuyapi

If that doesn’t work It might be best to ask the people who wrote tuyapi directly https://github.com/codetheweb/tuyapi . They really know what they are doing. I think it’s something quite basic about setting up the environment and node js, I had also downloaded the file from the github I think. This is pretty much my first experience writing anything in js and it’s like the worst experience of my life, for a moment I thought I actually had died and gone to hell. Sorry I’m not much of a help but this nodejs stuff seems to be dreamed up as a way to torture programmers so I’m limiting even how much I google stuff. If I have to go back to the code to fix even a typo, I’m going switch over to the python port, it was much more helpful debugging and getting things working.

Let me know what solved this as most other openhab users are likely to experience this.

ok, i think this is the point where I quit to continue working at this topic. This is my first time to hear somebody had died while coding and resurrected from hell… :wink: But thx 4 help…please inform me, if you have success with your binding-project, or other working methods to control the bulbs easily.

This should work as mentioned above

cd /etc/openhab2/scripts/
npm install codetheweb/tuyapi

Hi there, I’m quite lost with the explanations here. Is is possible to have a tutorial that explains how to add Tuya smart plugs in the BINDINGS of openHAB2?

Thanks very much !

NO! This isn’t a binding as such, so there is nothing to add to bindings.

The current script and device is fairly unreliable so I haven’t thought of making a proper binding. I’m partway through trying out a python port for the api, if that works then I’ll consider making a proper binding.

Thanks very much for you reply :slight_smile:

Also interested in this as well. Picked up 4 Sparin wifi plugs for $60 on Amazon. I’ll mess around with the scripts and see how it works. Thanks for sharing!

There looks like there is a reasonable interest in this. So I’m going to start looking to make a binding out of this.

I got them working with pyTuya and using an exec script

Switch SmartLifeSW1     "WiiMote Charger [%s]"          <outlet>    (SmartLife, mapdb)  {exec=">[ON: python /etc/openhab2/scripts/python/mini_plug1_ON.py] >[OFF: python /etc/openhab2/scripts/python/mini_plug1_OFF.py]" }

Much more elegant than mine… but just happy I got it working lol! Posting it here in case it helps others.

Items

Switch FrontHallLamp "Front Hall Lamp"
String FrontHallLampConfig

My System Start Rule

FrontHallLampConfig.postUpdate("-ip x.x.x.x -id ***** -key *****")

My Device Rule

var tuyaScript = "node /Applications/openhab-2.2.0/conf/scripts/njstuya.js "

rule "Front Hall Lamp"
when
	Item FrontHallLamp changed
then
	var String execResult
	logInfo("Mainfloor.rules", "FOYER: Table Lamp changed to " + FrontHallLamp.state)

	if ( FrontHallLamp.state == ON) {
		execResult = executeCommandLine(tuyaScript + FrontHallLampConfig.state + " ON", 50000)
	} else {
		execResult = executeCommandLine(tuyaScript + FrontHallLampConfig.state + " OFF", 50000)
	}

	logInfo("Mainfloor.rules", "FOYER: Table Lamp is now " + execResult)
end