clach04 / python-tuya

Python interface to ESP8266MOD WiFi smart devices from Shenzhen Xenon. NOTE I'm not using any devices with this library so I can't test :-(
MIT License
239 stars 55 forks source link

I created small python sample code for switching plugs on/off #35

Open zvainio opened 6 years ago

zvainio commented 6 years ago

I did not many good examples so I created something by myself. It reads plug data from json file and flips the switches state.

./p.py -d NeoWiFi01 -s on

{
    "devices": {
        "NeoWiFi01": {
            "uuid" : "06200632dc4f22XXXXXX",
            "key"  : "6ab4d393ddXXXXXX",
            "ip"   : "10.42.42.143"
        },
        "NeoWiFi02": {
            "uuid" : "06200632dc4f22XXXXXX",
            "key"  : "41aa63b644XXXXXX",
            "ip"   : "10.42.42.146"
        },
        "NeoWiFi03": {
            "uuid" : "06200632dc4f22XXXXXX",
            "key"  : "2c69263673XXXXXX",
            "ip"   : "10.42.42.145"
        }
    }
}

code:

#!/usr/bin/env python3

import pytuya
import sys
import getopt
import json

def main(argv):
    device = ''
    state = ''
    try:
        opts, args = getopt.getopt(argv,"hd:s:",["help", "device=", "state="])
    except getopt.GetoptError:
        print (sys.argv[0], '-d <device> -s <state>')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print (sys.argv[0], '-d <device> -s <state>')
            sys.exit()
        elif opt in ("-d", "--device"):
            device = arg
        elif opt in ("-s", "--state"):
            state = arg

    filename = "p.json"
    if filename:
        with open(filename, 'r') as f:
            datafile = json.load(f)

    print ('Device is', device)
    print ('State is', state)
    print (datafile["devices"][device]["uuid"])
    print (datafile["devices"][device]["key"])
    print (datafile["devices"][device]["ip"])

    d = pytuya.OutletDevice(datafile["devices"][device]["uuid"], datafile["devices"][device]["ip"], datafile["devices"][device]["key"])
    data = d.status()  # NOTE this does NOT require a valid key
    print('Dictionary %r' % data)
    print('state (bool, true is ON) %r' % data['dps']['1'])  # Show status of first controlled switch on device

    # Toggle switch state
    switch_state = data['dps']['1']
    data = d.set_status(not switch_state)  # This requires a valid key
    if data:
        print('set_status() result %r' % data)

    sys.exit(0)

if __name__ == "__main__":
   main(sys.argv[1:])

(edit clach04 to change formatting as Python code was missing indentation after markdown rendering)

zvainio commented 6 years ago

Plugs I'm using are NEO Coolcam WiFi which will cost about $10 First I created Tuya dev credentials and used tuya-cli link-wizard to get those needed keys to create my json config file.

clach04 commented 5 years ago

Neat! Thanks @zvainio.