symbiolink 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
symbiolink/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """SymbioLink PC client library."""
2
+
3
+ from .device import Device, RemoteError, connect, load_state, save_state # noqa: F401
4
+ from .transport import Announcement, TcpTransport, discover # noqa: F401
5
+
6
+ __version__ = "0.4.2"
symbiolink/cli.py ADDED
@@ -0,0 +1,342 @@
1
+ """symdb - ADB-style device management for Symbian phones running the
2
+ SymbioLink device server.
3
+
4
+ Phase 1 commands: devices, connect, disconnect, caps, shell info|battery|ls,
5
+ push, pull, screencap, plus setup helpers: setup-udev, install-app, sis-path.
6
+ Everything else is listed as pending/blocked in docs/CHECKLIST.md - nothing
7
+ here pretends to work.
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+
16
+ from symbiolink import __version__, discover, proto
17
+ from symbiolink.device import (
18
+ RemoteError,
19
+ connect,
20
+ is_usb_spec,
21
+ load_state,
22
+ save_state,
23
+ )
24
+ from symbiolink.transport import DEFAULT_PORT
25
+
26
+ DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
27
+ UDEV_RULE = "70-symbiolink.rules"
28
+ UDEV_DEST = "/etc/udev/rules.d/" + UDEV_RULE
29
+
30
+
31
+ def sis_path():
32
+ """The SymbioLink.sis phone installer bundled with this package."""
33
+ return os.path.join(DATA_DIR, "SymbioLink.sis")
34
+
35
+
36
+ def udev_rule_path():
37
+ return os.path.join(DATA_DIR, UDEV_RULE)
38
+
39
+
40
+ def target_from_args(args):
41
+ """-s host[:port] > $SYMDB_DEVICE > last connect > single discovered phone."""
42
+ spec = args.device or os.environ.get("SYMDB_DEVICE")
43
+ if spec:
44
+ return parse_spec(spec)
45
+ last = load_state().get("last")
46
+ if last:
47
+ return parse_spec(last)
48
+ found = discover(2.0)
49
+ if len(found) == 1:
50
+ return found[0].host, found[0].port
51
+ if not found:
52
+ raise SystemExit("no phone: run 'symdb devices --discover', then 'symdb connect <ip>'")
53
+ raise SystemExit(
54
+ "several phones found: " + ", ".join("%s:%d" % (a.host, a.port) for a in found)
55
+ )
56
+
57
+
58
+ def parse_spec(spec):
59
+ if is_usb_spec(spec):
60
+ return spec, 0
61
+ host, _, port = spec.partition(":")
62
+ return host, int(port or DEFAULT_PORT)
63
+
64
+
65
+ def open_device(args):
66
+ host, port = target_from_args(args)
67
+ return connect(host, port, timeout=args.timeout)
68
+
69
+
70
+ def cmd_devices(args):
71
+ found = discover(args.wait)
72
+ if not found:
73
+ print("no phones announced (start the SymbioLink app on the phone)")
74
+ return 1
75
+ last = load_state().get("last")
76
+ for ann in found:
77
+ mark = "*" if last == "%s:%d" % (ann.host, ann.port) else " "
78
+ print("%s %-15s:%-5d %s" % (mark, ann.host, ann.port, ann.label))
79
+ return 0
80
+
81
+
82
+ def cmd_connect(args):
83
+ if args.usb:
84
+ host, port = ("usb" if args.usb == "auto" else "usb:" + args.usb), 0
85
+ else:
86
+ host, port = parse_spec(args.address) if args.address else target_from_args(args)
87
+ dev = connect(host, port, timeout=args.timeout)
88
+ info = dev.hello_info or {}
89
+ if is_usb_spec(host):
90
+ # remember "usb" for auto-detect, or the exact tty when one was given
91
+ where = host
92
+ label = "USB %s" % dev.transport.path
93
+ else:
94
+ where = label = "%s:%d" % (host, port)
95
+ dev.close()
96
+ save_state({"last": where})
97
+ print("connected to %s" % label)
98
+ print(" device: %s" % info.get("device", {}).get("model", "unknown"))
99
+ print(" server: %s" % info.get("server", "?"))
100
+ return 0
101
+
102
+
103
+ def cmd_disconnect(args):
104
+ state = load_state()
105
+ if not state.get("last"):
106
+ print("nothing to disconnect")
107
+ return 0
108
+ print("forgot %s" % state["last"])
109
+ save_state({"last": None})
110
+ return 0
111
+
112
+
113
+ def cmd_caps(args):
114
+ dev = open_device(args)
115
+ try:
116
+ print(json.dumps(dev.caps(), indent=2, sort_keys=True))
117
+ finally:
118
+ dev.close()
119
+ return 0
120
+
121
+
122
+ def cmd_shell(args):
123
+ dev = open_device(args)
124
+ try:
125
+ what = args.what
126
+ if what == "info":
127
+ print(json.dumps(dev.info(), indent=2, sort_keys=True))
128
+ elif what == "battery":
129
+ print(json.dumps(dev.battery(), indent=2, sort_keys=True))
130
+ elif what == "ls":
131
+ path = args.path or "C:\\"
132
+ listing = dev.ls(path)
133
+ for entry in listing.get("entries", []):
134
+ kind = "d" if entry.get("dir") else "-"
135
+ print("%s %10d %s" % (kind, int(entry.get("size", 0)), entry.get("name")))
136
+ if listing.get("error"):
137
+ print("error: %s" % listing["error"], file=sys.stderr)
138
+ return 1
139
+ else:
140
+ raise SystemExit("unknown shell command %r" % what)
141
+ finally:
142
+ dev.close()
143
+ return 0
144
+
145
+
146
+ def cmd_push(args):
147
+ local, remote = args.local, args.remote
148
+ if remote.endswith("/") or remote.endswith("\\"):
149
+ remote = remote + os.path.basename(local)
150
+ dev = open_device(args)
151
+ try:
152
+ sent = dev.write_file(remote, local_path=local)
153
+ print("pushed %s -> %s (%d bytes)" % (local, remote, sent))
154
+ finally:
155
+ dev.close()
156
+ return 0
157
+
158
+
159
+ def cmd_pull(args):
160
+ remote, local = args.remote, args.local
161
+ if os.path.isdir(local):
162
+ local = os.path.join(local, remote.replace("\\", "/").rsplit("/", 1)[-1])
163
+ dev = open_device(args)
164
+ try:
165
+ blob = dev.read_file(remote)
166
+ finally:
167
+ dev.close()
168
+ with open(local, "wb") as fh:
169
+ fh.write(blob)
170
+ print("pulled %s -> %s (%d bytes)" % (remote, local, len(blob)))
171
+ return 0
172
+
173
+
174
+ def cmd_screencap(args):
175
+ dev = open_device(args)
176
+ try:
177
+ head, blob = dev.screencap()
178
+ finally:
179
+ dev.close()
180
+ with open(args.output, "wb") as fh:
181
+ fh.write(blob)
182
+ print(
183
+ "saved %s (%dx%d %s, %d bytes)"
184
+ % (
185
+ args.output,
186
+ int(head.get("width", 0)),
187
+ int(head.get("height", 0)),
188
+ head.get("mime", "application/octet-stream"),
189
+ len(blob),
190
+ )
191
+ )
192
+ return 0
193
+
194
+
195
+ def cmd_sis_path(args):
196
+ path = sis_path()
197
+ if not os.path.isfile(path):
198
+ print("symdb: bundled SymbioLink.sis missing (%s)" % path, file=sys.stderr)
199
+ return 1
200
+ print(path)
201
+ return 0
202
+
203
+
204
+ def cmd_install_app(args):
205
+ local = sis_path()
206
+ if not os.path.isfile(local):
207
+ print("symdb: bundled SymbioLink.sis missing (%s)" % local, file=sys.stderr)
208
+ return 1
209
+ remote = args.to
210
+ if remote.endswith("/") or remote.endswith("\\"):
211
+ remote = remote + "SymbioLink.sis"
212
+ dev = open_device(args)
213
+ try:
214
+ sent = dev.write_file(remote, local_path=local)
215
+ finally:
216
+ dev.close()
217
+ print("pushed SymbioLink.sis -> %s (%d bytes)" % (remote, sent))
218
+ if remote.upper().startswith("C:\\DATA\\"):
219
+ print("open Files > Phone memory > %s on the phone to install"
220
+ % remote[len("C:\\Data\\"):])
221
+ else:
222
+ print("open %s in Files on the phone to install" % remote)
223
+ return 0
224
+
225
+
226
+ def cmd_setup_udev(args):
227
+ rule = udev_rule_path()
228
+ if not sys.platform.startswith("linux"):
229
+ print("setup-udev is only needed on Linux; other systems need no rule "
230
+ "(the USB cable transport is only supported on Linux for now)")
231
+ return 0
232
+ cmds = [
233
+ ["sudo", "install", "-m644", rule, UDEV_DEST],
234
+ ["sudo", "udevadm", "control", "--reload"],
235
+ ]
236
+ if not args.install:
237
+ print("# %s (bundled at %s)" % (UDEV_RULE, rule))
238
+ with open(rule, encoding="utf-8") as fh:
239
+ print(fh.read().rstrip())
240
+ print()
241
+ print("# install it (then unplug and replug the phone):")
242
+ for cmd in cmds:
243
+ print(" ".join(cmd))
244
+ print()
245
+ print("# or let symdb run these: symdb setup-udev --install")
246
+ return 0
247
+ if not args.yes:
248
+ print("will run:")
249
+ for cmd in cmds:
250
+ print(" " + " ".join(cmd))
251
+ try:
252
+ answer = input("continue? [y/N] ")
253
+ except EOFError:
254
+ answer = ""
255
+ if answer.strip().lower() not in ("y", "yes"):
256
+ print("aborted")
257
+ return 1
258
+ for cmd in cmds:
259
+ rc = subprocess.call(cmd)
260
+ if rc != 0:
261
+ print("symdb: %s failed (exit %d)" % (" ".join(cmd), rc), file=sys.stderr)
262
+ return rc
263
+ print("installed %s; unplug and replug the phone" % UDEV_DEST)
264
+ return 0
265
+
266
+
267
+ def build_parser():
268
+ parser = argparse.ArgumentParser(prog="symdb", description=__doc__)
269
+ parser.add_argument("--version", action="version", version="symdb " + __version__)
270
+ parser.add_argument("-s", "--device", help="host[:port], usb or usb:/dev/ttyACMn (before the command)")
271
+ parser.add_argument("--timeout", type=float, default=8.0)
272
+ sub = parser.add_subparsers(dest="command", required=True)
273
+
274
+ p = sub.add_parser("devices", help="list phones announcing on the network")
275
+ p.add_argument("--discover", action="store_true", help="(default) listen for announcements")
276
+ p.add_argument("--wait", type=float, default=2.0, help="seconds to listen (default 2)")
277
+ p.set_defaults(func=cmd_devices)
278
+
279
+ p = sub.add_parser("connect", help="connect and remember the phone")
280
+ p.add_argument("address", nargs="?", help="host[:port]; omit to use discovery/last")
281
+ p.add_argument("--usb", nargs="?", const="auto", metavar="DEV",
282
+ help="use the USB cable (auto-detects /dev/ttyACM*, or give DEV)")
283
+ p.set_defaults(func=cmd_connect)
284
+
285
+ p = sub.add_parser("disconnect", help="forget the remembered phone")
286
+ p.set_defaults(func=cmd_disconnect)
287
+
288
+ p = sub.add_parser("caps", help="capability report from the phone")
289
+ p.set_defaults(func=cmd_caps)
290
+
291
+ p = sub.add_parser("shell", help="run a command on the phone")
292
+ p.add_argument("what", choices=["info", "battery", "ls"])
293
+ p.add_argument("path", nargs="?", help="path for 'ls'")
294
+ p.set_defaults(func=cmd_shell)
295
+
296
+ p = sub.add_parser("push", help="copy a file to the phone")
297
+ p.add_argument("local")
298
+ p.add_argument("remote", nargs="?", default="C:\\Data\\",
299
+ help="destination file or folder (default C:\\Data\\)")
300
+ p.set_defaults(func=cmd_push)
301
+
302
+ p = sub.add_parser("pull", help="copy a file from the phone")
303
+ p.add_argument("remote")
304
+ p.add_argument("local", nargs="?", default=".")
305
+ p.set_defaults(func=cmd_pull)
306
+
307
+ p = sub.add_parser("screencap", help="save a JPEG screenshot")
308
+ p.add_argument("output", nargs="?", default="screenshot.jpg")
309
+ p.set_defaults(func=cmd_screencap)
310
+
311
+ p = sub.add_parser("install-app", help="push the bundled SymbioLink.sis to the phone")
312
+ p.add_argument("--to", default="C:\\Data\\SymbioLink.sis", metavar="PATH",
313
+ help="destination on the phone (default C:\\Data\\SymbioLink.sis)")
314
+ p.set_defaults(func=cmd_install_app)
315
+
316
+ p = sub.add_parser("sis-path", help="print the path of the bundled SymbioLink.sis")
317
+ p.set_defaults(func=cmd_sis_path)
318
+
319
+ p = sub.add_parser("setup-udev", help="show (or --install) the Linux udev rule for USB")
320
+ p.add_argument("--install", action="store_true", help="run the sudo commands")
321
+ p.add_argument("-y", "--yes", action="store_true", help="do not ask for confirmation")
322
+ p.set_defaults(func=cmd_setup_udev)
323
+
324
+ return parser
325
+
326
+
327
+ def main(argv=None):
328
+ args = build_parser().parse_args(argv)
329
+ try:
330
+ return args.func(args)
331
+ except (RemoteError, proto.ProtocolError) as exc:
332
+ print("symdb: %s" % exc, file=sys.stderr)
333
+ return 2
334
+ except OSError as exc:
335
+ print("symdb: connection failed: %s" % exc, file=sys.stderr)
336
+ return 2
337
+ except KeyboardInterrupt:
338
+ return 130
339
+
340
+
341
+ if __name__ == "__main__":
342
+ sys.exit(main())
@@ -0,0 +1,11 @@
1
+ # SymbioLink: USB cable transport for Nokia S60 phones in "PC Suite" mode.
2
+ # 1. The phone's second CDC-ACM port (the one SymbioLink's symbiolink_usb.exe uses)
3
+ # declares a vendor-specific protocol, so cdc_acm skips it; teach cdc_acm
4
+ # this phone's id so it binds (shows up as an extra /dev/ttyACMn).
5
+ # 2. Give the logged-in user access to Nokia serial ports (no uucp group or
6
+ # re-login needed).
7
+ # Install: symdb setup-udev --install (or: sudo install -m644 70-symbiolink.rules /etc/udev/rules.d/ &&
8
+ # sudo udevadm control --reload)
9
+ # Must sort before 73-seat-late.rules or TAG+="uaccess" is ignored.
10
+ ACTION=="add", SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{idVendor}=="0421", RUN+="/bin/sh -c 'modprobe cdc_acm; echo 0421 $attr{idProduct} 02 > /sys/bus/usb/drivers/cdc_acm/new_id || true'"
11
+ SUBSYSTEM=="tty", KERNEL=="ttyACM*", ATTRS{idVendor}=="0421", MODE="0660", GROUP="uucp", TAG+="uaccess"
Binary file
symbiolink/device.py ADDED
@@ -0,0 +1,193 @@
1
+ """The client side of the SL/1 conversation: requests, data frames, capabilities."""
2
+
3
+ import json
4
+ import os
5
+
6
+ from . import proto
7
+ from .transport import SerialTransport, TcpTransport, find_usb_ports
8
+
9
+ PROTO_VERSION = 1
10
+
11
+
12
+ class RemoteError(Exception):
13
+ pass
14
+
15
+
16
+ class Device:
17
+ """A connected phone."""
18
+
19
+ def __init__(self, transport):
20
+ self.transport = transport
21
+ self.seq = 0
22
+ self.hello_info = None
23
+ self.pending = None # last DATA-expected length, for convenience
24
+
25
+ # ---------------------------------------------------------------- plumbing
26
+ def _next_seq(self):
27
+ self.seq = (self.seq + 1) & 0xFFFFFFFF
28
+ return self.seq
29
+
30
+ def _send(self, ftype, payload):
31
+ self.transport.sendall(proto.pack(ftype, self._next_seq(), payload))
32
+
33
+ def _send_json(self, ftype, obj):
34
+ self.transport.sendall(
35
+ proto.pack(ftype, self._next_seq(), json.dumps(obj, separators=(",", ":")).encode("utf-8"))
36
+ )
37
+
38
+ def _recv(self):
39
+ return proto.read_frame(self.transport)
40
+
41
+ def request(self, op, **args):
42
+ """Send a REQ and return the JSON RES payload as a dict."""
43
+ self._send_json(proto.TYPE_REQ, {"op": op, "args": args})
44
+ frame = self._recv()
45
+ if frame.ftype == proto.TYPE_ERR:
46
+ raise RemoteError(frame.json.get("error", "remote error"))
47
+ if frame.ftype != proto.TYPE_RES:
48
+ raise proto.ProtocolError("expected RES, got %r" % frame)
49
+ return frame.json
50
+
51
+ def send_data(self, blob):
52
+ self._send(proto.TYPE_DATA, blob)
53
+
54
+ def recv_data(self, size):
55
+ """Read exactly size bytes that arrive as DATA frames."""
56
+ out = bytearray()
57
+ while len(out) < size:
58
+ frame = self._recv()
59
+ if frame.ftype != proto.TYPE_DATA:
60
+ raise proto.ProtocolError("expected DATA, got %r" % frame)
61
+ out.extend(frame.payload)
62
+ if len(out) != size:
63
+ raise proto.ProtocolError("DATA overrun: %d > %d" % (len(out), size))
64
+ return bytes(out)
65
+
66
+ # -------------------------------------------------------------------- verbs
67
+ def hello(self, client="symdb"):
68
+ info = self.request("hello", client=client, proto=PROTO_VERSION)
69
+ self.hello_info = info
70
+ return info
71
+
72
+ def caps(self):
73
+ return self.request("caps")
74
+
75
+ def info(self):
76
+ return self.request("info")
77
+
78
+ def battery(self):
79
+ return self.request("battery")
80
+
81
+ def ls(self, path):
82
+ return self.request("fs.list", path=path)
83
+
84
+ def mkdir(self, path):
85
+ return self.request("fs.mkdir", path=path)
86
+
87
+ def rm(self, path):
88
+ return self.request("fs.rm", path=path)
89
+
90
+ def read_file(self, path):
91
+ head = self.request("fs.read", path=path)
92
+ size = int(head.get("size", 0))
93
+ return self.recv_data(size) if size else b""
94
+
95
+ def write_file(self, remote_path, local_path=None, data=None, chunk_size=32768):
96
+ if data is None:
97
+ with open(local_path, "rb") as fh:
98
+ data = fh.read()
99
+ self.request("fs.write", path=remote_path, size=len(data))
100
+ for part in proto.chunk(data, chunk_size):
101
+ if part:
102
+ self.send_data(part)
103
+ result = self.request("fs.write.end", path=remote_path, size=len(data))
104
+ if not result.get("ok"):
105
+ raise RemoteError(result.get("error", "write failed"))
106
+ return len(data)
107
+
108
+ def screencap(self):
109
+ head = self.request("screen.capture")
110
+ size = int(head.get("size", 0))
111
+ return head, self.recv_data(size) if size else b""
112
+
113
+ def close(self):
114
+ self.transport.close()
115
+
116
+
117
+ def is_usb_spec(host):
118
+ return host == "usb" or (host or "").startswith("usb:")
119
+
120
+
121
+ def connect(host, port, timeout=8.0, hello=True):
122
+ """host is an IP/hostname, or "usb" / "usb:/dev/ttyACMn" for the cable."""
123
+ if is_usb_spec(host):
124
+ return connect_usb(host[4:] or None, timeout, hello)
125
+ device = Device(TcpTransport(host, port, timeout).open())
126
+ if hello:
127
+ device.hello()
128
+ return device
129
+
130
+
131
+ def connect_usb(path=None, timeout=8.0, hello=True, probe_timeout=3.0):
132
+ """Open the USB cable transport.
133
+
134
+ With no path, every Nokia /dev/ttyACM* is tried with a short ``hello``
135
+ and the first that answers is kept (the phone exposes several ACM
136
+ interfaces in PC Suite mode; only the one symbiolink_usb.exe holds answers).
137
+ """
138
+ if path:
139
+ candidates = [path]
140
+ else:
141
+ candidates = find_usb_ports()
142
+ if not candidates:
143
+ raise OSError("no Nokia USB serial port (/dev/ttyACM* with idVendor "
144
+ "0421): plug the cable in, pick 'PC Suite' mode on "
145
+ "the phone and start SymbioLink")
146
+ errors = []
147
+ for dev in candidates:
148
+ t = SerialTransport(dev, probe_timeout if (hello and len(candidates) > 1) else timeout)
149
+ try:
150
+ t.open()
151
+ except PermissionError:
152
+ raise
153
+ except OSError as exc:
154
+ errors.append("%s: %s" % (dev, exc))
155
+ continue
156
+ device = Device(t)
157
+ if not hello:
158
+ t.settimeout(timeout)
159
+ return device
160
+ try:
161
+ device.hello()
162
+ except Exception as exc: # a modem ACM port may echo or babble
163
+ errors.append("%s: no answer (%s)" % (dev, exc or type(exc).__name__))
164
+ t.close()
165
+ continue
166
+ t.settimeout(timeout)
167
+ return device
168
+ raise OSError("no SymbioLink answer over USB: " + "; ".join(errors))
169
+
170
+
171
+ # --------------------------------------------------------------------- state
172
+ def state_path():
173
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config")
174
+ return os.path.join(base, "symbiolink", "state.json")
175
+
176
+
177
+ def load_state():
178
+ path = state_path()
179
+ try:
180
+ with open(path, "r", encoding="utf-8") as fh:
181
+ return json.load(fh)
182
+ except (OSError, ValueError):
183
+ return {}
184
+
185
+
186
+ def save_state(state):
187
+ path = state_path()
188
+ os.makedirs(os.path.dirname(path), exist_ok=True)
189
+ tmp = path + ".tmp"
190
+ with open(tmp, "w", encoding="utf-8") as fh:
191
+ json.dump(state, fh, indent=2, sort_keys=True)
192
+ fh.write("\n")
193
+ os.replace(tmp, path)