clach04 / python-tuya Goto Github PK
View Code? Open in Web Editor NEWPython interface to ESP8266MOD WiFi smart devices from Shenzhen Xenon. NOTE I'm not using any devices with this library so I can't test :-(
License: MIT License
Python interface to ESP8266MOD WiFi smart devices from Shenzhen Xenon. NOTE I'm not using any devices with this library so I can't test :-(
License: MIT License
My older plugs (KMC) broadcast to port 6666 both from 49155. My new Tuya/Smart Life plugs (Teckin) both broadcast to port 6667 from 49154.
I can get the status and control the older plugs using pytuya, but whenever trying to interact with the newer plugs with python, even retrieving the status I get an error. I'd guess that maybe these new plugs are listening on a port other than 6668, but I don't know which one. I ran a port scan and these new plugs are listening on TCP port 6668, but pytuya cannot communicate with them.
The error output when trying to get the status is:
File "/usr/local/lib/python2.7/dist-packages/pytuya/__init__.py", line 281, in status
data = self._send_receive(payload)
File "/usr/local/lib/python2.7/dist-packages/pytuya/__init__.py", line 179, in _send_receive
data = s.recv(1024)
I've also tried Python3 and it doesn't work any better.
Hi,
I have an older different device working great.
I just bought this one https://www.amazon.it/gp/product/B07X2S13N8 cause they had italian plugs. Been able to retrieve keys using older smartlife and tuya-cli for both of them. Unfortunately usual test code fails at d.status line. The same code works fine with older device. Any advice?
Thanks.
Pino.
python3.7 tuyacmd2.py Traceback (most recent call last): File "tuyacmd2.py", line 6, in <module> data = d.status() # NOTE this does NOT require a valid key File "/www/cgi-bin/protected/tuya/python-tuya/new/pytuya/__init__.py", line 279, in status data = self._send_receive(payload) File "/www/cgi-bin/protected/tuya/python-tuya/new/pytuya/__init__.py", line 177, in _send_receive data = s.recv(1024) socket.timeout: timed out
My bulb is white spectrum only, no color support. d.status()
returns this: {'devId': '<redacted>', 'dps': {'3': 25, '1': True, '2': 255}}
. Poking around with generate_payload and send_receive shows that 1 == state, 2 == brightness, and 3 == color temp, which doesn't match up with your set_white function.
Need more info., see issue #1
Original reported issue by @nijave:
Traceback (most recent call last):
File "/config/custom_components/switch/tuya.py", line 103, in update
self._status = self._device.status()
File "/config/deps/lib/python3.6/site-packages/pytuya/__init__.py", line 223, in status
data = s.recv(1024)
ConnectionResetError: [Errno 104] Connection reset by peer
Under Linux Python 3
@clach04 saw:
Traceback (most recent call last):
File "demo_status.py", line 38, in <module>
data = d.status()
File "C:\Users\clach04\py\python-tuya_crypt\pytuya\__init__.py", line 228, in status
data = s.recv(1024)
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host
This is under python 2.7. Suspect this is the same thing as original report.
NOTE I've not seen this under Py3 yet on my machine but I've had long runs when this never occurs.
The module gets stuck when the TCP connection is interrupted (it blocks waiting for response). Not sure what causes the TCP interruptions--I suspect network issues due to the high level of interference and outlets on 2.4Ghz.
Possibly add a send/receive timeout?
The light connected to my device starts in the ON (True) state.. I run the following python script:
import pytuya, time
old_state=[False, False, False]
SmartLife=["", "", ""]
SmartLife[1] = pytuya.OutletDevice('02200270ecfabc8e2ff0', '192.168.20.39', 'ceb9acd336c853f2')
SmartLife[2] = pytuya.OutletDevice('04200086b4e62d121b87', '192.168.20.14', '3e637e09ea909522') #Desk Lamp
device_set={2}
for i in device_set:
data = SmartLife[i].status()
old_state[i] = data['dps']['1']
print ("*** Polling started " + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
+ " " + str(i) + " " + str(old_state[i]) )
while True:
for i in device_set:
data = SmartLife[i].status()
state = data['dps']['1']
if (state != old_state[i]):
print time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + " State has changed to " + str(i) + " " + str(state)
old_state[i]=state
time.sleep(0.5)
The resulting console output:
*** Polling started Thu, 28 Jun 2018 10:18:46 2 True
Thu, 28 Jun 2018 10:48:33 State has changed to 2 False
There are no timers on the device. Nor is there user intervention. The light turns off by itself. This is repeatable (and an eventuality) on multiple but not all devices.
Thoughts?
Hello,
following process of the wiki page https://github.com/clach04/python-tuya/wiki,
I have installed jonvoo and Smart Life respecting release number.
Unfortunately, when I start the application and start the login, I got an alarm message requested to me to install the latest release.
Of course, I'm not able to log in and follow the process provided inside wiki.
do you had the same issue, how to solve it ?
thanks for your support
I am trying to run python program in raspberrypi3. but it gives following error.
pi@raspberrypi:/usr/lib/python3.5 $sudo python3 Test2.py Traceback (most recent call last): File "Test2.py", line 3, in <module> import pytuya ImportError: No module named 'pytuya'
Just FYI, I already installed pytuya module
pi@raspberrypi:/usr/lib/python3.5 $ pip3 install pytuya==7.0.2 Collecting pytuya==7.0.2 Using cached https://www.piwheels.org/simple/pytuya/pytuya-7.0.2-py3-none-any.whl Collecting pyaes (from pytuya==7.0.2) Using cached https://www.piwheels.org/simple/pyaes/pyaes-1.6.1-py3-none-any.whl Installing collected packages: pyaes, pytuya Successfully installed pyaes-1.6.1 pytuya-7.0.2
Appreciate your quick help!
Note : My overall objective is to control tuya switch from Openhab panel.
I have a curtain switch that I have attached to a projector screen. I'm trying to work out what needs to be done to get it supported.
device.status() returns.... 'json obj data unvalid' with version 3.1 and when used with version 3.3 returns
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pytuya-7.0.4-py2.7.egg/pytuya/__init__.py", line 307, in status
result = cipher.decrypt(result, False)
File "/usr/local/lib/python2.7/dist-packages/pytuya-7.0.4-py2.7.egg/pytuya/__init__.py", line 87, in decrypt
raw = cipher.decrypt(enc)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py", line 295, in decrypt
return self._cipher.decrypt(ciphertext)
ValueError: Input strings must be a multiple of 16 in length
What information can I gather to get support for this type of switch?
Hi together,
I am using python-tuya in my Snips Home Automation.
It works fine, but sometimes I get a "Connection Refused".
I know that it is blocked when the App is open (you think there is a possiblity work around?),
but also if the Mobile App is closed I sometimes get a "Connection Refused".
When I reopen the App, turn off and on the light switches and then close the app
it is working again...
Do you have any idea or solution for this?
Thank you for your python library!!! Most of the time it works really nice :))
Under Python 3.5.4 (and maybe 3.4.3, see issue #10), get:
ERROR: test_set_status (__main__.TestXenonDevice)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 116, in test_set_status
result = json.loads(result)
File "/opt/python/3.5.4/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
======================================================================
ERROR: test_set_timer (__main__.TestXenonDevice)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 106, in test_set_timer
result = json.loads(result)
File "/opt/python/3.5.4/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
Looking at this, it looks like a json library bug, json.loads() should accept bytes.
Hi,
I got a new smart bulb socket from manufacturer 'Hoteon'. And I want to use the pytuya library for controlling the device.
My ask is - Is the productKey same as device localkey?? Cause I am unable to use the functionalities of pytuya library on it.
If anyone knows how to extract one please let me know.
Thanks in Advance.
I've been playing with this and (at least with python 3) the following line causes an AttributeError: 'str' object has no attribute 'decode'
python-tuya/pytuya/__init__.py
Line 274 in 01c123f
As I'm not familiar with the code yet I quickly fixed it locally with:
if not isinstance(result, str):
result = result.decode()
result = json.loads(result)
Not sure how python2 behaves with all that.
I'm rather busy lately so I don't have the time to investigate further and come up with a proper fix.
I have two WiFi outlets, both branded as KMC. They came packaged together, so I assume they were manufactured at approximately the same time. The status of one shows u'dps': {u'1': True, u'2': 0}
, the other has additional information u'dps': {u'1': False, u'2': 0, u'5': 0, u'4': 0, u'6': 1187}
. What are the additional values that the second one shows, indexes 4,5,6?
@clach04 I originally was working on this in python-tuya/python-tuya and I also pushed it to pypi/python-tuya when I was testing it.
I got rid of my devices so stopped working on it and it seems like you got it working now following codetheweb/tuyapi
I am happy to add you to the pypi package so you can take over and use the name if you want?
A comment on the wiki notes: NOTE dps.6 looks like a timer
Actually this is defined as switch_all in the schema and should do an all on or all off if a 1 or 0 is set. I ordered one to verify. Will update when it arrives.
Just playing with an Alfawise X5 Vaccum Cleaner who run with SmartLife app.
Wifi fw : 2.1.8
MCU fw : 1.0.0
Get DSP give :
sudo python3 get_dps.py 192.168.0.41 012005742c3ae840f6f6
Plug State Information:
{'dps': {'14': 100, '26': '5', '1': True, '11': 0, '25': True, '27': '1', '28': False}, 'devId': '012005742c3ae840f6f6'}
Plug DPS List:
1;25;28
As Lib is made for Plug DPS are wrong, no worry for this
Battery is DPS 14 : Batt % remaining
States is DPS 27 where value are :
Charging "@home" is DPS 1 "True" for charging or "False" for out of base
Hopping this can help, ask for more detail
the status
method is ok.
and the set_staus
method is raise the error.
Traceback (most recent call last):
File "pytuya.py", line 330, in <module>
data = d.set_status(not switch_state) # This requires a valid key
File "pytuya.py", line 235, in set_status
data = s.recv(1024)
socket.error: [Errno 54] Connection reset by peer
related to Issue #2
repeated status calls sometimes fail with:
File "demo_status.py", line 38, in <module>
data = d.status()
File "C:\Users\clach04\py\python-tuya_clach04\pytuya\__init__.py", line 234, in status
result = json.loads(result)
File "C:\ProgramData\Anaconda2\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda2\lib\json\decoder.py", line 367, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
extract of test (after creating switch object):
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
data = d.set_status(pytuya.ON)
if data:
print('set_status() result %r' % data)
print('set_status() extra %r' % data[20:-8])
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
print('switch_state %r' % switch_state)
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
print('switch_state %r' % switch_state)
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
print('switch_state %r' % switch_state)
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
print('switch_state %r' % switch_state)
data = d.status()
print('Dictionary %r' % data)
switch_state = data['dps']['1']
print('switch_state %r' % switch_state)
When trying to run the example, I get this traceback:
Traceback (most recent call last):
File "C:/Users/Minichota/PycharmProjects/Global_Automation/lights.py", line 4, in
data = d.status() # NOTE this does NOT require a valid key
File "C:\Python\lib\site-packages\pytuya_init_.py", line 255, in status
data = self.send_receive(payload)
File "C:\Python\lib\site-packages\pytuya_init.py", line 165, in _send_receive
s.connect((self.address, self.port))
socket.timeout: timed out
I hope you can help me or guide me through to the solution
Need more info., see issue #1
Hello...
Since i dont get any node or c# working on my device i want to run the tuya controll logic on it want to try the python now...
But the code provided here is not totally clear to me. (python noob)
In the code it states:
d = pytuya.OutletDevice('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', LOCAL_KEY)
and when i fill that with my values all over the code like
d = pytuya.OutletDevice('02200506600104944eb9', '192.168.178.65', 78382189fd5087ba)
it throws a fit at the ba at the end of the local key which i know is correct
And as a quick question on the side...do i have to call this code with paramteters to get it do something or is a dumb code just for showing general functionality?
Casue is would not be able to alter it to get on/off/toggle into it
Thx for any thoughts
Pytuya is a part of my Snips Homeautomation.
I tried to implement logging for several times now and today I found out that the pytuya module somehow blocks logging.
Here is a simple example to reproduce the problem:
import pytuya
import logging
logging.basicConfig(
level=logging.INFO,
filename='logs.log',
filemode='w'
)
logger = logging.getLogger('Test')
logger.addHandler(logging.StreamHandler())
logger.info('Test')
is not working.
#import pytuya
import logging
logging.basicConfig(
level=logging.INFO,
filename='logs.log',
filemode='w'
)
logger = logging.getLogger('Test')
logger.addHandler(logging.StreamHandler())
logger.info('Test')
by commenting the pytuya module the logger is working again...
Is there a simple way to fix that?
Thank you!
Error:
line 4, in
data = d.status()
File "C:\Users\Diaboli Sica\AppData\Local\Programs\Python\Python37\lib\site-packages\pytuya_init_.py", line 279, in status
data = self.send_receive(payload)
File "C:\Users\Diaboli Sica\AppData\Local\Programs\Python\Python37\lib\site-packages\pytuya_init.py", line 175, in _send_receive
s.connect((self.address, self.port))
socket.timeout: timed out
Code:
import pytuya
d = pytuya.OutletDevice('xxxxx', 'xxxxx', 'xxxxx')
data = d.status()
Questions:
Does this support the usage of PIR &/or Door/Window Sensors?
I installed using # pip3 install python-tuya. No errors. I am running python 3.5.3. Tried to list classes via import, dir method, no classes shown.
pip3 install python-tuya
python
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
import pytuya
dir(pytuya)
['builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec']
Clach04, first let me say thank you for all the work you've put into python-tuya; it's already been incredibly helpful for me. I recently acquired the new WiFi controller for my RecTec pellet smoker and after some research I found it leverages the Tuya platform which led me to both your project and Tuyapi. So far I've been able to leverage your status function to get some good info from the smoker (state, temperatures, etc.) however I haven't been able to change its state (i.e. turn it on or off) with the set function (which I realize is designed for other devices - I was just hoping I might get lucky). I was hoping you might have some insight into how I might be able to do so (or if I'll need to figure out how to leverage the MQTT interface instead). The scripts I've been working on so far are available here. I hope you don't mind, but I've added your discover devices script as it greatly simplifies finding the device ID.
From the cloud API docs, it looks like there is sone firmware updating methods. Any chance we might be able to use that to reflash some of these devices with a different firmware?
I have a geekbes plug that I managed to flash with tasomota using an ftdi connextion, but getting it apart to access the programming pads does a lot of damage to the plug
Hello,
Thanks for a good work on supporting local access to Tuya devices.
On https://pypi.org/project/pytuya/ only version 7.0.2 is released. Currently many Tuya devices require 3.3 version of protocol.. It is supported only in verison 7.0.4 of pytuya.
In Home Assistant it is very hard to use import not from packages released from pypi.org.
Please do something with it. Release version 7.0.4 on pypi.org.
Thanks.
I did not many good examples so I created something by myself. It reads plug data from json file and flips the switches state.
./p.py -d NeoWiFi01 -s on
{
"devices": {
"NeoWiFi01": {
"uuid" : "06200632dc4f22XXXXXX",
"key" : "6ab4d393ddXXXXXX",
"ip" : "10.42.42.143"
},
"NeoWiFi02": {
"uuid" : "06200632dc4f22XXXXXX",
"key" : "41aa63b644XXXXXX",
"ip" : "10.42.42.146"
},
"NeoWiFi03": {
"uuid" : "06200632dc4f22XXXXXX",
"key" : "2c69263673XXXXXX",
"ip" : "10.42.42.145"
}
}
}
code:
#!/usr/bin/env python3
import pytuya
import sys
import getopt
import json
def main(argv):
device = ''
state = ''
try:
opts, args = getopt.getopt(argv,"hd:s:",["help", "device=", "state="])
except getopt.GetoptError:
print (sys.argv[0], '-d <device> -s <state>')
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print (sys.argv[0], '-d <device> -s <state>')
sys.exit()
elif opt in ("-d", "--device"):
device = arg
elif opt in ("-s", "--state"):
state = arg
filename = "p.json"
if filename:
with open(filename, 'r') as f:
datafile = json.load(f)
print ('Device is', device)
print ('State is', state)
print (datafile["devices"][device]["uuid"])
print (datafile["devices"][device]["key"])
print (datafile["devices"][device]["ip"])
d = pytuya.OutletDevice(datafile["devices"][device]["uuid"], datafile["devices"][device]["ip"], datafile["devices"][device]["key"])
data = d.status() # NOTE this does NOT require a valid key
print('Dictionary %r' % data)
print('state (bool, true is ON) %r' % data['dps']['1']) # Show status of first controlled switch on device
# Toggle switch state
switch_state = data['dps']['1']
data = d.set_status(not switch_state) # This requires a valid key
if data:
print('set_status() result %r' % data)
sys.exit(0)
if __name__ == "__main__":
main(sys.argv[1:])
(edit clach04 to change formatting as Python code was missing indentation after markdown rendering)
Hi,
when I want to change the color of a light I have the following error:
Traceback (most recent call last):
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in
vspd.debug(filename, port_num, debug_id, debug_options, run_as)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 39, in debug
run()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd_main_.py", line 312, in run_file
runpy.run_path(target, run_name='main')
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "C:\Users\ochol\source\repos\PythonApplication1\PythonApplication1\PythonApplication1.py", line 11, in
result = d.set_white(255, 255)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pytuya_init.py", line 471, in set_white
data = self.send_receive(payload)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pytuya_init.py", line 169, in _send_receive
s.connect((self.address, self.port))
socket.gaierror: [Errno 11001] getaddrinfo failed
here is my code:
import pytuya
d = pytuya.OutletDevice('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', 'LOCAL_KEY_HERE')
result = d.set_colour(255,255,255)
Thanks for your help
Hi,
do I need a key if I want to develop with your API?
Regards
Waldemar
Hello, first of all thank you for your work.
I am having problems into getting the payload and decrypting it in the new 3.3 protocol version.
This problem was reported and discussed in this topic of tuyapi:
codetheweb/tuyapi#175
Have you got plans for update your python library in order to be compatible with the new 3.3 version?
Regards.
Is there a reason you're explicitly setting the IV to ''?
Like
cipher = AES.new(self.key, mode=AES.MODE_ECB, IV='')
I was having some issues on homeassistant since it appears setting IV has been removed because it didn't used to do anything.
Package available from https://pypi.org/project/pytuya/
Related to Issue #24.
If any one is interested and has not worked on PyPi support before, I have a sample project at https://github.com/clach04/x10_any (sadly I don't have "how to publish" notes there, from memory I used twine but I did bookmark https://nosarthur.github.io/coding/2018/07/01/pypi.html which has a note on how to use a Markdown formatted readme that I mean to try).
Random thoughts:
New to python. Have installed python-tuya on Raspberry Pi using
python -m pip install python-tuya
I copied the demo code into demo.py and tried to run it.
python demo.py
Traceback (most recent call last):
File "demo.py", line 7, in <module>
d = pytuya.OutletDevice(deviceid, ipaddress, key)
AttributeError: 'module' object has no attribute 'OutletDevice'
Is there any way to create a website that takes the Tuya camera streamings ?
(I have the ID's, password and login data for them, but I don't know how to take the streaming into web)
Looks like there are a few people interested in HA support, and at least one implementation home-assistant/core#11000 in the works. Opening ticket as a place to jot notes down for sharing.
Custom component:
Using pytuya with tuya-homeassistant (python 3.6.4) and I get this error when toggling on/off the switch:
File "/config/deps/lib/python3.6/site-packages/pytuya/__init__.py", line 275, in status
result = json.loads(result.decode())
AttributeError: 'str' object has no attribute 'decode'
When I try to install pytuya package I get the following error:
pip install pytuya
Collecting pytuya
Using cached https://files.pythonhosted.org/packages/81/7a/a77347f79ab92408acf49d48d15043fa1254405fb501f2ecc6e64f2c7ca9/pytuya-7.0.1.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-yfyZYU/pytuya/setup.py", line 23, in
with codecs.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
File "/usr/lib/python2.7/codecs.py", line 896, in open
file = builtin.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: '/tmp/pip-install-yfyZYU/pytuya/README.md'
Here is the schema I retrieved from my dev_data_storage.xml file:
Feel free to include on your wiki.
[
{
"mode": "rw",
"code": "switch_1",
"name": "单插开关",
"property": {
"type": "bool"
},
"iconname": "icon-dp_power2",
"id": 1,
"type": "obj",
"desc": ""
},
{
"mode": "rw",
"code": "countdown",
"name": "倒计时",
"property": {
"unit": "秒",
"min": 0,
"max": 86400,
"scale": 0,
"step": 1,
"type": "value"
},
"iconname": "icon-dp_time2",
"id": 11,
"type": "obj",
"desc": "可根据产品实际倒计时功能修改。"
},
{
"mode": "rw",
"code": "randomTime",
"name": "随机定时",
"property": {
"type": "string",
"maxlen": 255
},
"id": 101,
"type": "obj",
"desc": "每6个字节代表 #1开关/#2星期/#3#4起始时间(min)/#5#6结束时间(min),最大42组"
},
{
"mode": "rw",
"code": "cycleTime",
"name": "循环定时",
"property": {
"type": "string",
"maxlen": 255
},
"id": 102,
"type": "obj",
"desc": "每10个字节代表 #1开关/#2星期/#3#4起始时间(min)/#5#6结束时间(min)/#7#8开启时间(min)/#9#10关闭时间(min)\n星期:00(单次)01(周日)02(周一)04(周二)08(周三)10(周四)20(周五)40(周六)"
},
{
"mode": "rw",
"code": "normalTime",
"name": "普通定时",
"property": {
"type": "string",
"maxlen": 255
},
"id": 103,
"type": "obj",
"desc": "每6个字节代表 #1开关/#2星期/#3#4开启时间(min)/#5#6关闭时间(min),最大42组"
}
]
Could we please get a new release? The work since 7.0.5
fixes pip installs which I need for my Home Assistant integration, and even updates the version number to 7.0.6
, but there hasn't been a release to PyPI meaning I can't use it.
Thanks for this.
I've been looking at the communications with my device and the suffix isn't "000000000000aa55".
It is CRC32 + "0000aa55". The CRC32 is of everything before (prefix -> payload) and is stored as a big endian.
The demo code still works with the CRC set to zero but they may decide in future (or with some devices) to reject anything with an incorrect CRC.
My device is labelled TECKIN WiFi Smart Plug
Hey, I just wanted to post this to you guys, and see what you thought. I re-wrote the tuyapi stuff as a project to help me learn Python, and I figured I'd post it to you guys. I don't want to step on toes or anything. https://github.com/Supermortal/python-tuya-oittm
I have two af that devices, i'm using the following code to get data from both:
import socket
import struct
import base64
import time
import pytuya
key = {'<local_key1>' , '<localKey2>'}
for k in key:
print k
host_port = 6666
host_ip = '239.255.255.250'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind(('', host_port))
mreq = struct.pack('4sl', socket.inet_aton(host_ip), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
try:
while True:
print('listening')
data = sock.recvfrom(1024)
raw_bytes, peer_info = data
print(data)
packet = raw_bytes
PREFIX_LEN = 16
SUFFIX_LEN = 8
prefix = packet[:PREFIX_LEN]
json_crypted_plus_suffix = packet[PREFIX_LEN:]
json_crypted_len = ord(prefix[-1])
json_crypted_b64_with_header = json_crypted_plus_suffix[:json_crypted_len-SUFFIX_LEN]
version_str = json_crypted_b64_with_header[:3]
print('version_str (%d) %r' % (len(version_str), version_str))
hexdigest = json_crypted_b64_with_header[3:][:16]
print('hexdigest (%d) %r' % (len(hexdigest), hexdigest))
json_crypted_b64 = json_crypted_b64_with_header[3+16:]
suffix = packet[-SUFFIX_LEN:] # assume we know length of end
print('packet (%d) %r' % (len(packet), packet))
print('prefix (%d) %r' % (len(prefix), prefix))
print('json_crypted_plus_suffix (%d) %r' % (len(json_crypted_plus_suffix), json_crypted_plus_suffix))
print('json_crypted_len %d' % (json_crypted_len))
print('suffix (%d) %r' % (len(suffix), suffix))
print('json_crypted_b64 (%d) %r' % (len(json_crypted_b64), json_crypted_b64))
for k in key:
try:
print k
cipher = pytuya.AESCipher(k)
json_raw = cipher.decrypt(json_crypted_b64)
print('json_raw (%d) %r' % (len(json_raw), json_raw))
except:
print 'Error'
continue
print '#################################################################'
finally:
sock.close()
But in execution I get error on decrypt:
listening
('\x00\x00U\xaa\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x9f\x00\x00\x00\x00{"ip":"192.168.1.250","gwId":"<dev_id>","active":2,"ability":0,"mode":0,"encrypt":true,"productKey":"IAYz2WK1th0cMLmL","version":"3.1"}\x12\xb8\xac\xb8\x00\x00\xaaU', ('192.168.1.250', 49154))
version_str (3) '\x00\x00\x00'
hexdigest (16) '\x00{"ip":"192.168.'
packet (175) '\x00\x00U\xaa\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x9f\x00\x00\x00\x00{"ip":"192.168.1.250","gwId":"<dev_id>","active":2,"ability":0,"mode":0,"encrypt":true,"productKey":"IAYz2WK1th0cMLmL","version":"3.1"}\x12\xb8\xac\xb8\x00\x00\xaaU'
prefix (16) '\x00\x00U\xaa\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x9f'
json_crypted_plus_suffix (159) '\x00\x00\x00\x00{"ip":"192.168.1.250","gwId":"<dev_id>","active":2,"ability":0,"mode":0,"encrypt":true,"productKey":"IAYz2WK1th0cMLmL","version":"3.1"}\x12\xb8\xac\xb8\x00\x00\xaaU'
json_crypted_len 159
suffix (8) '\x12\xb8\xac\xb8\x00\x00\xaaU'
json_crypted_b64 (132) '1.250","gwId":"<dev_id>","active":2,"ability":0,"mode":0,"encrypt":true,"productKey":"IAYz2WK1th0cMLmL","version":"3.1"}'
<local_key1>
Error
<local_key2>
Error
With tuyaAPI i can get actual data and set parameters:
{ devId: '<dev_id>',
dps:
{ '1': true,
'2': 32,
'3': 36,
'4': '1',
'5': false,
'6': false,
'102': 27,
'103': '0',
'104': false } }
Notes on that device:
dps updated in wiki
I'm seeing some very strange behavior where calling .status() on a wifi socket causes the socket to reset itself (turn off and then on immediately). It doesn't happen every time .status is called, but I can very very regularly see this happen. I've done some digging but haven't been able to diagnose why it's happening yet.
Any ideas as to what's causing this and how to fix it?
Under the Wiki section, under the top 'Home' heading, tuya app version 2.8.1 is listed as a possible option. Unfortunately, the app version is no longer supported by the tuya service, therefore a user cannot login to utilize the older version. When attempting to use v2.8.1, a pop-up reads, "Update app" and fails to continue.
Recommend to add a note to the wiki that this option is no longer valid.
I have made clach04 a contributor to my sean6541/tuya-homeassistant https://github.com/sean6541/tuya-homeassistant repository and an owner of the PyPi package pytuya https://pypi.org/project/pytuya/. Feel free to reset the versioning of pytuya, but remember to also update the requirement version in sean6541/tuya-homeassistant/tuya.py
Edit by clach04 to add URLs
Hello Sir. I'm a Graphics Designer. I'm happy to see an open source project, So, I want provide a logo for you. Would you mind if I propose a new logo design to improve visualization of your project as my Open Source Contribution?
Thanks for the attention.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.