Files
yolocam-linux/yolocam-ctl/yolocam_ctl/cli.py
T
2026-02-15 12:50:49 -08:00

778 lines
26 KiB
Python

# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
yolocam-ctl - Linux CLI for controlling YoloCam S3 camera parameters
Communicates with the camera over its CDC NCM USB network interface using the
reverse-engineered Yunxi protobuf protocol (TCP port 12345).
Protocol discovered by reverse engineering SocketPacketPolicy::pack() in ycc.dylib.
Wire format (SocketPacketPolicy dual-envelope):
OUTER (8 bytes): [0x08] [client_type] [0x00] [0x00] [LE32 inner_size]
INNER (6 bytes): [0xA5] [BE32 proto_size] [XOR header_checksum]
PAYLOAD (N bytes): [serialized protobuf]
TRAILER (2 bytes): [XOR data_checksum] [0x5A]
client_type: 0x01 for client, 0x00 for camera responses
inner_size: proto_size + 8 (inner header + checksums + trailer)
"""
import argparse
import json
import socket
import subprocess
import sys
import textwrap
import time
from yolocam.client import YoloCamClient
from yolocam.params import (
PARAMS, PARAM_CATEGORIES,
ISO_VALUES, SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
ZOOM_MULT_MIN, ZOOM_MULT_MAX,
zoom_raw_to_mult, zoom_mult_to_raw, find_nearest_aperture,
is_readable, is_writable,
)
from yolocam.protocol import CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT
from yolocam import yolocam_pb2 as pb
def format_response(resp, param_name=None):
"""Format a protobuf response message for CLI display.
Returns a dict suitable for JSON output or human-readable formatting.
"""
if resp is None:
return "No response from camera"
result = {}
result["resp_code"] = resp.resp_code
result["command"] = pb.CommandId.Name(resp.id) if resp.id else "NONE"
if resp.HasField("body"):
body = resp.body
which = body.WhichOneof("value")
if which == "int_val":
val = body.int_val
result["value"] = val
if param_name == "zoom":
result["zoom_mult"] = zoom_raw_to_mult(val)
elif param_name == "exposure-iso" and val in ISO_VALUES:
result["iso"] = val
elif param_name == "exposure-time" and val in SHUTTER_REVERSE:
result["shutter_speed"] = f"1/{SHUTTER_REVERSE[val]}"
elif param_name == "exposure-aperture" and val in APERTURE_TABLE:
result["aperture"] = APERTURE_TABLE[val]
elif which == "str_val":
result["value"] = body.str_val
elif which == "version_info":
vi = body.version_info
result["sys_version"] = vi.sys_version
result["unique_id"] = vi.unique_id
result["serial_num"] = vi.serial_num
result["sys_code"] = vi.sys_code
elif which == "exposure_params":
ep = body.exposure_params
result["iso"] = ep.iso
result["shutter_us"] = ep.shutter
if ep.shutter in SHUTTER_REVERSE:
result["shutter_speed"] = f"1/{SHUTTER_REVERSE[ep.shutter]}"
result["aperture_index"] = ep.aperture
if ep.aperture in APERTURE_TABLE:
result["aperture"] = APERTURE_TABLE[ep.aperture]
elif which == "white_balance_manual":
wb = body.white_balance_manual
result["saturation"] = wb.saturation
result["chroma"] = wb.chroma
elif which == "white_balance_offset":
wbo = body.white_balance_offset
result["red_offset"] = wbo.offset_r
result["blue_offset"] = wbo.offset_b
elif which == "lens_detail":
ld = body.lens_detail
result["lens_id"] = ld.lens_id
result["aperture"] = ld.aperture
result["focal"] = ld.focal
result["detected"] = ld.detected
result["serial"] = ld.serino
elif which == "stream_param":
sp = body.stream_param
if sp.HasField("venc_param"):
v = sp.venc_param
result["video"] = {
"codec": v.codec, "width": v.width, "height": v.height,
"bitrate": v.bitrate, "fps": v.rate, "profile": v.profile,
}
if sp.HasField("aenc_param"):
a = sp.aenc_param
result["audio"] = {
"codec": a.codec, "channels": a.channels,
"sample_rate": a.sample_rate, "bitrate": a.bitrate,
}
elif which == "video_status":
result["video_status"] = body.video_status.status
elif which == "range":
result["min"] = body.range.min
result["max"] = body.range.max
elif which == "disk_info":
di = body.disk_info
result["total_size"] = di.total_size
result["available_size"] = di.available_size
result["fs_type"] = di.fs_type
result["smb_path"] = di.smb_path
elif which == "lens_version_info":
lvi = body.lens_version_info
result["current_version"] = lvi.current_version
result["latest_version"] = lvi.latest_version
elif which is not None:
result["body_type"] = which
result["raw"] = str(getattr(body, which))
return result
def ensure_network_interface():
"""Ensure the CDC NCM interface to the camera is up and configured."""
try:
result = subprocess.run(
["ip", "route", "get", CAMERA_IP],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0 and CAMERA_IP in result.stdout:
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Find the CDC NCM interface (usb0 or similar)
try:
result = subprocess.run(
["ip", "-o", "link", "show"],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.splitlines():
parts = line.split(":")
if len(parts) >= 2:
iface = parts[1].strip()
if iface in ("lo", "wlo1") or iface.startswith(("enp", "vmnet", "br-", "docker", "veth")):
continue
if "usb" in iface.lower() or iface.startswith("enx"):
subprocess.run(
["sudo", "ip", "link", "set", iface, "up"],
capture_output=True, timeout=5
)
subprocess.run(
["sudo", "ip", "addr", "add", "192.168.126.11/24",
"dev", iface],
capture_output=True, timeout=5
)
time.sleep(1)
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return False
def check_camera_reachable():
"""Quick TCP connect test to see if the camera control port is reachable."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect((CAMERA_IP, CAMERA_PORT))
s.close()
return True
except (socket.timeout, socket.error, OSError):
return False
def cmd_get(args):
"""Get one or more camera parameters over a single connection."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
for param_name in args.params:
pdef = PARAMS.get(param_name)
if pdef is None:
print(f"Unknown parameter: {param_name}", file=sys.stderr)
print(f"Use 'yolocam-ctl list' to see available parameters", file=sys.stderr)
continue
if not is_readable(pdef):
print(f"{param_name}: (set-only, use 'set' command)")
continue
try:
resp = client.request(pdef.cid, recv_timeout=3.0)
result = format_response(resp, param_name)
except socket.timeout:
print(f"{param_name}: (no response)")
continue
if args.json:
result["parameter"] = param_name
print(json.dumps(result, indent=2))
else:
if "value" in result:
if "zoom_mult" in result:
print(f"{param_name}: {result['zoom_mult']:.1f}x")
elif "iso" in result and param_name == "exposure-iso":
print(f"{param_name}: {result['value']} (ISO {result['iso']})")
elif "shutter_speed" in result and param_name == "exposure-time":
print(f"{param_name}: {result['value']} ({result['shutter_speed']}s)")
elif "aperture" in result and param_name == "exposure-aperture":
print(f"{param_name}: {result['value']} ({result['aperture']})")
else:
print(f"{param_name}: {result['value']}")
elif "sys_version" in result:
print(f"Firmware: {result['sys_version']}")
print(f"Serial: {result['serial_num']}")
print(f"ID: {result['unique_id']}")
else:
print(f"{param_name}: {json.dumps(result, indent=2)}")
finally:
client.close()
def cmd_set(args):
"""Set a camera parameter."""
param_name = args.param
pdef = PARAMS.get(param_name)
if pdef is None:
print(f"Unknown parameter: {param_name}", file=sys.stderr)
sys.exit(1)
if not is_writable(pdef):
print(f"Parameter '{param_name}' is read-only", file=sys.stderr)
sys.exit(1)
if pdef.control_type == "zoom":
mult = float(args.value)
if mult < ZOOM_MULT_MIN or mult > ZOOM_MULT_MAX:
print(
f"Zoom {mult:.1f}x is out of range. Valid range is {ZOOM_MULT_MIN:.1f}x to {ZOOM_MULT_MAX:.1f}x.",
file=sys.stderr,
)
sys.exit(1)
value = zoom_mult_to_raw(mult)
else:
value = int(args.value)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pdef.cid, value)
result = format_response(resp, param_name)
if args.json:
result["parameter"] = param_name
result["set_value"] = value
print(json.dumps(result, indent=2))
else:
rc = result.get("resp_code", -1)
if rc == 200:
if pdef.control_type == "zoom":
print(f"{param_name} = {zoom_raw_to_mult(value):.1f}x (OK)")
else:
print(f"{param_name} = {value} (OK)")
else:
print(f"{param_name} = {value} (resp_code={rc})")
finally:
client.close()
def cmd_set_iso(args):
"""Set ISO by actual value (100, 200, 400, etc.)."""
iso_val = int(args.value)
if iso_val not in ISO_VALUES:
print(f"Invalid ISO value: {iso_val}", file=sys.stderr)
print(f"Valid values: {ISO_VALUES}", file=sys.stderr)
sys.exit(1)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_ISO, iso_val)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"ISO {iso_val} {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_shutter(args):
"""Set shutter speed by denominator (e.g., 1000 for 1/1000s)."""
speed = int(args.value)
if speed not in SHUTTER_TABLE:
print(f"Invalid shutter speed: 1/{speed}", file=sys.stderr)
valid = sorted(SHUTTER_TABLE.keys(), reverse=True)
print(f"Valid values: {['1/' + str(v) for v in valid]}", file=sys.stderr)
sys.exit(1)
us = SHUTTER_TABLE[speed]
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_TIME, us)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"Shutter 1/{speed}s ({us}us) {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_wb_temp(args):
"""Set white balance temperature in Kelvin."""
temp = int(args.value)
if temp < 2000 or temp > 10000:
print(f"Temperature should be 2000-10000K, got {temp}", file=sys.stderr)
sys.exit(1)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_WHITE_BALANCE_TEMPERATURE, temp)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"White balance {temp}K {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_aperture(args):
"""Set aperture by f-stop value (e.g., 2.8 for F2.8)."""
target = args.value.upper().lstrip("F")
try:
target_f = float(target)
except ValueError:
print(f"Invalid aperture: {args.value}", file=sys.stderr)
sys.exit(1)
best_idx = find_nearest_aperture(target_f)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_APERTURE, best_idx)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"Aperture {APERTURE_TABLE[best_idx]} (index {best_idx}) "
f"{'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_list(args):
"""List all available parameters."""
if args.json:
out = {}
for name, pdef in PARAMS.items():
out[name] = {"id": pdef.cid, "description": pdef.description, "type": pdef.control_type}
print(json.dumps(out, indent=2))
return
for category, names in PARAM_CATEGORIES.items():
print(f"\n {category}")
print(f" {'─' * len(category)}")
for name in names:
pdef = PARAMS.get(name)
if pdef is None:
continue
if not is_readable(pdef):
rw = "WO"
elif not is_writable(pdef):
rw = "RO"
else:
rw = "RW"
print(f" {name:<22} [{rw}] {pdef.description}")
def cmd_get_all(args):
"""Get all readable parameters, reconnecting as needed."""
results = {}
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
consecutive_timeouts = 0
try:
for name, pdef in PARAMS.items():
if not is_readable(pdef):
continue
try:
resp = client.request(pdef.cid, recv_timeout=3.0)
result = format_response(resp, name)
results[name] = result
consecutive_timeouts = 0
except socket.timeout:
results[name] = {"error": "no response"}
consecutive_timeouts += 1
if consecutive_timeouts >= 2:
try:
client.close()
except Exception:
pass
time.sleep(0.5)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
consecutive_timeouts = 0
except Exception as e:
results[name] = {"error": str(e)}
time.sleep(0.1)
finally:
client.close()
if args.json:
print(json.dumps(results, indent=2))
else:
for name, result in results.items():
rc = result.get("resp_code", -1)
if "error" in result:
print(f"{name}: ({result['error']})")
elif rc == 100:
print(f"{name}: (unsupported)")
elif "zoom_mult" in result:
print(f"{name}: {result['zoom_mult']:.1f}x")
elif "value" in result:
print(f"{name}: {result['value']}")
elif "sys_version" in result:
print(f"{name}: {result.get('sys_version', 'N/A')}")
else:
print(f"{name}: {result}")
def cmd_init(args):
"""Initialize camera connection following the Windows app sequence."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
print(f"Connected to {args.ip}:{args.port}")
print("Sending heartbeat...")
client.set_int(pb.CID_STREAM_HEARTBEAT, 1)
print("Checking camera status...")
resp = client.request(pb.CID_LOWPOWER_STATUS)
result = format_response(resp)
print(f" Low power status: {result.get('value', result)}")
print("Querying device info...")
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
if "sys_version" in result:
print(f" Firmware: {result['sys_version']}")
print(f" Serial: {result['serial_num']}")
print(f" ID: {result['unique_id']}")
init_params = [
(pb.CID_FRAME_RATE, "Frame rate"),
(pb.CID_RANGE_OF_APERTURE, "Aperture range"),
(pb.CID_LENS_STATUS, "Lens status"),
(pb.CID_USB_VERSION, "USB version"),
(pb.CID_HDMI_OUTPUT_FORMAT, "HDMI format"),
]
print("Querying camera parameters...")
for cid, name in init_params:
try:
resp = client.request(cid)
result = format_response(resp)
val = result.get("value", result.get("min", result))
print(f" {name}: {val}")
except Exception as e:
print(f" {name}: error ({e})")
print("Camera initialized successfully")
finally:
client.close()
def cmd_raw(args):
"""Send a raw command by numeric ID."""
cid = int(args.command_id)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
if args.value is not None:
resp = client.set_int(cid, int(args.value))
else:
resp = client.request(cid)
result = format_response(resp)
print(json.dumps(result, indent=2))
finally:
client.close()
def cmd_probe(args):
"""Probe the camera TCP port and verify protocol connectivity."""
print(f"Probing camera at {args.ip}:{args.port}...")
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
print(f"Protocol OK (resp_code={result.get('resp_code', 'N/A')})")
if "sys_version" in result:
print(f" Firmware: {result['sys_version']}")
print(f" Serial: {result['serial_num']}")
except Exception as e:
print(f"Probe failed: {e}")
finally:
client.close()
def cmd_monitor(args):
"""Monitor camera notifications in real-time."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
print(f"Connected to camera at {args.ip}:{args.port}")
# Send initial heartbeat (background thread already started by connect())
client.set_int(pb.CID_STREAM_HEARTBEAT, 1)
print("Monitoring notifications (Ctrl+C to stop)...")
print()
try:
client._sock.settimeout(None)
while True:
try:
resp = client._recv_one_message()
if resp:
ts = time.strftime("%H:%M:%S")
cmd_name = pb.CommandId.Name(resp.id) if resp.id else "NONE"
type_name = pb.MessageType.Name(resp.type)
result = format_response(resp)
print(f"[{ts}] {type_name} {cmd_name}: {json.dumps(result)}")
except Exception as e:
print(f"Error: {e}")
break
except KeyboardInterrupt:
print("\nStopped.")
finally:
client.close()
def cmd_status(args):
"""Show camera connection status and basic info."""
print("YoloCam S3 Status")
print("─" * 40)
try:
result = subprocess.run(
["lsusb"], capture_output=True, text=True, timeout=5
)
found = any("46f8:0855" in line for line in result.stdout.splitlines())
print(f"USB Device: {'Connected' if found else 'Not found'}")
except Exception:
print("USB Device: Unknown (lsusb failed)")
net_ok = ensure_network_interface()
print(f"Network: {'Interface configured' if net_ok else 'No interface'}")
tcp_ok = check_camera_reachable()
print(f"Control Port: {'Reachable' if tcp_ok else 'Not reachable'} ({CAMERA_IP}:{CAMERA_PORT})")
if tcp_ok:
try:
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
client.close()
if "sys_version" in result:
print(f"Firmware: {result['sys_version']}")
print(f"Serial: {result['serial_num']}")
print(f"ID: {result['unique_id']}")
except Exception as e:
print(f"Info: Failed to query ({e})")
def main():
parser = argparse.ArgumentParser(
prog="yolocam-ctl",
description="Control YoloCam S3 camera parameters on Linux",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent("""\
Examples:
yolocam-ctl status Show camera connection status
yolocam-ctl list List all available parameters
yolocam-ctl get brightness contrast Get current values
yolocam-ctl get-all Get all parameters
yolocam-ctl set brightness 50 Set brightness to 50
yolocam-ctl set exposure-mode 1 Switch to manual exposure
yolocam-ctl iso 400 Set ISO to 400
yolocam-ctl shutter 1000 Set shutter to 1/1000s (1000us)
yolocam-ctl wb-temp 5500 Set white balance to 5500K
yolocam-ctl aperture 2.8 Set aperture to F2.8
yolocam-ctl set zoom 2.0 Set 2.0x digital zoom
yolocam-ctl set hdr 1 Enable HDR
yolocam-ctl set focus-mode 3 Switch to continuous AF
yolocam-ctl init Full camera initialization
yolocam-ctl monitor Watch real-time notifications
yolocam-ctl raw 7 Query raw command ID 7
yolocam-ctl raw 7 50 Set raw command ID 7 to 50
"""),
)
parser.add_argument("--ip", default=CAMERA_IP, help=f"Camera IP (default: {CAMERA_IP})")
parser.add_argument("--port", type=int, default=CAMERA_PORT, help=f"Camera port (default: {CAMERA_PORT})")
parser.add_argument(
"--timeout", type=float, default=DEFAULT_TIMEOUT, help=f"Socket timeout (default: {DEFAULT_TIMEOUT}s)"
)
parser.add_argument("--json", action="store_true", help="Output in JSON format")
sub = parser.add_subparsers(dest="command", help="Command to execute")
sub.add_parser("status", help="Show camera connection status and info")
sub.add_parser("list", help="List all available parameters")
sub.add_parser("init", help="Initialize camera (mimics Windows app startup)")
p_get = sub.add_parser("get", help="Get camera parameter(s)")
p_get.add_argument("params", nargs="+", help="Parameter name(s)")
sub.add_parser("get-all", help="Get all camera parameters")
p_set = sub.add_parser("set", help="Set a camera parameter")
p_set.add_argument("param", help="Parameter name")
p_set.add_argument("value", help="Value to set")
p_iso = sub.add_parser("iso", help="Set ISO by value (100, 200, 400, ...)")
p_iso.add_argument("value", help="ISO value")
p_shutter = sub.add_parser("shutter", help="Set shutter speed (denominator, e.g., 1000 for 1/1000s)")
p_shutter.add_argument("value", help="Shutter speed denominator")
p_wb = sub.add_parser("wb-temp", help="Set white balance temperature in Kelvin")
p_wb.add_argument("value", help="Temperature in K (2000-10000)")
p_ap = sub.add_parser("aperture", help="Set aperture by f-stop (e.g., 2.8 or F2.8)")
p_ap.add_argument("value", help="F-stop value")
p_raw = sub.add_parser("raw", help="Send raw command by numeric ID")
p_raw.add_argument("command_id", help="Numeric command ID")
p_raw.add_argument("value", nargs="?", help="Value to set (omit for GET)")
sub.add_parser("probe", help="Probe camera TCP port to detect framing protocol")
sub.add_parser("monitor", help="Monitor real-time camera notifications")
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(0)
dispatch = {
"status": cmd_status,
"list": cmd_list,
"init": cmd_init,
"get": cmd_get,
"get-all": cmd_get_all,
"set": cmd_set,
"iso": cmd_set_iso,
"shutter": cmd_set_shutter,
"wb-temp": cmd_set_wb_temp,
"aperture": cmd_set_aperture,
"raw": cmd_raw,
"probe": cmd_probe,
"monitor": cmd_monitor,
}
try:
dispatch[args.command](args)
except ConnectionRefusedError:
print("Connection refused. Is the camera connected and the network interface up?", file=sys.stderr)
print(f"Try: yolocam-ctl status", file=sys.stderr)
sys.exit(1)
except socket.timeout:
print("Connection timed out. Camera may not be reachable.", file=sys.stderr)
sys.exit(1)
except OSError as e:
if "Network is unreachable" in str(e):
print("Network unreachable. The CDC NCM interface may not be configured.", file=sys.stderr)
print("Try: sudo dhclient <interface> OR yolocam-ctl status", file=sys.stderr)
else:
print(f"Network error: {e}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()