forked from jasonacox/tinytuya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
devices.py
101 lines (91 loc) · 3 KB
/
devices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# TinyTuya Example
# -*- coding: utf-8 -*-
"""
TinyTuya - Example to poll status of all devices in Devices.json
Author: Jason A. Cox
For more information see https://github.com/jasonacox/tinytuya
"""
import tinytuya
import json
import time
DEVICEFILE = 'devices.json'
SNAPSHOTFILE = 'snapshot.json'
havekeys = False
tuyadevices = []
# Terminal Color Formatting
bold = "\033[0m\033[97m\033[1m"
subbold = "\033[0m\033[32m"
normal = "\033[97m\033[0m"
dim = "\033[0m\033[97m\033[2m"
alert = "\033[0m\033[91m\033[1m"
alertdim = "\033[0m\033[91m\033[2m"
# Lookup Tuya device info by (id) returning (name, key)
def tuyaLookup(deviceid):
for i in tuyadevices:
if (i['id'] == deviceid):
return (i['name'], i['key'])
return ("", "")
# Read Devices.json
try:
# Load defaults
with open(DEVICEFILE) as f:
tuyadevices = json.load(f)
havekeys = True
except:
# No Device info
print(alert + "\nNo devices.json file found." + normal)
exit()
# Scan network for devices and provide polling data
print(normal + "\nScanning local network for Tuya devices...")
devices = tinytuya.deviceScan(False, 30)
print(" %s%s local active devices discovered%s" %
(dim, len(devices), normal))
print("")
def getIP(d, gwid):
for ip in d:
if (gwid == d[ip]['gwId']):
return (ip, d[ip]['version'])
return (0, 0)
polling = []
print("Polling local devices...")
for i in tuyadevices:
item = {}
name = i['name']
(ip, ver) = getIP(devices, i['id'])
item['name'] = name
item['ip'] = ip
item['ver'] = ver
item['id'] = i['id']
item['key'] = i['key']
if (ip == 0):
print(" %s[%s] - %s%s - %sError: No IP found%s" %
(subbold, name, dim, ip, alert, normal))
else:
try:
d = tinytuya.OutletDevice(i['id'], ip, i['key'])
d.set_version(float(ver)) # IMPORTANT to always set version
data = d.status()
if 'dps' in data:
item['dps'] = data
state = alertdim + "Off" + dim
try:
if '1' in data['dps'] or '20' in data['dps']:
state = bold + "On" + dim
print(" %s[%s] - %s%s - %s - DPS: %r" %
(subbold, name, dim, ip, state, data['dps']))
else:
print(" %s[%s] - %s%s - DPS: %r" %
(subbold, name, dim, ip, data['dps']))
except:
print(" %s[%s] - %s%s - %sNo Response" %
(subbold, name, dim, ip, alertdim))
else:
print(" %s[%s] - %s%s - %sNo Response" %
(subbold, name, dim, ip, alertdim))
except:
print(" %s[%s] - %s%s - %sNo Response" %
(subbold, name, dim, ip, alertdim))
polling.append(item)
# for loop
# Save polling data snapshot.json
tinytuya.scanner.save_snapshotfile( SNAPSHOTFILE, polling, None )