Skip to content

Commit e9a23af

Browse files
committed
Enhance device command handling by improving value parsing and error handling for version retrieval
1 parent 08ac887 commit e9a23af

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

tinytuya/__main__.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@
120120
subparsers[sp].add_argument('--dps', help='DPS index', required=True, type=int, metavar='N')
121121

122122
if sp == 'set':
123-
subparsers[sp].add_argument('--value', help='Value to set (always sent as a string; device handles coercion)', required=True, metavar='VALUE')
123+
subparsers[sp].add_argument('--value', help='Value to set. Parsed as JSON if possible (e.g. true, 123, "text"), otherwise sent as a plain string.', required=True, metavar='VALUE')
124124

125125
if HAVE_ARGCOMPLETE:
126126
argcomplete.autocomplete( parser )
@@ -231,7 +231,21 @@ def _run_device_command(args):
231231
dev_ip = devinfo.get('last_ip') or devinfo.get('ip') or None
232232
if dev_version is None:
233233
raw_ver = devinfo.get('version')
234-
dev_version = float(raw_ver) if raw_ver else None
234+
if raw_ver:
235+
try:
236+
dev_version = float(raw_ver)
237+
except (TypeError, ValueError):
238+
print(
239+
'Warning: invalid "version" value (%r) for device %s in %s; '
240+
'using default protocol version.' % (
241+
raw_ver,
242+
devinfo.get('id') or devinfo.get('name') or '<unknown>',
243+
device_file,
244+
)
245+
)
246+
dev_version = None
247+
else:
248+
dev_version = None
235249

236250
# Validate
237251
if not dev_id:
@@ -264,7 +278,13 @@ def _run_device_command(args):
264278
elif args.command == 'off':
265279
result = d.turn_off(switch=args.dps)
266280
elif args.command == 'set':
267-
result = d.set_value(args.dps, args.value)
281+
# Attempt to parse the value as JSON so that "true", "123", etc.
282+
# are sent with the correct type; fall back to a plain string.
283+
try:
284+
typed_value = json.loads(args.value)
285+
except (ValueError, TypeError):
286+
typed_value = args.value
287+
result = d.set_value(args.dps, typed_value)
268288
elif args.command == 'get':
269289
result = d.status()
270290
if result and 'Err' not in result:
@@ -275,7 +295,7 @@ def _run_device_command(args):
275295
dps_str = str(args.dps)
276296
if 'dps' in result and dps_str in result['dps']:
277297
# --dps given: print the plain value only
278-
print(result['dps'][dps_str])
298+
print(json.dumps(result['dps'][dps_str]))
279299
return
280300
else:
281301
available = list(result.get('dps', {}).keys())

0 commit comments

Comments
 (0)