Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use {DeviceName} instead of {DeviceID} alternatively for API commands #352

Merged
merged 3 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,24 @@ The TinyTuya API Server provides a central service to access all your Tuya devic
API Functions - The server listens for GET requests on local port 8888:

```
/help - List all available commands
/devices - List all devices discovered with metadata
/device/{DeviceID} - List specific device metadata
/numdevices - List current number of devices discovered
/status/{DeviceID} - List current device status
/set/{DeviceID}/{Key}/{Value} - Set DPS {Key} with {Value}
/turnon/{DeviceID}/{SwitchNo} - Turn on device, optional {SwtichNo}
/turnoff/{DeviceID}/{SwitchNo} - Turn off device, optional {SwtichNo}
/delayedoff/{DeviceID}/{SwitchNo}/{Seconds} - Turn off device with a delay, optional {SwitchNo}/{Delay}
/sync - Fetches the device list and local keys from the Tuya Cloud API
/help - List all available commands
/devices - List all devices discovered with metadata
/device/{DeviceID}|{DeviceName} - List specific device metadata
/numdevices - List current number of devices discovered
/status/{DeviceID}|{DeviceName} - List current device status
/set/{DeviceID}|{DeviceName}/{Key}/{Value} - Set DPS {Key} with {Value}
/turnon/{DeviceID}/{SwitchNo} - Turn on device, optional {SwtichNo}
/turnoff/{DeviceID}/{SwitchNo} - Turn off device, optional {SwtichNo}
/delayedoff/{DeviceID}|{DeviceName}/{SwitchNo}/{Seconds}
- Turn off device with a delay, optional {SwitchNo}/{Delay}
/sync - Fetches the device list and local keys from the Tuya Cloud API
/cloudconfig/{apiKey}/{apiSecret}/{apiRegion}/{apiDeviceID}
- Sets the Tuya Cloud API login info
/offline - List of registered devices that are offline
- Sets the Tuya Cloud API login info
/offline - List of registered devices that are offline
```

Note! If oyu use {DeviceName} instead of {DeviceID}, make sure your Device Names are absolutely unique! Otherwise you will get funny results.

## Quick Start

This folder contains the `server.py` script that runs a simple python based webserver that makes the TinyTuya API calls. Make sure the `device.json` file is the same directory where you start the server.
Expand Down
43 changes: 37 additions & 6 deletions server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer
from socketserver import ThreadingMixIn
import urllib.parse

# Required module: pycryptodome
try:
Expand Down Expand Up @@ -349,13 +350,13 @@ def do_GET(self):
elif self.path == '/help':
# show available commands
cmds = [("/devices","List all devices discovered with metadata"),
("/device/{DeviceID}", "List specific device metadata"),
("/device/{DeviceID}|{DeviceName}", "List specific device metadata"),
("/numdevices", "List current number of devices discovered"),
("/status/{DeviceID}", "List current device status"),
("/set/{DeviceID}/{Key}/{Value}", "Set DPS {Key} with {Value}"),
("/turnon/{DeviceID}/{SwitchNo}", "Turn on device, optional {SwtichNo}"),
("/turnoff/{DeviceID}/{SwitchNo}", "Turn off device, optional {SwtichNo}"),
("/delayoff/{DeviceID}/{SwitchNo}/{Time}", "Turn off device with delay of 10 secs, optional {SwitchNo}/{Time}"),
("/status/{DeviceID}|{DeviceName}", "List current device status"),
("/set/{DeviceID}|{DeviceName}/{Key}/{Value}", "Set DPS {Key} with {Value}"),
("/turnon/{DeviceID}|{DeviceName}/{SwitchNo}", "Turn on device, optional {SwtichNo}"),
("/turnoff/{DeviceID}|{DeviceName}/{SwitchNo}", "Turn off device, optional {SwtichNo}"),
("/delayoff/{DeviceID}|{DeviceName}/{SwitchNo}/{Time}", "Turn off device with delay of 10 secs, optional {SwitchNo}/{Time}"),
("/sync", "Fetches the device list and local keys from the Tuya Cloud API"),
("/cloudconfig/{apiKey}/{apiSecret}/{apiRegion}/{apiDeviceID}", "Sets the Tuya Cloud API login info"),
("/offline", "List of registered devices that are offline")]
Expand Down Expand Up @@ -384,6 +385,11 @@ def do_GET(self):
except:
message = json.dumps({"Error": "Syntax error in set command URL.", "url": self.path})
log.debug("Syntax error in set command URL: %s" % self.path)
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor note: Since we are repeating this same logic 6 times, should we consider making this a function?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, of course. I was unsure to put it into a function... I will change it accordingly.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would also pull the urllib.parse.unquote(id) out of the loop and move it to a variable beforehand instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I included both suggestions: getDeviceIdByName as a function and pull urllib.parse.unquote(id) out of the loop.

if(id in deviceslist):
d = tinytuya.OutletDevice(id, deviceslist[id]["ip"], deviceslist[id]["key"])
d.set_version(float(deviceslist[id]["version"]))
Expand All @@ -394,6 +400,11 @@ def do_GET(self):
log.debug("Device ID not found: %s" % id)
elif self.path.startswith('/device/'):
id = self.path.split('/device/')[1]
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
if(id in deviceslist):
message = json.dumps(deviceslist[id])
else:
Expand All @@ -418,6 +429,11 @@ def do_GET(self):
id = ""
message = json.dumps({"Error": "Invalid syntax in turnoff command.", "url": self.path})
log.debug("Syntax error in in turnoff command: %s" % self.path)
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
if id in deviceslist:
try:
d = tinytuya.OutletDevice(id, deviceslist[id]["ip"], deviceslist[id]["key"])
Expand All @@ -441,6 +457,11 @@ def do_GET(self):
id = ""
message = json.dumps({"Error": "Invalid syntax in delayoff command.", "url": self.path})
log.debug("Syntax error in in delayoff command: %s" % self.path)
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
if id in deviceslist:
try:
d = tinytuya.OutletDevice(id, deviceslist[id]["ip"], deviceslist[id]["key"])
Expand All @@ -466,6 +487,11 @@ def do_GET(self):
id = ""
message = json.dumps({"Error": "Invalid syntax in turnon command.", "url": self.path})
log.debug("Syntax error in turnon command URL: %s" % self.path)
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
if id in deviceslist:
try:
d = tinytuya.OutletDevice(id, deviceslist[id]["ip"], deviceslist[id]["key"])
Expand All @@ -485,6 +511,11 @@ def do_GET(self):
message = json.dumps(jout)
elif self.path.startswith('/status/'):
id = self.path.split('/status/')[1]
if(id not in deviceslist):
for key in deviceslist:
if deviceslist[key]['name'] == urllib.parse.unquote(id):
id = deviceslist[key]['id']
break
if(id in deviceslist):
try:
d = tinytuya.OutletDevice(id, deviceslist[id]["ip"], deviceslist[id]["key"])
Expand Down