88 For more information see https://github.com/jasonacox/tinytuya
99
1010"""
11+ import time
1112import tinytuya
1213
1314# tinytuya.set_debug(True)
1617d .set_version (3.3 )
1718d .set_socketPersistent (True )
1819
20+ # Devices will close the connection if they do not receve data every 30 seconds
21+ # Sending heartbeat packets every 9 seconds gives some wiggle room for lost packets or loop lag
22+ PING_TIME = 9
23+
24+ # Option - also poll
25+ POLL_TIME = 60
26+
1927print (" > Send Request for Status < " )
20- payload = d .generate_payload (tinytuya .DP_QUERY )
21- d .send (payload )
28+ d .status (nowait = True )
2229
2330print (" > Begin Monitor Loop <" )
31+ pingtime = time .time () + PING_TIME
32+ polltime = time .time () + POLL_TIME
2433while (True ):
2534 # See if any data is available
2635 data = d .receive ()
27- print ('Received Payload: %r' % data )
28-
29- # Send keyalive heartbeat
30- print (" > Send Heartbeat Ping < " )
31- payload = d .generate_payload (tinytuya .HEART_BEAT )
32- d .send (payload )
33-
34- # Option - Some plugs require an UPDATEDPS command to update their power data points
35-
36- # print(" > Send Request for Status < ")
37- # payload = d.generate_payload(tinytuya.DP_QUERY)
38- # d.send(payload)
39-
40- # # See if any data is available
41- # data = d.receive()
42- # print('Received Payload: %r' % data)
43-
44- # print(" > Send DPS Update Request < ")
45- # payload = d.generate_payload(tinytuya.UPDATEDPS,['18','19','20'])
46- # Some Tuya devices will not accept the DPS index values for UPDATEDPS - try:
47- # payload = d.generate_payload(tinytuya.UPDATEDPS)
48- # d.send(payload)
49-
50- # # See if any data is available
51- # data = d.receive()
52- # print('Received Payload: %r' % data)
53-
36+ if data :
37+ print ('Received Payload: %r' % data )
38+
39+ if ( pingtime <= time .time () ):
40+ pingtime = time .time () + PING_TIME
41+ # Send keep-alive heartbeat
42+ print (" > Send Heartbeat Ping < " )
43+ d .heartbeat (nowait = True )
44+
45+ # Option - Poll for status
46+ if ( polltime <= time .time () ):
47+ polltime = time .time () + POLL_TIME
48+
49+ # Option - Some plugs require an UPDATEDPS command to update their power data points
50+ if False :
51+ print (" > Send DPS Update Request < " )
52+
53+ # # Some Tuya devices require a list of DPs to update
54+ # payload = d.generate_payload(tinytuya.UPDATEDPS,['18','19','20'])
55+ # data = d.send(payload)
56+ # print('Received Payload: %r' % data)
57+
58+ # # Other devices will not accept the DPS index values for UPDATEDPS - try:
59+ # payload = d.generate_payload(tinytuya.UPDATEDPS)
60+ # data = d.send(payload)
61+ # print('Received Payload: %r' % data)
62+
63+ print (" > Send Request for Status < " )
64+ data = d .status ()
65+ print ('Received Payload: %r' % data )
0 commit comments