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
示例#2
0

# 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:
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
示例#4
0
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
示例#5
0
    def wizard(self, command, color=True):

        color = True
        ### Credentials Needed
        # Get Configuration Data
        CONFIGFILE = 'tinytuya.json'
        #DEVICEFILE = 'devices.json'
        #SNAPSHOTFILE = 'snapshot.json'
        config = {}
        config['apiKey'] = 'default_apiKey'  #'txejpdfda9iwmn5cg2es'
        config[
            'apiSecret'] = 'default_apiSecret'  #'46d6072ffd724e0ba5ebeb5cc6b9dce9'
        config['apiRegion'] = 'us'
        config['apiDeviceID'] = 'default_apiDeviceId'  #'017743508caab5f0973e'
        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"

        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
        #LOGGER.info("\n\n" + bold + "Device Listing\n" + dim)
        #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" %
                        (dim, len(devices), normal))
            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 = {}
                name1 = i['name']
                id1 = i['id']
                key1 = i['key']
                item['key'] = key1
                (ip, ver) = getIP(devices, i['id'])
                item['name'] = name1
                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" %
                                (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 data:
                            item['dps'] = data
                            state = alertdim + "Off" + dim
                            # LOGGER.info(data)
                            try:
                                if (data['dps']['1'] == True):
                                    state = bold + "On" + dim
                                LOGGER.info(
                                    'WOW' +
                                    "    %s[%s] - %s%s - %s - DPS: %r" %
                                    (subbold, name, dim, ip, state,
                                     data['dps']))
                            except:
                                pass
                                #LOGGER.info("    %s[%s] - %s%s - %sNo Response" %
                                #      (subbold, name, dim, ip, alertdim))
                        else:
                            pass
                            #LOGGER.info("    %s[%s] - %s%s - %sNo Response" %
                            #      (subbold, name, dim, ip, alertdim))
                    except:
                        pass
                        #LOGGER.info("    %s[%s] - %s%s - %sNo Response" %
                        #      (subbold, name, dim, ip, alertdim))
                polling.append(item)

        return
        # for loop

        # Save polling data snapsot
        ##current = {'timestamp' : time.time(), 'devices' : polling}
        ##output = json.dumps(current, indent=4)
        ##LOGGER.info(bold + "\n>> " + normal + "Saving device snapshot data to " + SNAPSHOTFILE)
        ##with open(SNAPSHOTFILE, "w") as outfile:
        ##    outfile.write(output)
        ### addNode
        #if(data['dps']['1']==True):
        #   state = bold + "On" + dim
        #  LOGGER.debug("    %s[%s] - %s%s - %s - DPS: %r" %
        #(subbold, name, dim, ip, state, data['dps']))

        #LOGGER.info("\nDone Polling Switches.\n")
        #return
        LOGGER.info(name)  # Device Name
        LOGGER.info('TESTING1: Device ip %s' % (ip))
        LOGGER.info(ip)  # Device IP
        LOGGER.info(id1)  # Device ID
        LOGGER.info(key1)  # Device Key
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):
    ####################### This is already in Node Sever for Custom Parameters for api Information below ###########
    #
    ####################### Change All print statements to LOGGER.info() ############################################
    # Get Configuration Data
    #CONFIGFILE = 'tinytuya.json'
    #DEVICEFILE = #'devices.json'
    #SNAPSHOTFILE = 'output.json'
    config = {}
    config['apiKey'] = "txejpdfda9iwmn5cg2es"
    config['apiSecret'] = "46d6072ffd724e0ba5ebeb5cc6b9dce9"
    config['apiRegion'] = 'us'
    config['apiDeviceID'] = "017743508caab5f0973e"
    needconfigs = True
    ####################################### Loads as custom parameters in Node Server ###############################
    ##try:
    # Load defaults
    ##    with open(CONFIGFILE) as f:
    ##        config = json.load(f)
    ## except:
    # First Time Setup
    ##    pass

    print('')
    print('Hello Polling Switches')
    print('')
    print(
        'TinyTuya Switch Discoverer' + ' [%s]' % (tinytuya.version)
    )  #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
        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 \n\n " + output)

    # Save list to devices.json
    ##print("\n>> " + "Saving list to " + DEVICEFILE)
    ##with open(DEVICEFILE, "w") as outfile:
    ##    outfile.write(output)
    ##    print("    %d registered devices saved" % len(tuyadevices))

    ######################### Device Switch Poller #################################
    #
    # Using devId to poll Switches without lights or should i use key length??????#$$
    #
    # NEED TO GRAB SWITCH DEVICES AND MAKE THEM SEPARATE NODES FOR EACH SWITCH $$$$$$
    #
    ######################### By-Pass Data Input ########################$$$$$$$$$$$$
    # Find out if we should poll all devices
    #answer = 'Yes' #input(subbold + '\nPoll local devices? ' +
    #     normal + '(Y/n): ')
    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("\n" + "Polling 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):
                #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['devId'] or 'devId' in data['devId']:
                                #state = "On"
                                #print("    %s[%s] - %s%s - %s - DPS: %r" %
                                #(name, ip, state, data['dps']))
                                print("%-35.35s %-24s %-16s %-17s %-5s" %
                                      (item["name"], item["id"], item["ip"],
                                       item["key"], item["ver"]))
                            else:
                                print("    %s[%s] - %s%s - DPS: %r" %
                                      (name, ip, data['devId']))
                                pass
                        except:
                            pass
                    else:
                        pass
                except:
                    pass
                    #print("    %s[%s] - %s%s - %sNo Response" %
                    #      (name, ip, alertdim))
            polling.append(item)
        # for loop


###################################################### Need to Clean this up ###################################################
# 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???? ##############
        ######################### OUTUT TEST RESULTS ###########################
        print("\n" + "Switch Passed Parameters")
        #print(name) ## Switch Office Outside Lights
        #print(ip)
        #print(item["id"])
        #print(item["key"])
        #print(data, item["name"])    ##print(data, item["name"]) ={ 'dps': {'20': True, '21': 'white', '22': 29, '23': 1000, '24': '00ad02a10318', '25': '000e0d0000000000000000c803e8', '26': 0}} Office Light
        #print(data['dps'], item["name"])   ##print(data['devices'], item["name"]) = {'20': True, '21': 'white', '22': 29, '23': 1000, '24': '00ad02a10318', '25': '000e0d0000000000000000c803e8', '26': 0} Office Light

        print("WHAT WE NEED TO PASS TO SWITCH CLASSES")
        print(
            name, ip, item["key"], item["id"]
        )  ##print(name, ip, item["key"], item["id"]) = Office Light 192.168.1.147 805217605357161b ebfc16d57ed374932cjqfk NOW TO MAKE THIS A SWITCH
        print("devId FULL PAYLOAD RAW")
        print(
            item["devId"]
        )  ##print(item["devId"]) = {'devId': '017743508caab5f0973e', 'dps': {'1': True, '9': 0}}
        print("\n" + "BOTH SWITCHES NOT PASSED?")
        ############## Function to start sort ################
        print("\n" + "Switch Status\n")
        if '1' in data['devId'] or 'devId' in data['devId']:
            print(item["name"], item["id"], item["ip"], item["key"])

        print("\n" + "Data Status \n")
        print(
            "Our Data" + "\n " + item["name"], data
        )  ## print("Our Data \n ",  item["name"], data) = ##print("Our Data \n ", data) = {'devId': '017743508caab5f0973e', 'dps': {'1': True, '9': 0}}
        print("")
        print("\nOur Devices" + "\n ", devices)

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

        # Test it
        turn_off('Switch Family Room Sconces'
                 )  #Switch Family Room Sconces #Switch Office Outside Lights
        time.sleep(2)
        turn_on('Switch Family Room Sconces'
                )  #Switch Family Room Sconces #Switch Office Outside Lights
        time.sleep(2)
        turn_off('Switch Office Outside Lights'
                 )  #Switch Family Room Sconces #Switch Office Outside Lights
        time.sleep(2)
        turn_on('Switch Office Outside Lights'
                )  #Switch Family Room Sconces #Switch Office Outside Lights

    print("\nDone.\n")
    return
def wizard(color=True):
    # Get Configuration Data
    #CONFIGFILE = 'tinytuya.json'
    #DEVICEFILE = #'devices.json'
    SNAPSHOTFILE = 'output'
    config = {}
    config['apiKey'] = "txejpdfda9iwmn5cg2es"
    config['apiSecret'] = "46d6072ffd724e0ba5ebeb5cc6b9dce9"
    config['apiRegion'] = 'us'
    config['apiDeviceID'] = "017743508caab5f0973e"
    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 = 'Y'  #input(subbold + '    Use existing credentials ' +
        #     normal + '(Y/n): ')
        if ('Y'[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 = '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']
        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 = 'Yes' #input(subbold + '\nPoll local devices? ' +
    #     normal + '(Y/n): ')
    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)
        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['devId'] = data
                        state = alertdim + "Off" + dim
                        try:
                            if '1' in data['devId'] or 'devId' in data['devId']:
                                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']))
                                pass
                        except:
                            #print("    %s[%s] - %s%s - %sNo Response" %
                            #      (subbold, name, dim, ip, alertdim))
                            pass
                    else:
                        #print("    %s[%s] - %s%s - %sNo Response" %
                        #      (subbold, name, dim, ip, alertdim))
                        pass
                except:
                    pass
                    #print("    %s[%s] - %s%s - %sNo Response" %
                    #      (subbold, name, dim, ip, alertdim))
            polling.append(item)
        # for loop
##################################### Need to remove unused else excepts above ########################$$$$$$$$$$$$$$$$$
# Save polling data snapsot
        current = {'timestamp': time.time(), 'devices': polling}
        output = json.dumps(current, indent=4)
        #print(name)

        #print(bold + "\n>> " + normal + "Saving device snapshot data to " + SNAPSHOTFILE)
        with open(SNAPSHOTFILE, "w") as outfile:
            outfile.write(output)
        #  pass
        #print(name)
        #print(ip)
        #print(id)
        #print(ver)
        #print(data)

######################### NOW INPUT SNAPSHOT FROM ABOVE INSTEAD OF PULLING FROM THE FILE $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
######################### So Far so Good creats json without writing it to an output file $$$$$$$$$$$$$$$$$$$$$$$$$$$$$
######################### Switch Poly will start here as a class $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#Class switchNode(self, SNAPSHOT PASSED ############)
######### PULLING FROM FILE ############
        with open(SNAPSHOTFILE) as json_file:  # 'snapshot.json'

            data = json.load(json_file)  # current gives error output
            # output


###################################### NODE SWITCH #########################################################
######################## SWITCH SEPERATE OUT THE SWITCHES THEY HAVE "devId" IN BETWEEN 'DPS' $$$$$$$$$$$$$$$
# Print a table with all devices
##print("%-25s %-24s %-16s %-17s %-5s" % ("Name","ID", "IP","Key","Version"))
##for item in data['devices']:
##    print("%-25.25s %-24s %-16s %-17s %-5s" % (
##        item["name"],
##        item["id"],
##        item["ip"],
##        item["key"],
##        item["ver"]))

# Print status of everything
##for item in data["devices"]:
##    print("\nDevice: %s" % item["name"])
##    d = tinytuya.OutletDevice(item["id"], item["ip"], item["key"])  #adding devId instead of just id
##    d.set_version(float(item["ver"]))
##    status = d.status()
##    print(status)
#print(["devId"])  #Seems to print switch only

# Turn on a device by name

        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)

            # Turn off a device by name
        def turn_off(name):
            # find the right item that matches name
            for item in data["devices"]:
                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)

        # Test it
        turn_off('Office Outside Lights')
        time.sleep(1)
        turn_on('Office Outside Lights')

    print("\nDone.\n")
    return
示例#9
0
    def wizard(self, color=True  ):
        config = {}
        config['apiKey'] = 'default_apiKey'  #'txejpdfda9iwmn5cg2es'
        config['apiSecret'] = 'default_apiSecret'   #'46d6072ffd724e0ba5ebeb5cc6b9dce9'
        config['apiRegion'] = 'us'
        config['apiDeviceID'] = 'default_apiDeviceId'  #'017743508caab5f0973e'
        needconfigs = True
        SLIPNAPSHOTFILE = 'slipnapshot.json'
        LOGGER.info('')
        LOGGER.info('TreatLife Device Discovery')  
        LOGGER.info('') 
        LOGGER.info('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 = '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))
    
        # Scans network for devices and provide polling data
        if('Y'[0:1].lower() != 'n'):
            ##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 '20' in data['dps'] or '20' in data['devId']: for Light Nodes and 
                            ### if '1' in data['dps'] or '1' in data['devId']: for Switch Nodes
                            ### if '1' in data['dps'] or '20' in data['dps'] or '20' in data['devId']: for all Nodes Lights & Switches
                            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!!!") ####### addNode 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)
        with open(SLIPNAPSHOTFILE, "w") as outfile:
            outfile.write(output) 
        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(self, command):  #color=True
        config = {}
        config['apiKey'] = "txejpdfda9iwmn5cg2es"
        config['apiSecret'] = "46d6072ffd724e0ba5ebeb5cc6b9dce9"
        config['apiRegion'] = 'us'
        config['apiDeviceID'] = "017743508caab5f0973e"
        needconfigs = True
        #SNAPSHOTFILE = 'snapshot.json'

        LOGGER.info('')
        LOGGER.info('TreatLife Device Discovery')
        LOGGER.info('')
        LOGGER.info('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 = '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']
        #LOGGER.info(response_dict)

        # 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)
        #LOGGER.info("Full json above", json_data)
        #LOGGER.info(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']
            tuyadevices.append(item)

        if ('Y'[0:1].lower() != 'n'):
            #### Scan network for devices and provide polling data ####
            #LOGGER.info("\nScanning local network for Tuya devices...\n")
            devices = tinytuya.deviceScan(False, 20)  #### changed 20 to 1

            def getIP(d, gwid):
                for ip in d:
                    if (gwid == d[ip]['gwId']):
                        return (ip, d[ip]['version'])
                return (0, 0)
        #### find devices

            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

        #### Poll for Devices device switches and lights ####
            polling = []
            LOGGER.info("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']:
                                    name = item["name"]
                                    LOGGER.info(name)
                                    id = item["id"]
                                    LOGGER.info(id)
                                    ip = item["ip"]
                                    LOGGER.info(ip)
                                    key = item["key"]
                                    LOGGER.info(key)
                                    ver = item["ver"]
                                    LOGGER.info(ver)
                                    pass
                                    result = '1' in data['dps']
                                    LOGGER.info(len(result))
                                    pass
                                    #### here i am trying to add the ID to increment up with the total amount of nodes ####
                                    #### need to automate the range to match node total
                                    #totalnum = len(name)
                                    #LOGGER.info(totalnum)
                                    #LOGGER.info("\nPolling TreatLife Switch Devices...\n")
                                    #for it in totalnum:
                                    #    item['address'] = 'switch_{}'.format(it)
                                    #    address = item['address']
                                    #    LOGGER.info(item['address'])
                                    #pass
                                    #### ADDNODE for switch here? ####
                                    #node = tuya_switch_node.SwitchNode(self.poly, self.address, address, name, id, ip, key, ver)
                                    #self.poly.addNode(node)
                                    #self.wait_for_node_done()

                                else:
                                    LOGGER.info(
                                        "\nPolling TreatLife LED Bulb Devices...\n"
                                    )
                                    if '20' in data['dps']:
                                        name = item["name"]
                                        LOGGER.info(name)
                                        id = item["id"]
                                        LOGGER.info(id)
                                        ip = item["ip"]
                                        LOGGER.info(ip)
                                        key = item["key"]
                                        LOGGER.info(key)
                                        ver = item["ver"]
                                        LOGGER.info(ver)
                                        pass
                                        totalnum = len(ver)
                                        LOGGER.info(totalnum)
                                        for it in range(
                                                1, int(totalnum)
                                        ):  #enumerate() '1' in data['dps'] for range
                                            item[
                                                'address'] = 'light_{}'.format(
                                                    it)
                                            address = item['address']
                                            LOGGER.info(item['address'])
                                        #### ADDNODE for light here ####
                                    pass
                            except:
                                pass
                        else:
                            pass
                    except:
                        pass

                polling.append(item)
                pass
示例#11
0
import os
from os import environ
from sys import exit

mqttserver = environ['MQTT_ADDR']
mqttport = int(environ['MQTT_PORT'])
mqtttopic = environ['MQTT_TOPIC']
updatesecs = int(environ['UPDATE_SECS'])

# mqttserver = "192.168.254.35"
# mqttport = 1883
# mqtttopic = "sensor/rectec"
# updatesecs = 5

print("Scanning for devices...")
devices = tinytuya.deviceScan()

print("Found %s devices." % len(devices))

global ip
if len(devices) > 0:
    print("Found %s devices. Using the first device found." % len(devices))
    ip = list(devices.keys())[0]
    print("IP: %s\n gwId: %s\n productKey: %s" %
          (ip, devices[ip]['gwId'], devices[ip]['productKey']))
else:
    exit(os.EX_SOFTWARE)

print("Using %s for the MQTT server IP" % mqttserver)

client = mqtt.Client()
示例#12
0
def find_switches():
    print(tiny.deviceScan())
示例#13
0
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 Light 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 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):
                #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 '20' in data['dps'] or '20' in data['devId']: for Light Nodes and
                            ### if '1' in data['dps'] or '1' in data['devId']: for Switch Nodes
                            ### if '1' in data['dps'] or '20' in data['dps'] or '20' in data['devId']: for all Nodes Lights & Switches
                            if '1' in data['dps'] or '20' in data[
                                    'dps'] or '20' 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 LIGHT 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"])
        DEVICENAME = 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 Light Switch by DEVICE Example #########################################

        # Check for environmental variables and always use those if available
        DEVICENAME = os.getenv("DEVICEID", DEVICEID)
        DEVICEID = os.getenv("DEVICEID", DEVICEID)
        DEVICEIP = os.getenv("DEVICEIP", DEVICEIP)
        DEVICEKEY = os.getenv("DEVICEKEY", DEVICEKEY)
        DEVICEVERS = os.getenv("DEVICEVERS", DEVICEVERS)

        if data["dps"] == '1':
            #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' %
                (DEVICENAME, 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"] != '1':  #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 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.BulbDevice(item["id"], item["ip"], item["key"])
        d.set_version(float(item["ver"]))
        d.set_socketPersistent(True)
        d.turn_off()
        # Show status of device
        #data = d.status()
        print('\nCurrent Status of Bulb: %r' % data)

        # 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.BulbDevice(item["id"], item["ip"], item["key"])
        d.set_version(float(item["ver"]))
        d.set_socketPersistent(True)
        d.turn_on()

        # Dimmer Test
        print('\nDimmer Control Test')
        for level in range(11):
            print('    Level: %d%%' % (level * 10))
            d.set_brightness_percentage(level * 10)
            time.sleep(1)

        # Colortemp Test
        print('\nColortemp Control Test (Warm to Cool)')
        for level in range(11):
            print('    Level: %d%%' % (level * 10))
            d.set_colourtemp_percentage(level * 10)
            time.sleep(1)

        # Flip through colors of rainbow - set_colour(r, g, b):
        print('\nColor Test - Cycle through rainbow')
        rainbow = {
            "red": [255, 0, 0],
            "orange": [255, 127, 0],
            "yellow": [255, 200, 0],
            "green": [0, 255, 0],
            "blue": [0, 0, 255],
            "indigo": [46, 43, 95],
            "violet": [139, 0, 255]
        }
        for x in range(2):
            for i in rainbow:
                r = rainbow[i][0]
                g = rainbow[i][1]
                b = rainbow[i][2]
                print('    %s (%d,%d,%d)' % (i, r, g, b))
                d.set_colour(r, g, b)
                time.sleep(2)
            print('')

        # Turn off
        d.turn_off()
        time.sleep(1)

        # Random Color Test
        d.turn_on()
        print('\nRandom Color Test')
        for x in range(10):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            print('    RGB (%d,%d,%d)' % (r, g, b))
            d.set_colour(r, g, b)
            time.sleep(2)

        # Test Modes
        print('\nTesting Bulb Modes')
        print('    White')
        d.set_mode('white')
        time.sleep(2)
        print('    Colour')
        d.set_mode('colour')
        time.sleep(2)
        print('    Scene')
        d.set_mode('scene')
        time.sleep(2)
        print('    Music')
        d.set_mode('music')
        time.sleep(2)

        d.set_mode(b)  #d.set_white()
        print('\nDimmer Control Test')
        for level in range(1):
            print('    Level: %d%%' % (level * 1))

    # Dimmer Test
        print('\nDimmer Control Test')
        for level in range(5):
            print('    Level: %d%%' % (level * 1))
            d.set_brightness_percentage(level * 1)
            time.sleep(1)

        # Power Control Test
        #print('\nPower Control Test')
        #print('    Turn off lamp')
        #d.turn_off()
        #time.sleep(2)
        #print('    Turn on lamp')
        #d.turn_on()
        #time.sleep(2)
        # Done
        print('\nDone wWith Light Color Test')

        # Who was passed
        print("\n" + item["name"])
        print(item["id"])
        print(item["ip"])
        print(item["key"] + "\n")

    print("\nDone.\n")
    return