Skip to content

Commit b6b4881

Browse files
committed
Merge branch 'bulb-rewrite' of https://github.com/uzlonewolf/tinytuya into pr/617
2 parents 78505b7 + 8d191d7 commit b6b4881

File tree

8 files changed

+92
-15
lines changed

8 files changed

+92
-15
lines changed

README.md

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ pipx install tinytuya
4242

4343
Pip will attempt to install `cryptography`, `requests` and `colorama` if not already installed.
4444

45+
### Alternate Install on Space- or Dependency-Limited Systems
46+
47+
On systems with limited space (such as an OpenWRT router), or if you would like to use a different cryptography library, you can install TinyTuya without automatic dependencies and manually install them yourself.
48+
49+
First, install a cryptography library. TinyTuya supports:
50+
* *cryptography* - Newest, requires OpenSSL - `python -m pip install cryptography`
51+
* *PyCryptodome* - Another good alternative, does not require OpenSSL, still actively developed - `python -m pip install pycryptodome` or `python -m pip install pycryptodomex`
52+
* *pyaes* - Pure Python, but is abandoned and does not support v3.5+ devices - `python -m pip install pyaes`
53+
* *PyCrypto* - Predecessor to PyCryptodome, is also abandoned and does not support v3.5+ devices - `python -m pip install pycrypto`
54+
55+
Optional: install `colorama` for terminal color support: `python -m pip install colorama`
56+
57+
Required for Wizard or Cloud functionality, Optional otherwise: install `requests` for Cloud functions to work: `python -m pip install requests`
58+
59+
Finally, install TinyTuya without dependencies: `python -m pip install --no-deps tinytuya`
60+
4561
## Tuya Device Preparation
4662

4763
Controlling and monitoring Tuya devices on your network requires the following:
@@ -90,7 +106,7 @@ TinyTuya has a built-in setup Wizard that uses the Tuya IoT Cloud Platform to ge
90106
```bash
91107
python -m tinytuya wizard # use -nocolor for non-ANSI-color terminals
92108
```
93-
* The **Wizard** will prompt you for the *API ID* key, API *Secret*, API *Region* (cn, us, us-e, eu, eu-w, or in) from your Tuya IoT project as set in Step 3 above.
109+
* The **Wizard** will prompt you for the *API ID* key, API *Secret*, API *Region* (cn, us, us-e, eu, eu-w, sg, or in) from your Tuya IoT project as set in Step 3 above.
94110
* To find those again, go to [iot.tuya.com](https://iot.tuya.com/), choose your project and click `Overview`
95111
* API Key: Access ID/Client ID
96112
* API Secret: Access Secret/Client Secret
@@ -459,7 +475,7 @@ tinytuya <command> [-debug] [-nocolor] [-h] [-yes] [-no-poll] [-device-file FILE
459475
Wizard
460476
tinytuya wizard [-h] [-debug] [-force [0.0.0.0/24 ...]] [-no-broadcasts] [-nocolor] [-yes] [-no-poll]
461477
[-device-file FILE] [-raw-response-file FILE] [-snapshot-file FILE] [-credentials-file FILE]
462-
[-key KEY] [-secret SECRET] [-region {cn,eu,eu-w,in,us,us-e}] [-device DEVICE [DEVICE ...]]
478+
[-key KEY] [-secret SECRET] [-region {cn,eu,eu-w,in,sg,us,us-e}] [-device DEVICE [DEVICE ...]]
463479
[-dry-run] [max_time]
464480
465481
Common Options
@@ -482,7 +498,7 @@ tinytuya <command> [-debug] [-nocolor] [-h] [-yes] [-no-poll] [-device-file FILE
482498
-credentials-file JSON file to load/save Cloud credentials from/to [Default: tinytuya.json]
483499
-key KEY Cloud API Key to use
484500
-secret SECRET Cloud API Secret to use
485-
-region Cloud API Region to use {cn,eu,eu-w,in,us,us-e}
501+
-region Cloud API Region to use {cn,eu,eu-w,in,sg,us,us-e}
486502
-device DEVICE(S) One or more Device ID(s) to use
487503
488504
Scan

RELEASE.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
* This update makes the colorama dependency optional for the tinytuya library, allowing it to function without colorama while gracefully disabling color output. This will help with memory lor dependency limited platforms. Update by @uzlonewolf in https://github.com/jasonacox/tinytuya/pull/637.
66

7+
## v1.17.2 - BulbDevice Fix
8+
9+
* Add Singapore datacenter, update BulbDevice for non-bulb devices again by @uzlonewolf in https://github.com/jasonacox/tinytuya/pull/625
10+
711
## v1.17.1 - Fix BulbDevice
812

913
* Fix BulbDevice for non-bulb devices. This will allow BulbDevice to be used even for non-bulb devices, e.g. turn_on() & turn_off(), by @uzlonewolf in https://github.com/jasonacox/tinytuya/pull/620.

server/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ ENV PYTHONUNBUFFERED=1
44
ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1
55
RUN pip install --no-cache-dir --upgrade pip setuptools wheel
66
RUN pip install --no-cache-dir cryptography pycryptodome
7-
RUN pip3 install --no-cache-dir netifaces tinytuya
7+
RUN pip install --no-cache-dir netifaces tinytuya psutil colorama requests
88
COPY . .
99
CMD ["python3", "server.py"]
1010
EXPOSE 8888

server/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ The UI at http://localhost:8888 allows you to view and control the devices.
113113
114114
## Release Notes
115115
116+
### p15 - Cross-Platform Memory Stats
117+
118+
* Switched to using the `psutil` library for memory usage stats, making server.py fully cross-platform (Windows, macOS, Linux). Fixes issue #634.
119+
* Memory usage is now reported on all platforms if `psutil` is installed; if not, the field is set to None.
120+
* Added requirements to documentation and header: `pip install psutil tinytuya colorama requests`.
121+
116122
### p14 - Recovery Logic
117123
118124
* Add main loop logic to try to recover when exception occurs.

server/server.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
Date: June 11, 2023
88
For more information see https://github.com/jasonacox/tinytuya
99
10+
Requirements:
11+
pip install psutil tinytuya colorama requests
12+
1013
Description
1114
Server continually listens for Tuya UDP discovery packets and updates the database of devices
1215
and uses devices.json to determine metadata about devices.
@@ -43,7 +46,14 @@
4346
print("WARN: Unable to import requests library, Cloud functions will not work.")
4447
print("WARN: Check dependencies. See https://github.com/jasonacox/tinytuya/issues/377")
4548
print("WARN: Error: {}.".format(impErr.args[0]))
46-
import resource
49+
50+
# Memory usage reporting uses the 'psutil' library, which is cross-platform.
51+
# If 'psutil' is not available, memory stats will be set to None.
52+
try:
53+
import psutil
54+
HAS_PSUTIL = True
55+
except ImportError:
56+
HAS_PSUTIL = False
4757
import signal
4858
import sys
4959
import os
@@ -62,7 +72,7 @@
6272
import tinytuya
6373
from tinytuya import scanner
6474

65-
BUILD = "p14"
75+
BUILD = "p15"
6676

6777
# Defaults from Environment
6878
APIPORT = int(os.getenv("APIPORT", "8888"))
@@ -426,7 +436,12 @@ def do_GET(self):
426436
elif self.path == '/stats':
427437
# Give Internal Stats
428438
serverstats['ts'] = int(time.time())
429-
serverstats['mem'] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
439+
# Report memory usage using psutil if available (cross-platform)
440+
if HAS_PSUTIL:
441+
process = psutil.Process(os.getpid())
442+
serverstats['mem'] = process.memory_info().rss // 1024 # Resident Set Size in KB
443+
else:
444+
serverstats['mem'] = None # psutil not available
430445
serverstats['cloudcreds'] = cloudcreds
431446
serverstats['cloudsync'] = cloudsync
432447
serverstats['cloudsyncdone'] = cloudsyncdone

tinytuya/core/core.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,14 @@
7979
from __future__ import print_function # python 2.7 support
8080
import logging
8181
import sys
82-
from colorama import init
82+
83+
try:
84+
from colorama import init
85+
HAVE_COLORAMA = True
86+
except ImportError:
87+
HAVE_COLORAMA = False
88+
89+
HAVE_COLOR = HAVE_COLORAMA or not sys.platform.startswith('win')
8390

8491
from .crypto_helper import AESCipher
8592

@@ -91,7 +98,8 @@
9198

9299

93100
# Colorama terminal color capability for all platforms
94-
init()
101+
if HAVE_COLORAMA:
102+
init()
95103

96104
version_tuple = (1, 17, 3) # Major, Minor, Patch
97105
version = __version__ = "%d.%d.%d" % version_tuple
@@ -124,6 +132,7 @@ def hex2bin(x):
124132

125133
def set_debug(toggle=True, color=True):
126134
"""Enable tinytuya verbose logging"""
135+
color = color and HAVE_COLOR
127136
if toggle:
128137
if color:
129138
logging.basicConfig(
@@ -197,6 +206,7 @@ def appenddevice(newdevice, devices):
197206

198207
# Terminal color helper
199208
def termcolor(color=True):
209+
color = color and HAVE_COLOR
200210
if color is False:
201211
# Disable Terminal Color Formatting
202212
bold = subbold = normal = dim = alert = alertdim = cyan = red = yellow = ""

tinytuya/scanner.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,16 @@
2525
import errno
2626
import base64
2727
import traceback
28-
from colorama import init
2928
import tinytuya
3029

30+
try:
31+
from colorama import init
32+
HAVE_COLORAMA = True
33+
except ImportError:
34+
HAVE_COLORAMA = False
35+
36+
HAVE_COLOR = HAVE_COLORAMA or not sys.platform.startswith('win')
37+
3138
# Optional libraries required for forced scanning
3239
#try:
3340
# from getmac import get_mac_address
@@ -54,7 +61,8 @@
5461
PSULIBS = False
5562

5663
# Colorama terminal color capability for all platforms
57-
init()
64+
if HAVE_COLORAMA:
65+
init()
5866

5967
# Configuration Files
6068
DEVICEFILE = tinytuya.DEVICEFILE
@@ -205,6 +213,10 @@ def get_ip_to_broadcast():
205213
def send_discovery_request( iface_list=None ):
206214
close_sockets = False
207215

216+
if not tinytuya.AESCipher.CRYPTOLIB_HAS_GCM:
217+
# GCM is required for discovery requests
218+
return False
219+
208220
if not iface_list:
209221
close_sockets = True
210222
iface_list = {}
@@ -1146,6 +1158,7 @@ def devices(verbose=False, scantime=None, color=True, poll=True, forcescan=False
11461158
11471159
"""
11481160
# Terminal formatting
1161+
color = color and HAVE_COLOR
11491162
termcolors = tinytuya.termcolor(color)
11501163
#(bold, subbold, normal, dim, alert, alertdim, cyan, red, yellow) = termcolors
11511164
term = TermColors( *termcolors )
@@ -1920,6 +1933,7 @@ def snapshot(color=True, assume_yes=False, skip_poll=None):
19201933
skip_poll = True or False, auto-answer 'no' to "Poll local devices?" (overrides assume_yes)
19211934
"""
19221935
# Terminal formatting
1936+
color = color and HAVE_COLOR
19231937
termcolors = tinytuya.termcolor(color)
19241938
term = TermColors( *termcolors )
19251939

@@ -1992,6 +2006,7 @@ def alldevices(color=True, scantime=None, forcescan=False, discover=True, assume
19922006
color = True or False, print output in color [Default: True]
19932007
"""
19942008
# Terminal formatting
2009+
color = color and HAVE_COLOR
19952010
#(bold, subbold, normal, dim, alert, alertdim, cyan, red, yellow) = tinytuya.termcolor(color)
19962011
termcolors = tinytuya.termcolor(color)
19972012
term = TermColors( *termcolors )
@@ -2031,6 +2046,7 @@ def alldevices(color=True, scantime=None, forcescan=False, discover=True, assume
20312046
return
20322047

20332048
def poll_and_display( tuyadevices, color=True, scantime=None, snapshot=False, forcescan=False, discover=True ): # pylint: disable=W0621
2049+
color = color and HAVE_COLOR
20342050
termcolors = tinytuya.termcolor(color)
20352051
term = TermColors( *termcolors )
20362052

tinytuya/wizard.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,17 @@
2424
# Modules
2525
from __future__ import print_function
2626
import json
27-
from colorama import init
2827
from datetime import datetime
2928
import tinytuya
29+
import sys
30+
31+
try:
32+
from colorama import init
33+
HAVE_COLORAMA = True
34+
except ImportError:
35+
HAVE_COLORAMA = False
36+
37+
HAVE_COLOR = HAVE_COLORAMA or not sys.platform.startswith('win')
3038

3139
# Backward compatibility for python2
3240
try:
@@ -35,7 +43,8 @@
3543
pass
3644

3745
# Colorama terminal color capability for all platforms
38-
init()
46+
if HAVE_COLORAMA:
47+
init()
3948

4049
# Configuration Files
4150
DEVICEFILE = tinytuya.DEVICEFILE
@@ -114,6 +123,7 @@ def wizard(color=True, retries=None, forcescan=False, nocloud=False, assume_yes=
114123
except:
115124
old_devices = {}
116125

126+
color = color and HAVE_COLOR
117127
(bold, subbold, normal, dim, alert, alertdim, cyan, red, yellow) = tinytuya.termcolor(color)
118128

119129
print(bold + 'TinyTuya Setup Wizard' + dim + ' [%s]' % (tinytuya.version) + normal)
@@ -150,8 +160,8 @@ def wizard(color=True, retries=None, forcescan=False, nocloud=False, assume_yes=
150160
"\n us-e\tUS - Eastern America Data Center (alias: UE)" +
151161
"\n eu\tCentral Europe Data Center" +
152162
"\n eu-w\tWestern Europe Data Center (alias: WE)" +
153-
"\n in\tIndia Data Center\n" +
154-
"\n sg\tSingapore Data Center")
163+
"\n in\tIndia Data Center" +
164+
"\n sg\tSingapore Data Center\n")
155165
config['apiRegion'] = input(subbold + " Enter " + bold + "Your Region" + subbold +
156166
" (Options: cn, us, us-e, eu, eu-w, in, or sg): " + normal)
157167
# Write Config

0 commit comments

Comments
 (0)