def setSwOn(self, command): DEVICEID = "017743508caab5f385a7" DEVICEIP = "192.168.1.148" DEVICEKEY = "7b8f2415ac96dfea" DEVICEVERS = "us" d=tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) LOGGER.info(' Turn Switch 2 On') d.turn_on() self.setDriver('GV2', 1)
def start(self): DEVICEID = "017743508caab5f0973e" DEVICEIP = "192.168.1.139" DEVICEKEY = "e779c96c964f71b2" DEVICEVERS = "us" LOGGER.info(DEVICEID) LOGGER.info(DEVICEIP) LOGGER.info(DEVICEKEY) LOGGER.info('us') # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TinyTuya - Smart Bulb RGB Test High [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) #LOGGER.info('TESTING: Device %s' % # (ip)) #self.setDriver('ST', 1) # Connect to the device - replace with real values d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Generate the payload to send - add all the DPS values you want to change here #if data != [0]: payload1 = d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) # time.sleep(2) payload2 = d.generate_payload(tinytuya.CONTROL, {'1': True, '2': 50}) # time.sleep(2) #payload1=d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) #payload2=d.generate_payload(tinytuya.CONTROL, {'1': True, '2': 50}) # Send the payload to the device #d._send_receive(payload1) #time.sleep(2) #d._send_receive(payload2) #LOGGER.info(str(ip).upper()) # Get the status of the device #response = requests.request("GET", url, headers=headers, data=payload) #LOGGER.info('Response. Using {}'str(d._send_receive(payload))) # Command for # Show status of device #self.setDriver('GV2', data, force=True) data = d.status() LOGGER.info('\nCurrent Status of Switch: %r' % data) #%r
def setSwOn(self, command): DEVICEID = "017743508caab5f0973e" #"DEVICEID" DEVICEIP = "192.168.1.147" #"DEVICEIP" DEVICEKEY = "e779c96c964f71b2" #"DEVICEKEY" DEVICEVERS = "us" # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) # self.nodes[input[key]['address']].runCmd(input[key]) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY)#('DEVICEID'), ('DEVICEIP'), ('DEVICEKEY') d.set_version(3.3) LOGGER.info(' Turn Switch 1 On') #d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) d.turn_on() self.setDriver('GV2', 1)
def start(self): #LOGGER.info('TESTING1: Switch %s' % (id)) #LOGGER.info(id) DEVICEID = "017743508caab5f385a7" DEVICEIP = "192.168.1.148" DEVICEKEY = "7b8f2415ac96dfea" DEVICEVERS = "us" LOGGER.info(DEVICEID) LOGGER.info(DEVICEIP) LOGGER.info(DEVICEKEY) #LOGGER.info('us') # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3)
def start(self): DEVICEID = "017743508caab5f0973e" DEVICEIP = "192.168.1.147" DEVICEKEY = "e779c96c964f71b2" DEVICEVERS = "us" LOGGER.info(DEVICEID) LOGGER.info(DEVICEIP) LOGGER.info(DEVICEKEY) #LOGGER.info('us') # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) self.setDriver('ST', 1)
def setSwOn(self, command): DEVICEID = "017743508caab5f385a7" DEVICEIP = "192.168.1.148" DEVICEKEY = "7b8f2415ac96dfea" DEVICEVERS = "us" d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) LOGGER.info(' Turn Switch 2 On') d.turn_on() ############ Need to figure out Status of Device to Driver for actual Status of Devices! ################# # __init__:_decode_payload: decoded results='{"devId":"017743508caab5f385a7","dps":{"1":true},"t":1623487883}' # __init__:set_status: set_status received data={'devId': '017743508caab5f385a7', 'dps': {'1': True}, 't': 1623487883} #LOGGER.info("\nREADING TEST: Response %r" % data) self.setDriver('GV2', 1)
def turn_off(name): # find the right item that matches name for data['devId'] in item['devId']: if item["name"] == name: break print("\nTurning Off: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(False)
def turn_off(self, command): # find the right item that matches name for item in data["devices"]: if item["name"] == name: break LOGGER.info("\nTurning Off: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(False)
def turn_on(name): # find the right item that matches name for item in data["devices"]: if item["name"] == name: break print("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True)
def setSwOn(self, command): for item in 'data'["devices"]: if item["name"] == name: break LOGGER.info("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True) self.setDriver('GV2', 1) pass
def test_status(self): d = tinytuya.OutletDevice('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', LOCAL_KEY) d.set_version(3.1) d._send_receive = MagicMock(side_effect=mock_send_receive_status) result = d.status() # Make sure mock_send_receive_set_timer() has been called twice with correct parameters self.assertEqual(result['test_result'], "SUCCESS")
def turn_on(name): # find the right item that matches name for data['devId'] in item[ 'devId']: ## 'devId' works: dps does not: devices if item["name"] == name: break print("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True)
def turn_on(self, command): # find the right item that matches name for item in data["devices"]: if item["name"] == name: break LOGGER.info("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True) turn_on('Switch Family Room Sconces')
def setup(): GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode GPIO.setup(sensorPin, GPIO.IN) # set sensorPin to INPUT mode d = tinytuya.OutletDevice(DEVICE_ID_HERE, IP_ADDRESS, LOCAL_KEY, 'device22') d.set_version(3.3) d.set_dpsUsed({"1": None}) data = d.status() # NOTE this does NOT require a valid key vor version 3.1 data = d.set_status(False) # socket is off return d
def deviceRaw(deviceid, ip, key, vers): """Poll Device for Status - raw DPS response rawData = tuyapower.deviceRaw(id, ip, key, vers) Parameters : id = Device ID e.g. 01234567891234567890 ip = Device IP Address e.g. 10.0.1.99 key = Device Key e.g. 0123456789abcdef vers = Version of Protocol 3.1 or 3.3 Response : rawData = Data response from device """ watchdog = 0 while True: data = False if(api == "tinytuya"): d = tinytuya.OutletDevice(deviceid, ip, key) else: d = pytuya.OutletDevice(deviceid, ip, key) if vers == "3.3": d.set_version(3.3) try: data = d.status() except KeyboardInterrupt: log.info( "CANCEL: Received interrupt from user while polling plug %s [%s]." % (deviceid, ip) ) except: watchdog += 1 if watchdog > RETRY: log.info( "TIMEOUT: No response from plug %s [%s] after %s attempts." % (deviceid, ip, RETRY) ) return ("ERROR: Timeout polling device") try: sleep(2) continue except KeyboardInterrupt: log.info( "CANCEL: Received interrupt from user while polling plug %s [%s]." % (deviceid, ip) ) return(data)
def test_set_status(self): d = tinytuya.OutletDevice('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', LOCAL_KEY) d.set_version(3.1) d._send_receive = MagicMock(side_effect=mock_send_receive_set_status) result = d.set_status(True, 1) result = result.decode( mock_byte_encoding ) # Python 3 (3.5.4 and earlier) workaround to json stdlib "behavior" https://docs.python.org/3/whatsnew/3.6.html#json result = json.loads(result) # Make sure mock_send_receive_set_timer() has been called twice with correct parameters self.assertEqual(result['test_result'], "SUCCESS")
def start(self): #SWITCHIP = 'IP' #LOGGER.info('IP') #LOGGER.info(ip) #LOGGER.info('TESTING1: Switch %s' % (id)) #LOGGER.info(id) DEVICEID = "017743508caab5f0973e" DEVICEIP = "192.168.1.146" DEVICEKEY = "e779c96c964f71b2" DEVICEVERS = "us" #LOGGER.info(DEVICEID) #LOGGER.info(DEVICEIP) #LOGGER.info(DEVICEKEY) #LOGGER.info('us') # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Generate the payload to send - add all the DPS values you want to change here #if data != [0]: payload1 = d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) # time.sleep(2) payload2 = d.generate_payload(tinytuya.CONTROL, {'1': True, '2': 50}) # time.sleep(2) d._send_receive(payload1) time.sleep(2) d._send_receive(payload2) time.sleep(2) d._send_receive(payload1) time.sleep(2) d._send_receive(payload2) data = d.status() LOGGER.info('\nCurrent Status of Switch: %r' % data) #%r
def __init__(self, deviceId=None, ip=None, localKey=None, version=3.1): """ :param deviceId: ID from tinytuya scan :param ip: Ip of device :param localKey: LocalKey from tinytuya wizard :param version: on Windows run 3.1 """ self.deviceName = "desklight" self.deviceId = deviceId self.ip = ip self.localKey = localKey self.version = version self.driver = tinytuya.OutletDevice(self.deviceId, self.ip, self.localKey) self.driver.set_version(self.version) self.check_status()
def query(self, command=None): DEVICEID = self.DEVICEID DEVICEIP = self.DEVICEIP DEVICEKEY = self.DEVICEKEY DEVICEVERS = self.DEVICEVERS DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) # Switch Status d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) data = d.status() LOGGER.info(data['dps']['1']) if data['dps']['1'] == True: self.setDriver('GV3', 1) if data['dps']['1'] == False: self.setDriver('GV3', 0) self.reportDrivers()
def setSwOff(self, command): DEVICEID = self.DEVICEID DEVICEIP = self.DEVICEIP DEVICEKEY = self.DEVICEKEY DEVICEVERS = self.DEVICEVERS DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) LOGGER.info(' Turn Switch Off') d.turn_off() self.setDriver('GV2', 0) self.query(self)
def get_plug_power(): plug_status_body = {} for item in plug_mapping: logger.info('getting plug data from {}'.format(item['label'])) d = tinytuya.OutletDevice(item['dev_id'], item['address'], item['local_key']) d.set_version(3.3) try: data = d.status() # Show status of first controlled switch on device logger.info('Dictionary {}'.format(data)) logger.info('State (bool, true is ON) {}'.format(data['dps']['1'])) logger.info('Power {}'.format(float(data['dps']['19']) / 10.0)) plug_status_body[item['label']] = (float(data['dps']['19']) / 10.0) except: logger.error("d.status failed.") return plug_status_body
def discover(self, *args, **kwargs): DEVICEID = "017743508caab5f0973e" DEVICEIP = "192.168.1.137" DEVICEKEY = "e779c96c964f71b2" DEVICEVERS = "us" LOGGER.info(DEVICEID) LOGGER.info(DEVICEIP) LOGGER.info(DEVICEKEY) LOGGER.info('us') # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TinyTuya - Smart Bulb RGB Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) # Connect to the device - replace with real values d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Generate the payload to send - add all the DPS values you want to change here #if data != [0] payload1 = d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) time.sleep(2) payload2 = d.generate_payload(tinytuya.CONTROL, {'1': True, '2': 50}) #time.sleep(2) #payload1=d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) #payload2=d.generate_payload(tinytuya.CONTROL, {'1': True, '2': 50}) # Send the payload to the device d._send_receive(payload1) time.sleep(2) d._send_receive(payload2)
def setSwOn(self, command): DEVICEID = self.DEVICEID DEVICEIP = self.DEVICEIP DEVICEKEY = self.DEVICEKEY DEVICEVERS = self.DEVICEVERS DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice( DEVICEID, DEVICEIP, DEVICEKEY) #('DEVICEID'), ('DEVICEIP'), ('DEVICEKEY') d.set_version(3.3) d.turn_on() LOGGER.info(' Turn Switch On') #d.generate_payload(tinytuya.CONTROL, {'1': False, '2': 50}) self.setDriver('GV2', 1) self.query(self)
def setSwOff(self, command): DEVICEID = "017743508caab5f385a7" DEVICEIP = "192.168.1.148" DEVICEKEY = "7b8f2415ac96dfea" DEVICEVERS = "us" # Check for environmental variables and always use those if available DDEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) LOGGER.info("TreatLife - Smart Switch Test [%s]\n" % tinytuya.__version__) LOGGER.info('TESTING: Device %s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) LOGGER.info('TESTING: Device %s' % (DEVICEIP)) d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) LOGGER.info(' Turn Switch 2 Off') d.turn_off() #LOGGER.info('\nCurrent Status of', ['received data'], 'Light: %r' % 'dps') self.setDriver('GV2', 0)
async def update_energy(self): tinytuya.set_debug(True) # Use tinytuya.set_debug(True,False) for windows command prompt (no color) d = tinytuya.OutletDevice('bf88154973e45bbb96aaci', '192.168.137.141', '932ccff3371cd2eb') d.set_version(3.3) print(" > Fetch Status < ") data = d.status() print(data) d.heartbeat() time.sleep(1) print(" > Request Update < ") result = d.updatedps([18,19,20]) # command 18 print(result) print(" > Fetch Status Again < ") data2 = d.status() print(data2) print("") print("Before %r" % data) print("After %r" % data2)
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']) if ver == "3.3": d.set_version(3.3) 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:
def tuyaPlatform(self, apiRegion, apiKey, apiSecret, uri, token=None): request = "https://openapi.tuya%s.com/v1.0/%s" % (apiRegion, uri) now = int(time.time() * 1000) if (token == None): payload = apiKey + str(now) else: payload = apiKey + token + str(now) # Sign Payload signature = hmac.new(apiSecret.encode('utf-8'), msg=payload.encode('utf-8'), digestmod=hashlib.sha256).hexdigest().upper() # Create Header Data headers = {} headers['client_id'] = apiKey headers['sign_method'] = 'HMAC-SHA256' headers['t'] = str(now) headers['sign'] = signature if (token != None): headers['access_token'] = token # Get Token response = requests.get(request, headers=headers) try: response_dict = json.loads(response.content.decode()) except: try: response_dict = json.loads(response.content) except: LOGGER.debug("Failed to get valid JSON response") #return(response_dict) #def wizard(self, command, color=True): config = {} config['apiKey'] = 'default_apiKey' #'txejpdfda9iwmn5cg2es' config[ 'apiSecret'] = 'default_apiSecret' #'46d6072ffd724e0ba5ebeb5cc6b9dce9' config['apiRegion'] = 'us' config['apiDeviceID'] = 'default_apiDeviceId' #'017743508caab5f0973e' needconfigs = True if (config['apiKey'] != '' and config['apiSecret'] != '' and config['apiRegion'] != '' and config['apiDeviceID'] != ''): needconfigs = False answer = 'Y' #input(subbold + ' Use existing credentials ' + # normal + '(Y/n): ') if ('Y'[0:1].lower() == 'n'): needconfigs = True KEY = config['apiKey'] SECRET = config['apiSecret'] DEVICEID = config['apiDeviceID'] REGION = config['apiRegion'] # us, eu, cn, in LANG = 'en' # en or zh # Get Oauth Token from tuyaPlatform uri = 'token?grant_type=1' response_dict = tuyaPlatform(REGION, KEY, SECRET, uri) token = response_dict['result']['access_token'] # Get UID from sample Device ID uri = 'devices/%s' % DEVICEID response_dict = tuyaPlatform(REGION, KEY, SECRET, uri, token) uid = response_dict['result']['uid'] # Use UID to get list of all Devices for User uri = 'users/%s/devices' % uid json_data = tuyaPlatform(REGION, KEY, SECRET, uri, token) response_dict = response_dict # Filter to only Name, ID and Key tuyadevices = [] for i in json_data['result']: item = {} item['name'] = i['name'].strip() item['id'] = i['id'] item['key'] = i['local_key'] tuyadevices.append(item) #Display device list LOGGER.info("\n\n" + "Device Listing\n") output = json.dumps(tuyadevices, indent=4) # sort_keys=True) LOGGER.info(output) # Save list to devices.json ##LOGGER.info(bold + "\n>> " + normal + "Saving list to " + DEVICEFILE) ##with open(DEVICEFILE, "w") as outfile: ## outfile.write(output) ##LOGGER.info(dim + " %d registered devices saved" % len(tuyadevices)) if ('Y'[0:1].lower() != 'n'): # Scan network for devices and provide polling data ##LOGGER.info(normal + "\nScanning local network for Tuya devices...") devices = tinytuya.deviceScan(False, 20) ##LOGGER.info(" %s%s local devices discovered%s" % ## (len(devices))) ##LOGGER.info("") def getIP(d, gwid): for ip in d: if (gwid == d[ip]['gwId']): return (ip, d[ip]['version']) return (0, 0) polling = [] LOGGER.info("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): LOGGER.info(" %s[%s] - %s%s - %sError: No IP found%s" % (name, ip, name)) else: try: d = tinytuya.OutletDevice(i['id'], ip, i['key']) if ver == "3.3": d.set_version(3.3) data = d.status() if 'dps' in data: item['devId'] = data #state = alertdim + "Off" try: if '1' in data['dps'] or '20' in data[ 'devId'] or '1' in data['dps']: #state = "On" #LOGGER.info(" %s[%s] - %s%s - %s - DPS: %r" % # (name, ip, state, data['dps']) LOGGER.info( "\nEACH TREATLIFE SWITCH TO NODE WITH ADDNODE FROM HERE!!!" ) LOGGER.info( "%-35.35s %-24s %-16s %-17s %-5s" % (item["name"], item["id"], item["ip"], item["key"], item["ver"])) else: #LOGGER.info(" %s[%s] - %s%s - DPS: %r" % # (name, ip, data['dps'])) pass except: #LOGGER.info(" %s[%s] - %s%s - %sNo Response" % # (subbold, name, dim, ip, alertdim)) pass else: #LOGGER.info(" %s[%s] - %s%s - %sNo Response" % # (subbold, name, dim, ip, alertdim)) pass except: pass #LOGGER.info(" %s[%s] - %s%s - %sNo Response" % # (subbold, name, dim, ip, alertdim)) polling.append(item) # for loop # Save polling data snapsot current = {'timestamp': time.time(), 'devices': polling} output = json.dumps(current, indent=4) SWITCHID = i['id'] SWITCHIP = item["ip"] SWITCHKEY = item["key"] LOGGER.info("Currently Passed Name:", 'item'["name"]) LOGGER.info('SWITCHID') # Device Name #LOGGER.info(SWITCHIP) # Device IP #LOGGER.info(SWITCHKEY) LOGGER.info("TEST1 ID" + 'item'["id"]) # Device ID LOGGER.info("TEST1 KEY" + 'item'["key"]) # Device Key
def wizard(color=True): """ TinyTuya Setup Wizard Tuya based WiFi smart devices Parameter: color = True or False, print output in color [Default: True] Description Setup Wizard will prompt user for Tuya IoT Developer credentials and will gather all of the Device IDs and their Local KEYs. It will save the credentials and the device data in the tinytuya.json and devices.json configuration files respectively. HOW to set up your Tuya IoT Developer account: iot.tuya.com: https://github.com/jasonacox/tinytuya#get-the-tuya-device-local-key Credits * Tuya API Documentation https://developer.tuya.com/en/docs/iot/open-api/api-list/api?id=K989ru6gtvspg * TuyaAPI https://github.com/codetheweb/tuyapi by codetheweb and blackrozes The TuyAPI/CLI wizard inspired and informed this python version. """ # Get Configuration Data CONFIGFILE = 'tinytuya.json' DEVICEFILE = 'devices.json' SNAPSHOTFILE = 'snapshot.json' config = {} config['apiKey'] = '' config['apiSecret'] = '' config['apiRegion'] = '' config['apiDeviceID'] = '' needconfigs = True try: # Load defaults with open(CONFIGFILE) as f: config = json.load(f) except: # First Time Setup pass if (color == False): # Disable Terminal Color Formatting bold = subbold = normal = dim = alert = alertdim = "" else: # 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" print(bold + 'TinyTuya Setup Wizard' + dim + ' [%s]' % (tinytuya.version) + normal) print('') if (config['apiKey'] != '' and config['apiSecret'] != '' and config['apiRegion'] != '' and config['apiDeviceID'] != ''): needconfigs = False print( " " + subbold + "Existing settings:" + dim + "\n API Key=%s \n Secret=%s\n DeviceID=%s\n Region=%s" % (config['apiKey'], config['apiSecret'], config['apiDeviceID'], config['apiRegion'])) print('') answer = input(subbold + ' Use existing credentials ' + normal + '(Y/n): ') if (answer[0:1].lower() == 'n'): needconfigs = True if (needconfigs): # Ask user for config settings print('') config['apiKey'] = input(subbold + " Enter " + bold + "API Key" + subbold + " from tuya.com: " + normal) config['apiSecret'] = input(subbold + " Enter " + bold + "API Secret" + subbold + " from tuya.com: " + normal) config['apiDeviceID'] = input( subbold + " Enter " + bold + "any Device ID" + subbold + " currently registered in Tuya App (used to pull full list): " + normal) # TO DO - Determine apiRegion based on Device - for now, ask config['apiRegion'] = input(subbold + " Enter " + bold + "Your Region" + subbold + " (Options: us, eu, cn or in): " + normal) # Write Config json_object = json.dumps(config, indent=4) with open(CONFIGFILE, "w") as outfile: outfile.write(json_object) print(bold + "\n>> Configuration Data Saved to " + CONFIGFILE) print(dim + json_object) KEY = config['apiKey'] SECRET = config['apiSecret'] DEVICEID = config['apiDeviceID'] REGION = config['apiRegion'] # us, eu, cn, in LANG = 'en' # en or zh # Get Oauth Token from tuyaPlatform uri = 'token?grant_type=1' response_dict = tuyaPlatform(REGION, KEY, SECRET, uri) token = response_dict['result']['access_token'] # Get UID from sample Device ID uri = 'devices/%s' % DEVICEID response_dict = tuyaPlatform(REGION, KEY, SECRET, uri, token) uid = response_dict['result']['uid'] # Use UID to get list of all Devices for User uri = 'users/%s/devices' % uid json_data = tuyaPlatform(REGION, KEY, SECRET, uri, token) # Filter to only Name, ID and Key tuyadevices = [] for i in json_data['result']: item = {} item['name'] = i['name'].strip() item['id'] = i['id'] item['key'] = i['local_key'] tuyadevices.append(item) # Display device list print("\n\n" + bold + "Device Listing\n" + dim) output = json.dumps(tuyadevices, indent=4) # sort_keys=True) print(output) # Save list to devices.json print(bold + "\n>> " + normal + "Saving list to " + DEVICEFILE) with open(DEVICEFILE, "w") as outfile: outfile.write(output) print(dim + " %d registered devices saved" % len(tuyadevices)) # Find out if we should poll all devices answer = input(subbold + '\nPoll local devices? ' + normal + '(Y/n): ') if (answer[0:1].lower() != 'n'): # Scan network for devices and provide polling data print(normal + "\nScanning local network for Tuya devices...") devices = tinytuya.deviceScan(False, 20) print(" %s%s local 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']) if ver == "3.3": d.set_version(3.3) 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']: if '1' in data['dps']: if data['dps']['1'] == True: state = bold + "On" + dim if '20' in data['dps']: if data['dps']['20'] == True: 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 snapsot current = {'timestamp': time.time(), 'devices': polling} output = json.dumps(current, indent=4) print(bold + "\n>> " + normal + "Saving device snapshot data to " + SNAPSHOTFILE) with open(SNAPSHOTFILE, "w") as outfile: outfile.write(output) print("\nDone.\n") return
def wizard(color=True): ########################################################################################### CUSTOM PARAMETERS ################################################################################################################## ####################################### Loads as custom parameters in Node Server ############################### config = {} config['apiKey'] = "txejpdfda9iwmn5cg2es" config['apiSecret'] = "46d6072ffd724e0ba5ebeb5cc6b9dce9" config['apiRegion'] = 'us' config['apiDeviceID'] = "017743508caab5f0973e" needconfigs = True SNAPSHOTFILE = 'snapshot.json' print('') print('TreatLife Device Discovery') print('') print('Authentication' + ' [%s]' % (tinytuya.version)) if (config['apiKey'] != '' and config['apiSecret'] != '' and config['apiRegion'] != '' and config['apiDeviceID'] != ''): needconfigs = False answer = 'Y' #input(subbold + ' Use existing credentials ' + # normal + '(Y/n): ') if ('Y'[0:1].lower() == 'n'): needconfigs = True KEY = config['apiKey'] SECRET = config['apiSecret'] DEVICEID = config['apiDeviceID'] REGION = config['apiRegion'] # us, eu, cn, in LANG = 'us' # en or zh # Get Oauth Token from tuyaPlatform uri = 'token?grant_type=1' response_dict = tuyaPlatform(REGION, KEY, SECRET, uri) token = response_dict['result']['access_token'] # Get UID from sample Device ID uri = 'devices/%s' % DEVICEID response_dict = tuyaPlatform(REGION, KEY, SECRET, uri, token) uid = response_dict['result']['uid'] # Use UID to get list of all Devices for User uri = 'users/%s/devices' % uid json_data = tuyaPlatform(REGION, KEY, SECRET, uri, token) #print("Full json above", json_data) # Filter to only Name, ID and Key tuyadevices = [] for i in json_data['result']: item = {} item['name'] = i['name'].strip() item['id'] = i['id'] item['key'] = i['local_key'] item['ip'] = i['ip'] ####Added IP tuyadevices.append(item) #print() #print("%-35.35s %-24s %-16s %-17s" % ( # i['name'], # i['id'], # i['ip'], # i['local_key'] # )) # Display device list ##print("\n\n" + "Device Listing\n") ##output = json.dumps(tuyadevices, indent=4) # sort_keys=True) ##print("\n\n" + "Hello Here's are the Devices with INTERNET ACTIVE IP ADDRESSES \n\n " + output) if ('Y'[0:1].lower() != 'n'): # Scan network for devices and provide polling data ###print(normal + "\nScanning local network for Tuya devices...") devices = tinytuya.deviceScan(False, 20) #### changed 20 to 1 #print(" %s%s local devices discovered%s" % # ( len(devices))) print("") def getIP(d, gwid): for ip in d: if (gwid == d[ip]['gwId']): return (ip, d[ip]['version']) return (0, 0) ################################### For Loop Switches ########################################################################################## polling = [] print("Polling TreatLife Switch Devices...\n") for i in tuyadevices: item = {} name = i['name'] (ip, ver) = getIP(devices, i['id']) ## 'id' item['name'] = name item['ip'] = ip item['ver'] = ver item['id'] = i['id'] item['key'] = i['key'] if (ip == 0): pass else: try: d = tinytuya.OutletDevice(i['id'], ip, i['key']) if ver == "3.3": d.set_version(3.3) data = d.status() if 'dps' in data: item['devId'] = data #state = alertdim + "Off" + dim try: if '1' in data['dps'] or '20' in data[ 'devId'] or '20' in data[ 'dps']: # if '20' in data['dps'] or '1' in data['devId'] or '20' in data['dps']: = all devices #state = "On" # if '20' in data['dps'] or '20' in data['devId'] or '20' in data['dps']: = just lights #print(" %s[%s] - %s%s - %s - DPS: %r" % # if '1' in data['dps'] or '20' in data['devId'] or '1' in data['dps']: = just switches # (name, ip, state, data['dps'])) print( "\nEACH TREATLIFE SWITCH TO NODE WITH ADDNODE FROM HERE!!!" ) ########################## addNode Switches HERE!! ###################################################################### print("%-35.35s %-24s %-16s %-17s %-5s" % (item["name"], item["id"], item["ip"], item["key"], item["ver"])) else: pass except: pass else: pass except: pass polling.append(item) ################################### For Loop Lights ########################################################################################## polling = [] polling = [] print("\nPolling TreatLife Light Devices...\n") for i in tuyadevices: item = {} name = i['name'] (ip, ver) = getIP(devices, i['id']) ## 'id' item['name'] = name item['ip'] = ip item['ver'] = ver item['id'] = i['id'] item['key'] = i['key'] if (ip == 0): pass else: try: d = tinytuya.OutletDevice(i['id'], ip, i['key']) if ver == "3.3": d.set_version(3.3) data = d.status() if 'dps' in data: item['devId'] = data #state = alertdim + "Off" + dim try: if '20' in data['dps'] or '20' in data[ 'devId'] or '20' in data[ 'dps']: # if '20' in data['dps'] or '1' in data['devId'] or '20' in data['dps']: = all devices #state = "On" # if '20' in data['dps'] or '20' in data['devId'] or '20' in data['dps']: = just lights #print(" %s[%s] - %s%s - %s - DPS: %r" % # if '1' in data['dps'] or '20' in data['devId'] or '1' in data['dps']: = just switches # (name, ip, state, data['dps'])) print( "\nEACH TREATLIFE LIGHT TO NODE WITH ADDNODE FROM HERE!!!" ) ########################## addNode Lights HERE!! ###################################################################### print("%-35.35s %-24s %-16s %-17s %-5s" % (item["name"], item["id"], item["ip"], item["key"], item["ver"])) else: pass except: pass else: pass except: pass polling.append(item) # for loop ###################################################### JSON STATUS ################################################### # Save polling data snapsot current = { 'timestamp': time.time(), 'devices': polling } #current = {'timestamp' : time.time(), 'devices' : polling} output = json.dumps(current, indent=4) #output = json.dumps(current, indent=4) ##print("") ##print("Hello Here's the JSON \n " + output) #Prints output.json ##print("") #print("Full json below", json_data) #print(json.dumps({'devices' : polling, 'devces' : item['name']})) json.dumps(output, indent=4, sort_keys=True) # Saves Device json to root ##print("Saving device snapshot data to " + SNAPSHOTFILE) #with open(SNAPSHOTFILE, "w") as outfile: # outfile.write(output) #print(json.dumps([[{'id' : polling}]])) #print(json.dumps({'ip' : polling})) #print(json.dumps({'key' : polling})) # Prints full list print("%-35.35s %-24s %-16s %-17s" % (item["name"], item["id"], item['ip'], item["key"])) print( '\nCurrent Status of', 'devices', item["name"] ) # print('\nCurrent Status of', 'devices', item["name"], 'Light: %r' % data) print("\n", current) #print("\nHello ", item["name"], name['Under Cabinets']) print("\nDone.\n") return
def wizard(color=True): ########################################################################################### CUSTOM PARAMETERS ################################################################################################################## ####################################### Loads as custom parameters in Node Server ############################### config = {} config['apiKey'] = "txejpdfda9iwmn5cg2es" config['apiSecret'] = "46d6072ffd724e0ba5ebeb5cc6b9dce9" config['apiRegion'] = 'us' config['apiDeviceID'] = "017743508caab5f0973e" needconfigs = True print('') print('TreatLife Device Discovery') print('') print('Authentication' + ' [%s]' % (tinytuya.version)) ##print## 2 if (config['apiKey'] != '' and config['apiSecret'] != '' and config['apiRegion'] != '' and config['apiDeviceID'] != ''): needconfigs = False answer = 'Y' #input(subbold + ' Use existing credentials ' + # normal + '(Y/n): ') if ('Y'[0:1].lower() == 'n'): needconfigs = True KEY = config['apiKey'] SECRET = config['apiSecret'] DEVICEID = config['apiDeviceID'] REGION = config['apiRegion'] # us, eu, cn, in LANG = 'us' # en or zh # Get Oauth Token from tuyaPlatform uri = 'token?grant_type=1' response_dict = tuyaPlatform(REGION, KEY, SECRET, uri) token = response_dict['result']['access_token'] # Get UID from sample Device ID uri = 'devices/%s' % DEVICEID response_dict = tuyaPlatform(REGION, KEY, SECRET, uri, token) uid = response_dict['result']['uid'] # Use UID to get list of all Devices for User uri = 'users/%s/devices' % uid json_data = tuyaPlatform(REGION, KEY, SECRET, uri, token) # Filter to only Name, ID and Key tuyadevices = [] for i in json_data['result']: item = {} item['name'] = i['name'].strip() item['id'] = i['id'] item['key'] = i['local_key'] item['ip'] = i['ip'] ####Added IP tuyadevices.append(item) # Display device list #print("\n\n" + "Device Listing\n") output = json.dumps(tuyadevices, indent=4) # sort_keys=True) ##print("\n\n" + "Hello Here's are the Devices with INTERNET ACTIVE IP ADDRESSES \n\n " + output) ######################### Device Switch Poller ################################### # # # Using devId to poll Switches with lights or should i use key length??????#### # # # NEED TO GRAB SWITCH DEVICES AND MAKE THEM SEPARATE NODES FOR EACH SWITCH/LIGHT # # # ######################### By-Pass Data Input ##################################### if ('Y'[0:1].lower() != 'n'): # Scan network for devices and provide polling data ###print(normal + "\nScanning local network for Tuya devices...") devices = tinytuya.deviceScan(False, 20) #### changed 20 to 1 #print(" %s%s local devices discovered%s" % # ( len(devices))) 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 TreatLife Devices...\n") for i in tuyadevices: item = {} name = i['name'] (ip, ver) = getIP(devices, i['id']) ## '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" % # (name, ip, alert, normal)) pass else: try: d = tinytuya.OutletDevice(i['id'], ip, i['key']) if ver == "3.3": d.set_version(3.3) data = d.status() if 'dps' in data: item['devId'] = data #state = alertdim + "Off" + dim try: if '1' in data['dps'] or '1' in data[ 'devId']: # if '1' to '20' for all Devices #state = "On" #print(" %s[%s] - %s%s - %s - DPS: %r" % # (name, ip, state, data['dps'])) print( "\nEACH TREATLIFE SWITCH TO NODE WITH ADDNODE FROM HERE!!!" ) ########################## addNode HERE!! ###################################################################### print("%-35.35s %-24s %-16s %-17s %-5s" % (item["name"], item["id"], item["ip"], item["key"], item["ver"])) else: pass except: pass else: pass except: pass polling.append(item) # for loop ###################################################### JSON STATUS ################################################### # Save polling data snapsot current = { 'timestamp': time.time(), 'devices': polling } #current = {'timestamp' : time.time(), 'devices' : polling} output = json.dumps(current, indent=4) #output = json.dumps(current, indent=4) print("") print("Hello Here's the JSON \n " + output) #Prints output.json print("") ####################################################################################### NODE SWITCH CLASS START HERE ########################################################################################################## #class SwitchNodes(polyinterface.Node): #def __init__(self, controller, primary, address, name): #, ip, id1, key1 # super(SwitchNodes, self).__init__(controller, primary, address, name) ######################## SEPERATE OUT THE SWITCHES THEY HAVE "devId" IN BETWEEN 'DPS' or should I use length???? ############## ######################## Passed to Nodes ############################# print("Currently Passed Name:", item["name"]) DEVICEID = item["id"] #"017743508caab5f0973e" print("Currently Passed ID:", DEVICEID) DEVICEIP = item["ip"] #"192.168.1.146" print("Currently Passed IP:", DEVICEIP) DEVICEKEY = item["key"] #"e779c96c964f71b2" print("Currently Passed KEY:", DEVICEKEY + "\n") DEVICEVERS = "us" ########################################################################################### NODE SERVER NODES ################################################################################################################# ######################## Node Switch by DEVICE Example ######################################### # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) if data["dps"] != '20': #print("\nTreatLife - Smart Device Test [%s]\n" % tinytuya.__version__) print( "TESTING NODE Switch by DEVICE: ", item["name"], '%s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) # Connect to the device - replace with real values d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Payload to Cycle Switch payload1 = d.generate_payload(tinytuya.CONTROL, {'1': False, '9': 0}) payload2 = d.generate_payload(tinytuya.CONTROL, {'1': True, '9': 0}) # Send the payload to the device # Test by DEVICE def on_1(self): payload1 = d.generate_payload(tinytuya.CONTROL, { '1': False, '9': 0 }) time.sleep(1) payload2 = d.generate_payload(tinytuya.CONTROL, { '1': True, '9': 0 }) if data["devId"] != '20': print("\nTest Cycle Switch by DEVICE ON") d._send_receive(payload1) print('\nCurrent Status of', item["name"], 'Switch: %r' % data) time.sleep(2) print("\n\nTest Cycle Switch by DEVICE OFF") d._send_receive(payload2) print('\nCurrent Status of', item["name"], 'Switch: %r' % data) on_1('self') print("\nTest Cycle Switch by def on") ###################### Node Light by DEVICE Example ######################################### # Check for environmental variables and always use those if available DEVICEID = os.getenv("DEVICEID", DEVICEID) DEVICEIP = os.getenv("DEVICEIP", DEVICEIP) DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY) DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS) if data["dps"] == '20': #print("\nTreatLife - Smart Light Test [%s]\n" % tinytuya.__version__) print( '\n\nTESTING NODE Light by DEVICE: Device ', item["name"], '%s at %s with key %s version %s' % (DEVICEID, DEVICEIP, DEVICEKEY, DEVICEVERS)) # Connect to the device - replace with real values d = tinytuya.OutletDevice(DEVICEID, DEVICEIP, DEVICEKEY) d.set_version(3.3) # Payload to Cycle Light payload1 = d.generate_payload(tinytuya.CONTROL, {'20': False, '2': 50}) payload2 = d.generate_payload(tinytuya.CONTROL, {'20': True, '2': 50}) if data["dps"] == '20': #if data["dps"] or item["dps"] != '1': TRY WHEN BACK print("\nTest Cycle Light by DEVICE ON") d._send_receive(payload1) print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) print("\n\nTest Cycle Light by DEVICE OFF\n") d._send_receive(payload2) print('\nCurrent Status of', item["name"], 'Light: %r' % data) ###################### Node Switch by NAME Example ######################################### # Turn on a device by name def turn_on(name): # find the right item that matches name for data['devId'] in item[ 'devId']: ## 'devId' works: dps does not: devices if item["name"] == name: break print("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True) # Turn off a device by name def turn_off(name): # find the right item that matches name for data['devId'] in item['devId']: if item["name"] == name: break print("\nTurning Off: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(False) if data["dps"] != '20': print("\n\nTest Cycle Switch by Name \n") turn_off( 'Switch Family Room Sconces' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Switch: %r' % data) time.sleep(1) turn_on( 'Switch Family Room Sconces' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Switch: %r' % data) time.sleep(1) turn_off( 'Switch Office Outside Lights' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Switch: %r' % data) time.sleep(1) turn_on( 'Switch Office Outside Lights' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Switch: %r' % data) ###################### Node Light by NAME Example ######################################### # Turn on a device by name def turn_on(name): if data["dps"] == '20': # find the right item that matches name for data['dps'] in item['dps']: if item["name"] == name: break print("\nTurning On: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(True) # Turn off a device by name def turn_off(name): if data["dps"] == '20': # find the right item that matches name for data['dps'] in item['dps']: if item["name"] == name: break print("\nTurning Off: %s" % item["name"]) d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"]) d.set_version(float(item["ver"])) d.set_status(False) if data["dps"] == '20': print("\n\nTest Cycle Light by Name \n") turn_off( 'Office Light' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) turn_on( 'Office Light' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) turn_off( 'Garage' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) turn_on( 'Garage' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) turn_off( 'Under Cabinets' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) time.sleep(2) turn_on( 'Under Cabinets' ) #Switch Family Room Sconces #Switch Office Outside Lights print('\nCurrent Status of', item["name"], 'Light: %r' % data) # Who was passed print("\n" + item["name"]) print(item["id"]) print(item["ip"]) print(item["key"] + "\n") print("\nDone.\n") return