rubberorca 0.1.3__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.
rubberorca/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ from .protocol import (
2
+ ACK_LEN,
3
+ CHAR_UUID,
4
+ ETX,
5
+ PAYLOAD_MAX,
6
+ SERVICE_UUID,
7
+ STX,
8
+ VERSION,
9
+ Ack,
10
+ ProtocolError,
11
+ build_frame,
12
+ escape_text,
13
+ parse_ack,
14
+ )
15
+
16
+ from .sdk import RubberOrca
17
+
18
+ __version__ = "0.1.3" # x-release-please-version
19
+ __all__ = [
20
+ "ACK_LEN",
21
+ "Ack",
22
+ "CHAR_UUID",
23
+ "ETX",
24
+ "PAYLOAD_MAX",
25
+ "ProtocolError",
26
+ "RubberOrca",
27
+ "SERVICE_UUID",
28
+ "STX",
29
+ "VERSION",
30
+ "__version__",
31
+ "build_frame",
32
+ "escape_text",
33
+ "parse_ack",
34
+ ]
rubberorca/cli.py ADDED
@@ -0,0 +1,172 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from typing import Optional
7
+
8
+ from .protocol import ProtocolError, escape_text
9
+ from .transport import list_serial_ports, scan_ble, send_command, send_raw_byte
10
+
11
+
12
+ def build_command_from_args(args: argparse.Namespace) -> str:
13
+ """Convert parsed CLI subcommand arguments into a RubberOrca wire command."""
14
+ cmd = args.command
15
+ if cmd == "send":
16
+ return args.payload
17
+ if cmd == "type":
18
+ return f'type "{escape_text(args.text)}"'
19
+ if cmd == "key":
20
+ return args.name
21
+ if cmd == "press":
22
+ if args.ms is not None:
23
+ return f"press {args.mod} {args.ms}"
24
+ return f"press {args.mod}"
25
+ if cmd == "media":
26
+ return f"media {args.action}"
27
+ if cmd == "mouse":
28
+ if args.mouse_cmd == "move":
29
+ return f"mouse move {args.dx} {args.dy}"
30
+ if args.mouse_cmd == "click":
31
+ return f"mouse click {args.button}"
32
+ if args.mouse_cmd == "scroll":
33
+ return f"mouse scroll {args.amount}"
34
+ if cmd == "jiggler":
35
+ return f"jiggler {args.state}"
36
+ if cmd == "macro":
37
+ if args.macro_cmd == "define":
38
+ return f"macro define {args.slot} {{ {args.body} }}"
39
+ if args.macro_cmd == "run":
40
+ return f"macro run {args.slot}"
41
+ if cmd == "ble-name":
42
+ return f'ble name "{args.name}"'
43
+ if cmd == "ble-passkey":
44
+ return f"ble passkey {args.passkey}"
45
+ if cmd == "layout":
46
+ return f"layout {args.name}"
47
+ raise ValueError(f"Unsupported command: {cmd}")
48
+
49
+
50
+ def build_parser() -> argparse.ArgumentParser:
51
+ parser = argparse.ArgumentParser(
52
+ prog="rubberorca",
53
+ description="Control RubberOrca ESP32-S3 USB HID over BLE 5.0 GATT or USB CDC Serial.",
54
+ )
55
+ parser.add_argument("--port", help="USB CDC serial port (uses BLE GATT when omitted)")
56
+ parser.add_argument("--address", help="Explicit BLE device address or UUID")
57
+ parser.add_argument("--baud", type=int, default=115200, help="Serial baud rate (default: 115200)")
58
+ parser.add_argument("--timeout", type=float, default=3.0, help="Transport timeout in seconds")
59
+ parser.add_argument("--seq", type=int, default=1, help="Packet sequence number (0-255)")
60
+
61
+ sub = parser.add_subparsers(dest="command", required=True)
62
+
63
+ sub.add_parser("scan", help="Scan for BLE 0xFFE0 devices and list serial ports")
64
+
65
+ p_send = sub.add_parser("send", help="Send a raw command or &&/; chain")
66
+ p_send.add_argument("payload", help="Raw command string")
67
+
68
+ p_type = sub.add_parser("type", help="Type text over USB HID keyboard")
69
+ p_type.add_argument("text", help="Text to type")
70
+
71
+ p_key = sub.add_parser("key", help="Send a single special key")
72
+ p_key.add_argument("name", choices=["enter", "tab", "backspace"])
73
+
74
+ p_press = sub.add_parser("press", help="Press a modifier or shortcut combo")
75
+ p_press.add_argument("mod", help="Modifier or combo (shift, ctrl, alt, gui, right, left, f5, 'gui l')")
76
+ p_press.add_argument("ms", nargs="?", type=int, help="Optional hold duration in ms (1-5000)")
77
+
78
+ p_media = sub.add_parser("media", help="Send a Consumer Control media key")
79
+ p_media.add_argument(
80
+ "action",
81
+ choices=["play_pause", "volume_up", "volume_down", "next", "prev", "mute"],
82
+ )
83
+
84
+ p_mouse = sub.add_parser("mouse", help="Control USB HID mouse")
85
+ mouse_sub = p_mouse.add_subparsers(dest="mouse_cmd", required=True)
86
+ pm_move = mouse_sub.add_parser("move", help="Move relative pointer")
87
+ pm_move.add_argument("dx", type=int)
88
+ pm_move.add_argument("dy", type=int)
89
+ pm_click = mouse_sub.add_parser("click", help="Click mouse button")
90
+ pm_click.add_argument("button", choices=["left", "right", "middle"], default="left", nargs="?")
91
+ pm_scroll = mouse_sub.add_parser("scroll", help="Scroll vertical wheel")
92
+ pm_scroll.add_argument("amount", type=int)
93
+
94
+ p_jig = sub.add_parser("jiggler", help="Control mouse jiggler")
95
+ p_jig.add_argument("state", choices=["on", "off", "toggle"])
96
+
97
+ p_macro = sub.add_parser("macro", help="Manage NVS macros (m0..m15)")
98
+ macro_sub = p_macro.add_subparsers(dest="macro_cmd", required=True)
99
+ pm_def = macro_sub.add_parser("define", help="Save macro body to NVS slot")
100
+ pm_def.add_argument("slot", help="Slot name m0..m15")
101
+ pm_def.add_argument("body", help="Command chain to store")
102
+ pm_run = macro_sub.add_parser("run", help="Run stored NVS macro")
103
+ pm_run.add_argument("slot", help="Slot name m0..m15")
104
+
105
+ p_ble = sub.add_parser("ble-name", help="Update BLE advertising name in NVS")
106
+ p_ble.add_argument("name", help="Printable ASCII name (1-29 chars)")
107
+
108
+ p_pk = sub.add_parser("ble-passkey", help="Set 6-digit BLE bonding passkey or 'off'")
109
+ p_pk.add_argument("passkey", help="6-digit passkey (100000-999999) or 'off'")
110
+
111
+ p_lay = sub.add_parser("layout", help="Set USB HID keyboard layout in NVS")
112
+ p_lay.add_argument("name", choices=["us", "tr_q"])
113
+
114
+ p_raw = sub.add_parser("raw-byte", help="Send a single-byte fallback command (e.g. 0x32)")
115
+ p_raw.add_argument("value", help="Hex or decimal byte in 0x10..0x8F")
116
+
117
+ return parser
118
+
119
+
120
+ def main(argv: Optional[list[str]] = None) -> int:
121
+ parser = build_parser()
122
+ args = parser.parse_args(argv)
123
+
124
+ try:
125
+ if args.command == "scan":
126
+ ble_devices = asyncio.run(scan_ble(timeout=args.timeout))
127
+ print("BLE devices (Service 0xFFE0):")
128
+ if ble_devices:
129
+ for addr, name in ble_devices:
130
+ print(f" {addr} {name}")
131
+ else:
132
+ print(" (none)")
133
+ print("Serial ports:")
134
+ ports = list_serial_ports()
135
+ if ports:
136
+ for dev, desc in ports:
137
+ print(f" {dev} {desc}")
138
+ else:
139
+ print(" (none)")
140
+ return 0
141
+
142
+ if args.command == "raw-byte":
143
+ val = int(args.value, 0)
144
+ send_raw_byte(
145
+ val,
146
+ port=args.port,
147
+ address=args.address,
148
+ baud=args.baud,
149
+ timeout=args.timeout,
150
+ )
151
+ print(f"Sent fallback byte 0x{val:02X}")
152
+ return 0
153
+
154
+ wire_cmd = build_command_from_args(args)
155
+ ack = send_command(
156
+ wire_cmd,
157
+ port=args.port,
158
+ address=args.address,
159
+ baud=args.baud,
160
+ timeout=args.timeout,
161
+ seq=args.seq,
162
+ )
163
+ status = "OK" if ack.ok else f"ERR(code={ack.code})"
164
+ print(f"ACK seq={ack.seq} {status}")
165
+ return 0 if ack.ok else 2
166
+ except (ProtocolError, RuntimeError, ValueError, TimeoutError, asyncio.TimeoutError) as exc:
167
+ print(f"Error: {exc}", file=sys.stderr)
168
+ return 1
169
+
170
+
171
+ if __name__ == "__main__":
172
+ raise SystemExit(main())
@@ -0,0 +1,333 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import Any, Callable, Optional, TextIO
9
+
10
+ from . import __version__
11
+ from .protocol import ProtocolError, escape_text
12
+ from .transport import list_serial_ports, scan_ble, send_command
13
+
14
+ MCP_PROTOCOL_VERSION = "2024-11-05"
15
+
16
+ TOOLS: list[dict[str, Any]] = [
17
+ {
18
+ "name": "scan_devices",
19
+ "description": "Scan for nearby RubberOrca BLE devices (Service 0xFFE0) and local USB serial ports.",
20
+ "inputSchema": {
21
+ "type": "object",
22
+ "properties": {
23
+ "timeout": {"type": "number", "minimum": 0.5, "maximum": 15.0, "default": 4.0},
24
+ },
25
+ "additionalProperties": False,
26
+ },
27
+ },
28
+ {
29
+ "name": "type_text",
30
+ "description": "Type ASCII text onto the target host over wired USB HID keyboard.",
31
+ "inputSchema": {
32
+ "type": "object",
33
+ "properties": {
34
+ "text": {"type": "string", "minLength": 1},
35
+ "port": {"type": "string"},
36
+ "address": {"type": "string"},
37
+ },
38
+ "required": ["text"],
39
+ "additionalProperties": False,
40
+ },
41
+ },
42
+ {
43
+ "name": "press_key",
44
+ "description": "Send enter/tab/backspace or press a modifier/shortcut combo (shift, ctrl, alt, gui, right, left, f5, 'gui l', 'gui d', 'ctrl shift esc').",
45
+ "inputSchema": {
46
+ "type": "object",
47
+ "properties": {
48
+ "key": {"type": "string", "minLength": 1},
49
+ "ms": {"type": "integer", "minimum": 1, "maximum": 5000},
50
+ "port": {"type": "string"},
51
+ "address": {"type": "string"},
52
+ },
53
+ "required": ["key"],
54
+ "additionalProperties": False,
55
+ },
56
+ },
57
+ {
58
+ "name": "media_control",
59
+ "description": "Send a USB HID Consumer Control media key.",
60
+ "inputSchema": {
61
+ "type": "object",
62
+ "properties": {
63
+ "action": {
64
+ "type": "string",
65
+ "enum": ["play_pause", "volume_up", "volume_down", "next", "prev", "mute"],
66
+ },
67
+ "port": {"type": "string"},
68
+ "address": {"type": "string"},
69
+ },
70
+ "required": ["action"],
71
+ "additionalProperties": False,
72
+ },
73
+ },
74
+ {
75
+ "name": "mouse_action",
76
+ "description": "Move, click, or scroll the wired USB HID mouse.",
77
+ "inputSchema": {
78
+ "type": "object",
79
+ "properties": {
80
+ "action": {"type": "string", "enum": ["move", "click", "scroll"]},
81
+ "dx": {"type": "integer", "minimum": -127, "maximum": 127},
82
+ "dy": {"type": "integer", "minimum": -127, "maximum": 127},
83
+ "button": {"type": "string", "enum": ["left", "right", "middle"]},
84
+ "amount": {"type": "integer", "minimum": -127, "maximum": 127},
85
+ "port": {"type": "string"},
86
+ "address": {"type": "string"},
87
+ },
88
+ "required": ["action"],
89
+ "additionalProperties": False,
90
+ },
91
+ },
92
+ {
93
+ "name": "jiggler",
94
+ "description": "Turn the RubberOrca mouse jiggler on, off, or toggle it.",
95
+ "inputSchema": {
96
+ "type": "object",
97
+ "properties": {
98
+ "state": {"type": "string", "enum": ["on", "off", "toggle"]},
99
+ "port": {"type": "string"},
100
+ "address": {"type": "string"},
101
+ },
102
+ "required": ["state"],
103
+ "additionalProperties": False,
104
+ },
105
+ },
106
+ {
107
+ "name": "macro_define",
108
+ "description": "Persist a command chain into an ESP32-S3 NVS macro slot (m0..m15).",
109
+ "inputSchema": {
110
+ "type": "object",
111
+ "properties": {
112
+ "slot": {"type": "string", "pattern": "^m([0-9]|1[0-5])$"},
113
+ "body": {"type": "string", "minLength": 1},
114
+ "port": {"type": "string"},
115
+ "address": {"type": "string"},
116
+ },
117
+ "required": ["slot", "body"],
118
+ "additionalProperties": False,
119
+ },
120
+ },
121
+ {
122
+ "name": "macro_run",
123
+ "description": "Execute a stored NVS macro slot (m0..m15).",
124
+ "inputSchema": {
125
+ "type": "object",
126
+ "properties": {
127
+ "slot": {"type": "string", "pattern": "^m([0-9]|1[0-5])$"},
128
+ "port": {"type": "string"},
129
+ "address": {"type": "string"},
130
+ },
131
+ "required": ["slot"],
132
+ "additionalProperties": False,
133
+ },
134
+ },
135
+ {
136
+ "name": "send_command",
137
+ "description": "Send a raw RubberOrca command or && / ; command chain.",
138
+ "inputSchema": {
139
+ "type": "object",
140
+ "properties": {
141
+ "command": {"type": "string", "minLength": 1},
142
+ "port": {"type": "string"},
143
+ "address": {"type": "string"},
144
+ },
145
+ "required": ["command"],
146
+ "additionalProperties": False,
147
+ },
148
+ },
149
+ ]
150
+
151
+
152
+ class RubberOrcaMcpServer:
153
+ """Minimal stdio JSON-RPC 2.0 MCP server for RubberOrca."""
154
+
155
+ def __init__(
156
+ self,
157
+ *,
158
+ default_port: Optional[str] = None,
159
+ default_address: Optional[str] = None,
160
+ baud: int = 115200,
161
+ timeout: float = 3.0,
162
+ sender: Callable[..., Any] = send_command,
163
+ ) -> None:
164
+ self.default_port = default_port
165
+ self.default_address = default_address
166
+ self.baud = baud
167
+ self.timeout = timeout
168
+ self._sender = sender
169
+ self._seq = 1
170
+
171
+ def _next_seq(self) -> int:
172
+ seq = self._seq
173
+ self._seq = (self._seq + 1) & 0xFF
174
+ return seq
175
+
176
+ def _dispatch_wire(self, wire_cmd: str, args: dict[str, Any]) -> dict[str, Any]:
177
+ port = args.get("port") or self.default_port
178
+ address = args.get("address") or self.default_address
179
+ ack = self._sender(
180
+ wire_cmd,
181
+ port=port,
182
+ address=address,
183
+ baud=self.baud,
184
+ timeout=self.timeout,
185
+ seq=self._next_seq(),
186
+ )
187
+ text = f"ACK seq={ack.seq} {'OK' if ack.ok else f'ERR(code={ack.code})'}"
188
+ return {"content": [{"type": "text", "text": text}], "isError": not ack.ok}
189
+
190
+ def call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
191
+ if name == "scan_devices":
192
+ timeout = float(args.get("timeout", 4.0))
193
+ ble = asyncio.run(scan_ble(timeout=timeout))
194
+ serial_ports = list_serial_ports()
195
+ payload = {
196
+ "ble": [{"address": a, "name": n} for a, n in ble],
197
+ "serial": [{"port": d, "description": desc} for d, desc in serial_ports],
198
+ }
199
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "isError": False}
200
+
201
+ if name == "type_text":
202
+ text = str(args["text"])
203
+ return self._dispatch_wire(f'type "{escape_text(text)}"', args)
204
+
205
+ if name == "press_key":
206
+ key = str(args["key"]).strip()
207
+ if key in ("enter", "tab", "backspace"):
208
+ return self._dispatch_wire(key, args)
209
+ ms = args.get("ms")
210
+ cmd = f"press {key} {int(ms)}" if ms is not None else f"press {key}"
211
+ return self._dispatch_wire(cmd, args)
212
+
213
+ if name == "media_control":
214
+ return self._dispatch_wire(f"media {args['action']}", args)
215
+
216
+ if name == "mouse_action":
217
+ action = args["action"]
218
+ if action == "move":
219
+ return self._dispatch_wire(f"mouse move {int(args.get('dx', 0))} {int(args.get('dy', 0))}", args)
220
+ if action == "click":
221
+ return self._dispatch_wire(f"mouse click {args.get('button', 'left')}", args)
222
+ if action == "scroll":
223
+ return self._dispatch_wire(f"mouse scroll {int(args.get('amount', 0))}", args)
224
+ raise ValueError(f"Unsupported mouse action: {action}")
225
+
226
+ if name == "jiggler":
227
+ return self._dispatch_wire(f"jiggler {args['state']}", args)
228
+
229
+ if name == "macro_define":
230
+ return self._dispatch_wire(f"macro define {args['slot']} {{ {args['body']} }}", args)
231
+
232
+ if name == "macro_run":
233
+ return self._dispatch_wire(f"macro run {args['slot']}", args)
234
+
235
+ if name == "send_command":
236
+ return self._dispatch_wire(str(args["command"]), args)
237
+
238
+ raise KeyError(f"Unknown tool: {name}")
239
+
240
+ def handle_request(self, req: dict[str, Any]) -> Optional[dict[str, Any]]:
241
+ req_id = req.get("id")
242
+ method = req.get("method")
243
+ params = req.get("params") or {}
244
+
245
+ # Notifications have no id and expect no response.
246
+ if req_id is None:
247
+ return None
248
+
249
+ if method == "initialize":
250
+ return {
251
+ "jsonrpc": "2.0",
252
+ "id": req_id,
253
+ "result": {
254
+ "protocolVersion": MCP_PROTOCOL_VERSION,
255
+ "capabilities": {"tools": {}},
256
+ "serverInfo": {"name": "rubberorca-mcp", "version": __version__},
257
+ },
258
+ }
259
+
260
+ if method == "ping":
261
+ return {"jsonrpc": "2.0", "id": req_id, "result": {}}
262
+
263
+ if method == "tools/list":
264
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
265
+
266
+ if method == "tools/call":
267
+ tool_name = params.get("name", "")
268
+ tool_args = params.get("arguments") or {}
269
+ try:
270
+ result = self.call_tool(tool_name, tool_args)
271
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
272
+ except KeyError as exc:
273
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": str(exc)}}
274
+ except (ProtocolError, RuntimeError, ValueError, TimeoutError, asyncio.TimeoutError) as exc:
275
+ return {
276
+ "jsonrpc": "2.0",
277
+ "id": req_id,
278
+ "result": {"content": [{"type": "text", "text": f"Error: {exc}"}], "isError": True},
279
+ }
280
+
281
+ return {
282
+ "jsonrpc": "2.0",
283
+ "id": req_id,
284
+ "error": {"code": -32601, "message": f"Method not found: {method}"},
285
+ }
286
+
287
+ def serve(self, stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None:
288
+ for line in stdin:
289
+ line = line.strip()
290
+ if not line:
291
+ continue
292
+ try:
293
+ req = json.loads(line)
294
+ except json.JSONDecodeError as exc:
295
+ err = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}
296
+ stdout.write(json.dumps(err) + "\n")
297
+ stdout.flush()
298
+ continue
299
+
300
+ resp = self.handle_request(req)
301
+ if resp is not None:
302
+ stdout.write(json.dumps(resp) + "\n")
303
+ stdout.flush()
304
+
305
+
306
+ def main(argv: Optional[list[str]] = None) -> int:
307
+ parser = argparse.ArgumentParser(
308
+ prog="rubberorca-mcp",
309
+ description="Stdio MCP server for controlling RubberOrca ESP32-S3 USB HID.",
310
+ )
311
+ parser.add_argument("--port", default=os.environ.get("RUBBERORCA_PORT"), help="Default USB CDC serial port")
312
+ parser.add_argument("--address", default=os.environ.get("RUBBERORCA_ADDRESS"), help="Default BLE address/UUID")
313
+ parser.add_argument("--baud", type=int, default=115200, help="Serial baud rate")
314
+ parser.add_argument(
315
+ "--timeout",
316
+ type=float,
317
+ default=float(os.environ.get("RUBBERORCA_TIMEOUT", "3.0")),
318
+ help="Transport timeout in seconds",
319
+ )
320
+ args = parser.parse_args(argv)
321
+
322
+ server = RubberOrcaMcpServer(
323
+ default_port=args.port,
324
+ default_address=args.address,
325
+ baud=args.baud,
326
+ timeout=args.timeout,
327
+ )
328
+ server.serve()
329
+ return 0
330
+
331
+
332
+ if __name__ == "__main__":
333
+ raise SystemExit(main())
rubberorca/protocol.py ADDED
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ STX = 0x02
6
+ ETX = 0x03
7
+ VERSION = 0x01
8
+ PAYLOAD_MAX = 1024
9
+ ACK_LEN = 6
10
+ BLE_CHUNK_SIZE = 20
11
+
12
+ SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb"
13
+ CHAR_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"
14
+
15
+
16
+ class ProtocolError(ValueError):
17
+ """Raised when frame encoding or ACK decoding fails."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Ack:
22
+ seq: int
23
+ ok: bool
24
+ code: int
25
+
26
+
27
+ def escape_text(text: str) -> str:
28
+ """Escape text for the RubberOrca `type "..."` command."""
29
+ return (
30
+ text.replace("\\", "\\\\")
31
+ .replace('"', '\\"')
32
+ .replace("\n", "\\n")
33
+ .replace("\t", "\\t")
34
+ )
35
+
36
+
37
+ def build_frame(payload: str, seq: int = 1) -> bytes:
38
+ """Encode a command string into an STX/ETX XOR-checked binary frame."""
39
+ data = payload.encode("utf-8")
40
+ if len(data) > PAYLOAD_MAX:
41
+ raise ProtocolError(f"Payload length {len(data)} exceeds PAYLOAD_MAX ({PAYLOAD_MAX})")
42
+ xor = 0
43
+ for b in data:
44
+ xor ^= b
45
+ header = bytes([STX, VERSION, seq & 0xFF, (len(data) >> 8) & 0xFF, len(data) & 0xFF])
46
+ return header + data + bytes([xor, ETX])
47
+
48
+
49
+ def parse_ack(raw: bytes | bytearray) -> Ack:
50
+ """Parse a 6-byte ACK frame `[STX, VER, SEQ, OK, CODE, ETX]`."""
51
+ if len(raw) != ACK_LEN:
52
+ raise ProtocolError(f"Expected {ACK_LEN} ACK bytes, got {len(raw)}")
53
+ if raw[0] != STX or raw[5] != ETX:
54
+ raise ProtocolError(f"Invalid ACK framing: {bytes(raw).hex()}")
55
+ if raw[1] != VERSION:
56
+ raise ProtocolError(f"Unsupported ACK version: {raw[1]}")
57
+ return Ack(seq=raw[2], ok=bool(raw[3]), code=raw[4])
rubberorca/sdk.py ADDED
@@ -0,0 +1,103 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Any, Callable, Optional
5
+
6
+ from .protocol import Ack, escape_text
7
+ from .transport import list_serial_ports, scan_ble, send_command, send_raw_byte
8
+
9
+
10
+ class RubberOrca:
11
+ """High-level Python SDK client for RubberOrca ESP32-S3 USB HID."""
12
+
13
+ def __init__(
14
+ self,
15
+ *,
16
+ port: Optional[str] = None,
17
+ address: Optional[str] = None,
18
+ baud: int = 115200,
19
+ timeout: float = 3.0,
20
+ sender: Callable[..., Ack] = send_command,
21
+ raw_sender: Callable[..., None] = send_raw_byte,
22
+ ) -> None:
23
+ self.port = port
24
+ self.address = address
25
+ self.baud = baud
26
+ self.timeout = timeout
27
+ self._sender = sender
28
+ self._raw_sender = raw_sender
29
+ self._seq = 1
30
+
31
+ def _next_seq(self) -> int:
32
+ seq = self._seq
33
+ self._seq = (self._seq + 1) & 0xFF
34
+ return seq
35
+
36
+ @staticmethod
37
+ def scan(timeout: float = 4.0) -> dict[str, list[tuple[str, str]]]:
38
+ """Discover nearby BLE 0xFFE0 devices and local serial ports."""
39
+ return {
40
+ "ble": asyncio.run(scan_ble(timeout=timeout)),
41
+ "serial": list_serial_ports(),
42
+ }
43
+
44
+ def send(self, command: str) -> Ack:
45
+ return self._sender(
46
+ command,
47
+ port=self.port,
48
+ address=self.address,
49
+ baud=self.baud,
50
+ timeout=self.timeout,
51
+ seq=self._next_seq(),
52
+ )
53
+
54
+ def raw_byte(self, value: int) -> None:
55
+ self._raw_sender(
56
+ value,
57
+ port=self.port,
58
+ address=self.address,
59
+ baud=self.baud,
60
+ timeout=self.timeout,
61
+ )
62
+
63
+ def type(self, text: str) -> Ack:
64
+ return self.send(f'type "{escape_text(text)}"')
65
+
66
+ def delay(self, ms: int) -> Ack:
67
+ return self.send(f"delay {int(ms)}")
68
+
69
+ def key(self, name: str) -> Ack:
70
+ return self.send(name)
71
+
72
+ def press(self, mod: str, ms: Optional[int] = None) -> Ack:
73
+ return self.send(f"press {mod} {int(ms)}" if ms is not None else f"press {mod}")
74
+
75
+ def media(self, action: str) -> Ack:
76
+ return self.send(f"media {action}")
77
+
78
+ def mouse_move(self, dx: int, dy: int) -> Ack:
79
+ return self.send(f"mouse move {int(dx)} {int(dy)}")
80
+
81
+ def mouse_click(self, button: str = "left") -> Ack:
82
+ return self.send(f"mouse click {button}")
83
+
84
+ def mouse_scroll(self, amount: int) -> Ack:
85
+ return self.send(f"mouse scroll {int(amount)}")
86
+
87
+ def jiggler(self, state: str = "toggle") -> Ack:
88
+ return self.send(f"jiggler {state}")
89
+
90
+ def macro_define(self, slot: str, body: str) -> Ack:
91
+ return self.send(f"macro define {slot} {{ {body} }}")
92
+
93
+ def macro_run(self, slot: str) -> Ack:
94
+ return self.send(f"macro run {slot}")
95
+
96
+ def set_ble_name(self, name: str) -> Ack:
97
+ return self.send(f'ble name "{name}"')
98
+
99
+ def set_ble_passkey(self, passkey: str | int) -> Ack:
100
+ return self.send(f"ble passkey {passkey}")
101
+
102
+ def set_layout(self, layout: str) -> Ack:
103
+ return self.send(f"layout {layout}")
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Optional
5
+
6
+ from .protocol import (
7
+ ACK_LEN,
8
+ BLE_CHUNK_SIZE,
9
+ CHAR_UUID,
10
+ SERVICE_UUID,
11
+ Ack,
12
+ ProtocolError,
13
+ build_frame,
14
+ parse_ack,
15
+ )
16
+
17
+
18
+ async def scan_ble(timeout: float = 4.0) -> list[tuple[str, str]]:
19
+ """Return `(address, name)` pairs advertising Service 0xFFE0."""
20
+ from bleak import BleakScanner
21
+
22
+ discovered = await BleakScanner.discover(timeout=timeout, return_adv=True)
23
+ matches: list[tuple[str, str]] = []
24
+ for device, adv in discovered.values():
25
+ uuids = [u.lower() for u in (adv.service_uuids or [])]
26
+ if SERVICE_UUID in uuids:
27
+ matches.append((device.address, device.name or adv.local_name or "Unknown"))
28
+ return matches
29
+
30
+
31
+ def list_serial_ports() -> list[tuple[str, str]]:
32
+ """Return `(device, description)` pairs for available serial ports."""
33
+ from serial.tools import list_ports
34
+
35
+ return [(p.device, p.description) for p in list_ports.comports()]
36
+
37
+
38
+ async def send_ble_frame(
39
+ frame: bytes,
40
+ address: Optional[str] = None,
41
+ timeout: float = 3.0,
42
+ expect_ack: bool = True,
43
+ ) -> Optional[Ack]:
44
+ """Send raw bytes over BLE GATT 0xFFE1 and optionally await a 6-byte ACK."""
45
+ from bleak import BleakClient, BleakScanner
46
+
47
+ target = address
48
+ if not target:
49
+ device = await BleakScanner.find_device_by_filter(
50
+ lambda _d, adv: SERVICE_UUID in [u.lower() for u in (adv.service_uuids or [])],
51
+ timeout=timeout,
52
+ )
53
+ if not device:
54
+ raise RuntimeError("No RubberOrca BLE device found (Service 0xFFE0)")
55
+ target = device
56
+
57
+ ack_event = asyncio.Event()
58
+ rx_buf = bytearray()
59
+
60
+ def on_notify(_sender: object, data: bytearray) -> None:
61
+ rx_buf.extend(data)
62
+ if len(rx_buf) >= ACK_LEN:
63
+ ack_event.set()
64
+
65
+ async with BleakClient(target, timeout=timeout) as client:
66
+ if expect_ack:
67
+ await client.start_notify(CHAR_UUID, on_notify)
68
+
69
+ for i in range(0, len(frame), BLE_CHUNK_SIZE):
70
+ await client.write_gatt_char(CHAR_UUID, frame[i : i + BLE_CHUNK_SIZE], response=False)
71
+
72
+ if not expect_ack:
73
+ return None
74
+
75
+ await asyncio.wait_for(ack_event.wait(), timeout=timeout)
76
+ return parse_ack(rx_buf[:ACK_LEN])
77
+
78
+
79
+ def send_serial_frame(
80
+ frame: bytes,
81
+ port: str,
82
+ baud: int = 115200,
83
+ timeout: float = 3.0,
84
+ expect_ack: bool = True,
85
+ ) -> Optional[Ack]:
86
+ """Send raw bytes over USB CDC Serial and optionally read a 6-byte ACK."""
87
+ import serial
88
+
89
+ with serial.Serial(port, baud, timeout=timeout) as ser:
90
+ ser.reset_input_buffer()
91
+ ser.write(frame)
92
+ ser.flush()
93
+ if not expect_ack:
94
+ return None
95
+ raw = ser.read(ACK_LEN)
96
+ if len(raw) != ACK_LEN:
97
+ raise ProtocolError(f"Timed out waiting for ACK on {port} (got {len(raw)} bytes)")
98
+ return parse_ack(raw)
99
+
100
+
101
+ def send_command(
102
+ command: str,
103
+ *,
104
+ port: Optional[str] = None,
105
+ address: Optional[str] = None,
106
+ baud: int = 115200,
107
+ timeout: float = 3.0,
108
+ seq: int = 1,
109
+ ) -> Ack:
110
+ """Encode and transmit a command over Serial (if `port` given) or BLE."""
111
+ frame = build_frame(command, seq=seq)
112
+ if port:
113
+ ack = send_serial_frame(frame, port=port, baud=baud, timeout=timeout, expect_ack=True)
114
+ else:
115
+ ack = asyncio.run(send_ble_frame(frame, address=address, timeout=timeout, expect_ack=True))
116
+ assert ack is not None
117
+ return ack
118
+
119
+
120
+ def send_raw_byte(
121
+ byte_val: int,
122
+ *,
123
+ port: Optional[str] = None,
124
+ address: Optional[str] = None,
125
+ baud: int = 115200,
126
+ timeout: float = 3.0,
127
+ ) -> None:
128
+ """Send a single-byte fallback command (0x10..0x8F) without framing."""
129
+ if not (0x10 <= byte_val <= 0x8F):
130
+ raise ProtocolError(f"Fallback byte 0x{byte_val:02X} outside 0x10..0x8F")
131
+ raw = bytes([byte_val])
132
+ if port:
133
+ send_serial_frame(raw, port=port, baud=baud, timeout=timeout, expect_ack=False)
134
+ else:
135
+ asyncio.run(send_ble_frame(raw, address=address, timeout=timeout, expect_ack=False))
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: rubberorca
3
+ Version: 0.1.3
4
+ Summary: Python SDK, CLI, and stdio MCP server for RubberOrca ESP32-S3 USB HID over BLE 5.0 GATT and USB CDC Serial.
5
+ Author-email: AtaCanYmc <atacanymc@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AtaCanYmc/RubberOrca
8
+ Project-URL: Repository, https://github.com/AtaCanYmc/RubberOrca
9
+ Project-URL: Issues, https://github.com/AtaCanYmc/RubberOrca/issues
10
+ Keywords: esp32-s3,usb-hid,ble,gatt,mcp,automation,rubberorca
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: System :: Hardware
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: bleak>=0.22
23
+ Requires-Dist: pyserial>=3.5
24
+
25
+ [Back to Root README](../README.md)
26
+
27
+ # RubberOrca Python SDK, CLI, and MCP Server
28
+
29
+ Unified Python package (`rubberorca`) providing a Python SDK, `rubberorca` CLI, and `rubberorca-mcp` stdio MCP server over BLE 5.0 GATT (`0xFFE0` / `0xFFE1`) and USB CDC Serial.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install rubberorca
35
+ # Or editable from source:
36
+ pip install -e ./python
37
+ ```
38
+
39
+ ## Python SDK
40
+
41
+ ```python
42
+ from rubberorca import RubberOrca
43
+
44
+ orca = RubberOrca() # Auto-discovers BLE 0xFFE0 (or pass port="/dev/cu.usbmodem1101")
45
+ orca.type("hello from RubberOrca")
46
+ orca.key("enter")
47
+ orca.set_layout("tr_q")
48
+ orca.jiggler("toggle")
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ ```bash
54
+ # Discover BLE 0xFFE0 devices and local serial ports
55
+ rubberorca scan
56
+
57
+ # Send commands over BLE (default)
58
+ rubberorca type "hello from RubberOrca"
59
+ rubberorca key enter
60
+ rubberorca media play_pause
61
+ rubberorca mouse move 40 -20
62
+ rubberorca jiggler toggle
63
+ rubberorca macro define m0 'type "git status" && enter'
64
+ rubberorca macro run m0
65
+ rubberorca ble-name "OrcaMini"
66
+ rubberorca raw-byte 0x32
67
+
68
+ # Send over USB CDC Serial instead of BLE
69
+ rubberorca --port /dev/cu.usbmodem1101 send 'type "ok" && enter'
70
+ ```
71
+
72
+ ## MCP Server
73
+
74
+ `rubberorca-mcp` exposes RubberOrca tools over stdio JSON-RPC 2.0 with zero extra dependencies (`scan_devices`, `type_text`, `press_key`, `media_control`, `mouse_action`, `jiggler`, `macro_define`, `macro_run`, `send_command`).
75
+
76
+ Example MCP client configuration (`mcp_config.json`):
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "rubberorca": {
82
+ "command": "rubberorca-mcp",
83
+ "args": []
84
+ }
85
+ }
86
+ }
87
+ ```
88
+
89
+ Pass `--port /dev/cu.usbmodem1101` or `--address <BLE_ADDR>` in `args` (or set `RUBBERORCA_PORT` / `RUBBERORCA_ADDRESS`) to pin a specific device.
90
+
91
+ ## Testing
92
+
93
+ ```bash
94
+ python3 -m unittest discover -s python/tests -v
95
+ ```
@@ -0,0 +1,11 @@
1
+ rubberorca/__init__.py,sha256=2fZ9BA6ozGsgsNGG4sdwwZr3e60iEQ7zBISJYg2aRVA,523
2
+ rubberorca/cli.py,sha256=lzGWQY2_2DDju2mpocj7_wdRwknY58qXXeSyhtMUU1U,6871
3
+ rubberorca/mcp_server.py,sha256=o5O7fjcbXfcewC6NsLzwDr2ENTAeWDrD_cgkLLEaHpE,12138
4
+ rubberorca/protocol.py,sha256=5jxHB_AzbtiLMqec7d7F1LW3IMAcllFIolx6GvhsXfI,1639
5
+ rubberorca/sdk.py,sha256=hGCZb2azoxE3_HbfnMpqIX3GergaJdr3qxAxNcQHPYY,3120
6
+ rubberorca/transport.py,sha256=FfzP9yWnomr3o7ZI_oF8QyuCGLHD6QZ8jrOHLkIDDgk,4139
7
+ rubberorca-0.1.3.dist-info/METADATA,sha256=Rn2Hrxv0Yg8soieXxe7K7pdevGLdchOGAr3sPeQLmVA,2826
8
+ rubberorca-0.1.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ rubberorca-0.1.3.dist-info/entry_points.txt,sha256=JMrR18OwAfwzxLgwpx7HB9WpnZF6U1c0fBNIszQ4nPM,95
10
+ rubberorca-0.1.3.dist-info/top_level.txt,sha256=88O2WZH-p-sImz895InbuuDoRVLrhDA2X5-h_T8hsu4,11
11
+ rubberorca-0.1.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ rubberorca = rubberorca.cli:main
3
+ rubberorca-mcp = rubberorca.mcp_server:main
@@ -0,0 +1 @@
1
+ rubberorca