PaulAnnekov / tuyaha

Implements the special Tuya Home Assistant API.
Other
141 stars 106 forks source link

tuyapi: Use Session object for every request made. #38

Closed estebanz01 closed 4 years ago

estebanz01 commented 4 years ago

This change implements the Session object, allowing us to reuse TCP connections via requests pool.

First step in order to fully fix #36.

estebanz01 commented 4 years ago

@PaulAnnekov I'm a ruby dev, so let me know if I'm missing something related to python styling.

Also, I was wondering if we can start doing the push approach in this PR or just open a new one.

estebanz01 commented 4 years ago

This is what I wrote for testing, so now it maintains the final state and only one A query is done. Since I only have switches, I do not have a real way to test the other devices, hopefully a smart lock will arrive soon 🤞 .

from tuyaha import TuyaApi
import pprint
import time

USERNAME = "<value>"
PASSWORD = "<value>"
REGION = "<value>" # cn, eu, us
COUNTRY_CODE = "<value>" # Your account country code, e.g., 1 for USA or 86 for China
BIZ_TYPE = "<value>" # tuya, smart_life, jinvoo_smart

api = TuyaApi()

pp = pprint.PrettyPrinter(indent=4)

res = api.init(USERNAME, PASSWORD, COUNTRY_CODE, BIZ_TYPE)
res_1 = api.discover_devices()

pp.pprint(res)
pp.pprint(res_1)

print("turning on")
res[0].turn_on()
pp.pprint(res[0].state())
time.sleep(5)

print("turning off")
res[0].turn_off()
pp.pprint(res[0].state())
time.sleep(5)

print("turning on")
res[0].turn_on()
pp.pprint(res[0].state())
djtimca commented 4 years ago

I manually patched these files into my HA docker instance and restarted the container. Everything works much better now.

Approximate delay when I update a switch from outside HA is ~30 seconds, but for HA controlled state changes it triggers instantly and keeps its state exactly as needed.

One bug in light.py though:

In turn_off you missed the quotes around false so it returns an error in the UI (but does update after a while). I updated that manually and it works.

estebanz01 commented 4 years ago

I manually patched these files into my HA docker instance and restarted the container. Everything works much better now.

Approximate delay when I update a switch from outside HA is ~30 seconds, but for HA controlled state changes it triggers instantly and keeps its state exactly as needed.

One bug in light.py though:

In turn_off you missed the quotes around false so it returns an error in the UI (but does update after a while). I updated that manually and it works.

@djtimca thanks for testing this! 😁 I pushed a fix for the missing quotes.

djtimca commented 4 years ago

What is still required to merge / push the update so the HA Tuya component can be updated. Right now I have to manually update after every HA Update.

@PaulAnnekov

PaulAnnekov commented 4 years ago

@djtimca I will try to take a look at this PR today.

PaulAnnekov commented 4 years ago

Thanks, good job! Will release today.