Giter Site home page Giter Site logo

python-tuya's Introduction

python-tuya

Build Status

NOTE I'm no longer using this library (I flashed my devices with Tasmota instead - it's a way more reliable firmware, even without any WiFi) so this is not actively maintained.

Similar active projects:

An alternative is to reflash the devices (e.g with Tasmota, ESPurna, etc.) using https://github.com/ct-Open-Source/tuya-convert/ or if OTA is not an option over serial, see https://github.com/arendst/Tasmota - these are much better firmwre options. Recommended reading:


Python 2.7 and Python 3.6.1 interface to ESP8266MOD WiFi smart devices from Shenzhen Xenon. If you are using the Jinvoo Smart App, this allows local control over the LAN. NOTE requires the devices to have already been activated by Jinvoo Smart App (or similar).

Key extraction

https://github.com/clach04/python-tuya/wiki has background information for how to get device id and local key. (the device id can be seen in Jinvoo Smart App, under "Device Info").

Known to work with:

Demo:

import pytuya

d = pytuya.OutletDevice('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', 'LOCAL_KEY_HERE')
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)

# on a switch that has 4 controllable ports, turn the fourth OFF (1 is the first)
data = d.set_status(False, 4)
if data:
    print('set_status() result %r' % data)
    print('set_status() extrat %r' % data[20:-8])

TODO demo timer (with comment not all devices support this, one way to check, is to check Jinvoo Smart App and see if there is a clock icon that is not dimmed out).

Encryption notes

These devices uses AES encryption, this is not available in Python standard library, there are three options:

  1. PyCrypto
  2. PyCryptodome
  3. pyaes (note Python 2.x support requires ricmoo/pyaes#13)

Related Projects

Publishing cheat sheet

pip install twine pycrypto
python setup.py sdist --formats=zip
twine upload dist/*
# version bump ready for next release

Acknowledgements

  • Major breakthroughs on protocol work came from https://github.com/codetheweb/tuyapi from the reverse engineering time and skills of codetheweb and blackrozes, additional protocol reverse engineering from jepsonrob and clach04.
  • nijave pycryptodome support and testing
  • Exilit for unittests and docstrings
  • mike-gracia for improved Python version support
  • samuscherer for RGB Bulb support
  • magneticflux- for improved Python version support
  • sean6541 - for initial PyPi package and Home Assistant support https://github.com/sean6541/tuya-homeassistant
  • ziirish - for resolving a dependcy problem related to version numbers at install time

python-tuya's People

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-tuya's Issues

Get Device Local Key

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.

7.0.6 release

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.

Key does not get recognized/throws error

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

7.0.4 release on PyPI

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.

AttributeError when decoding

I've been playing with this and (at least with python 3) the following line causes an AttributeError: 'str' object has no attribute 'decode'

result = json.loads(result.decode())

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.

Vaccum Cleaner

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 :

  • 0 for Sleep mode,
  • 25 for Searching Home,
  • 2 for spot Mode,
  • 1 for "normal working mode"
  • 5 for charging

Charging "@home" is DPS 1 "True" for charging or "False" for out of base

Hopping this can help, ask for more detail

Key needed?

Hi,

do I need a key if I want to develop with your API?

Regards

Waldemar

Missing CRC32

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

Schema for Geekbes Mini Smart Socket YM-SW-1

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组"
}
]

Older Python 3 json problems - TypeError: the JSON object must be str, not 'bytes'

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.

socket timeout error

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

RecTec Pellet Smoker Controller Support

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.

dps status

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?

Wiki usb power strip

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.

Hang when TCP connection is interrupted

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?

BHT-6000 Thermostat (Decrypt)

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

ValueError() on get_status() - encrypted payload returned (sometimes)

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)

socket.timeout: timed out

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:

  1. Is there any way to use ethernet instead of wifi?
  2. When using wifi, does the light bulb have to be near to the pc?
  3. Can I have my phone near the light and let my pc control the light over the internet using the phone as a connector?

d.status timeout with a just bought device

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

The TCP reset issue

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.

PyPi package

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:

  • obviously need a setup.py :) (see x10_any) commit 92873a2
  • Need a version string to be added (see x10_any) commit ed44ab9
  • pycrypto dependency may be a problem for Home Assistant (see pycryptodome)

Sometimes "Connection Refused" occurs

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

Initializing IV to ''

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.

Tuya App 2.8 No Longer Valid

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.

Support for curtain switch

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?

new switches different port

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.

Smart Life / Jinvoo request latest release installed

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

Update firmware

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

Logging is blocked when pytuya is imported

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!

Repeated use of status() turns off light

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?

Error when changing color on the light

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

Cannot use module, OutletDevice method does not exist

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']

Color temperature doesn't work for Lumiman bulb

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.

ImportError: No module named 'pytuya'

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 created small python sample code for switching plugs on/off

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)

How to run demo?

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'

.status() occasionally restarts device

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?

Logo Design Offer as Open Source Contribution

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.

AttributeError: 'str' object has no attribute 'decode'

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'

pip install pytuya fails

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'

Tuya 3.3 version support

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.

[Errno 54] Connection reset by peer

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

Web version

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)

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.