ttypal-ai 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hjp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: ttypal-ai
3
+ Version: 0.1.0
4
+ Summary: Serial port debug tool for humans and AI agents
5
+ License: MIT
6
+ Keywords: serial,uart,debug,embedded,AI,automation
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Topic :: System :: Hardware
12
+ Classifier: Topic :: Software Development :: Embedded Systems
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pyserial>=3.5
17
+ Requires-Dist: tomli-w>=1.0
18
+ Requires-Dist: tomli>=2.0; python_version < "3.11"
19
+ Dynamic: license-file
20
+
21
+ # ttypal
22
+
23
+ Serial port debug tool designed for both humans and AI agents.
24
+
25
+ ## Features
26
+
27
+ - Interactive terminal (like minicom, but better)
28
+ - Auto-logging with timestamps and rotation
29
+ - External command injection via Unix socket (for AI/scripts)
30
+ - Record/replay serial sessions
31
+ - Board config management
32
+ - Claude Code plugin for AI-driven serial debugging
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install ttypal
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```bash
43
+ # Interactive mode
44
+ ttypal
45
+
46
+ # Headless daemon (for AI automation)
47
+ ttypal-daemon start -b myboard
48
+
49
+ # Send commands from another process
50
+ ttypal-send --wait "# " "uname -a"
51
+
52
+ # Read recent serial output
53
+ ttypal-tail -n 50
54
+ ```
55
+
56
+ ## Claude Code Integration
57
+
58
+ ```bash
59
+ claude --plugin-dir /path/to/ttypal
60
+ # Then use /ttypal skill or just ask AI to operate the serial port
61
+ ```
62
+
63
+ ## License
64
+
65
+ MIT
@@ -0,0 +1,45 @@
1
+ # ttypal
2
+
3
+ Serial port debug tool designed for both humans and AI agents.
4
+
5
+ ## Features
6
+
7
+ - Interactive terminal (like minicom, but better)
8
+ - Auto-logging with timestamps and rotation
9
+ - External command injection via Unix socket (for AI/scripts)
10
+ - Record/replay serial sessions
11
+ - Board config management
12
+ - Claude Code plugin for AI-driven serial debugging
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install ttypal
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ # Interactive mode
24
+ ttypal
25
+
26
+ # Headless daemon (for AI automation)
27
+ ttypal-daemon start -b myboard
28
+
29
+ # Send commands from another process
30
+ ttypal-send --wait "# " "uname -a"
31
+
32
+ # Read recent serial output
33
+ ttypal-tail -n 50
34
+ ```
35
+
36
+ ## Claude Code Integration
37
+
38
+ ```bash
39
+ claude --plugin-dir /path/to/ttypal
40
+ # Then use /ttypal skill or just ask AI to operate the serial port
41
+ ```
42
+
43
+ ## License
44
+
45
+ MIT
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ttypal-ai"
7
+ version = "0.1.0"
8
+ description = "Serial port debug tool for humans and AI agents"
9
+ requires-python = ">=3.9"
10
+ license = {text = "MIT"}
11
+ readme = "README.md"
12
+ keywords = ["serial", "uart", "debug", "embedded", "AI", "automation"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Environment :: Console",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Topic :: System :: Hardware",
19
+ "Topic :: Software Development :: Embedded Systems",
20
+ ]
21
+ dependencies = [
22
+ "pyserial>=3.5",
23
+ "tomli-w>=1.0",
24
+ "tomli>=2.0; python_version < '3.11'",
25
+ ]
26
+
27
+ [project.scripts]
28
+ ttypal = "ttypal.main:main"
29
+ ttypal-send = "ttypal.cli_send:main"
30
+ ttypal-tail = "ttypal.cli_tail:main"
31
+ ttypal-daemon = "ttypal.cli_headless:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["ttypal*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,169 @@
1
+ """
2
+ AI 端到端测试:验证通过 socket 发命令能得到正确的设备回复。
3
+ 模拟 AI 的完整工作流:ttypal-send --wait "# " "command"
4
+ """
5
+ import json
6
+ import socket
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from ttypal.replay_backend import ReplayBackend
12
+ from ttypal.logger import Logger
13
+ from ttypal.socket_server import SocketServer
14
+
15
+
16
+ FIXTURES = Path(__file__).parent / "fixtures"
17
+
18
+
19
+ def _start_reader(backend, logger, stop_event):
20
+ """模拟 terminal 的 reader 线程:从串口读数据写入 logger"""
21
+ while not stop_event.is_set():
22
+ data = backend.read()
23
+ if data:
24
+ logger.write(data)
25
+ elif not backend.is_open:
26
+ break
27
+ else:
28
+ time.sleep(0.01)
29
+
30
+
31
+ def _send_request(sock_path, req):
32
+ """通过 socket 发请求,返回响应"""
33
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
34
+ s.connect(sock_path)
35
+ s.sendall(json.dumps(req).encode() + b"\n")
36
+ s.shutdown(socket.SHUT_WR)
37
+
38
+ resp_data = b""
39
+ while True:
40
+ chunk = s.recv(4096)
41
+ if not chunk:
42
+ break
43
+ resp_data += chunk
44
+ s.close()
45
+ return json.loads(resp_data)
46
+
47
+
48
+ def test_ai_send_echo_gets_correct_output(tmp_path):
49
+ """AI 发送 'echo hello',验证返回内容包含 'hello'"""
50
+ backend = ReplayBackend(str(FIXTURES / "basic_commands.rec"), realtime=True)
51
+ backend.open()
52
+
53
+ logger = Logger("ai_test", directory=str(tmp_path / "logs"))
54
+ sock_path = str(tmp_path / "ai.sock")
55
+ srv = SocketServer(backend, logger, sock_path, "# ")
56
+ srv.start()
57
+
58
+ stop = threading.Event()
59
+ reader = threading.Thread(target=_start_reader, args=(backend, logger, stop))
60
+ reader.start()
61
+
62
+ # 等录制前几个 RX 事件播放完(prompt 出现)
63
+ time.sleep(0.3)
64
+
65
+ resp = _send_request(sock_path, {
66
+ "cmd": "send_wait",
67
+ "data": "echo hello",
68
+ "prompt": "# ",
69
+ "timeout": 5,
70
+ })
71
+
72
+ assert resp["status"] == "ok"
73
+ assert "hello" in resp["output"]
74
+
75
+ stop.set()
76
+ srv.stop()
77
+ reader.join(timeout=2)
78
+ logger.close()
79
+
80
+
81
+ def test_ai_send_uname_gets_kernel_info(tmp_path):
82
+ """AI 发送 'uname -a',验证返回内容包含 Linux 内核信息"""
83
+ backend = ReplayBackend(str(FIXTURES / "basic_commands.rec"), realtime=True)
84
+ backend.open()
85
+
86
+ logger = Logger("ai_test2", directory=str(tmp_path / "logs"))
87
+ sock_path = str(tmp_path / "ai2.sock")
88
+ srv = SocketServer(backend, logger, sock_path, "# ")
89
+ srv.start()
90
+
91
+ stop = threading.Event()
92
+ reader = threading.Thread(target=_start_reader, args=(backend, logger, stop))
93
+ reader.start()
94
+
95
+ # 等所有 RX 播放完
96
+ time.sleep(0.5)
97
+
98
+ resp = _send_request(sock_path, {
99
+ "cmd": "send_wait",
100
+ "data": "uname -a",
101
+ "prompt": "# ",
102
+ "timeout": 5,
103
+ })
104
+
105
+ assert resp["status"] == "ok"
106
+ assert "Linux" in resp["output"]
107
+ assert "rockchip" in resp["output"]
108
+
109
+ stop.set()
110
+ srv.stop()
111
+ reader.join(timeout=2)
112
+ logger.close()
113
+
114
+
115
+ def test_ai_send_simple_no_wait(tmp_path):
116
+ """AI 发送命令不等待回复(fire-and-forget),验证命令被发到串口"""
117
+ backend = ReplayBackend(str(FIXTURES / "basic_commands.rec"), realtime=False)
118
+ backend.open()
119
+
120
+ logger = Logger("ai_test3", directory=str(tmp_path / "logs"))
121
+ sock_path = str(tmp_path / "ai3.sock")
122
+ srv = SocketServer(backend, logger, sock_path, "# ")
123
+ srv.start()
124
+
125
+ time.sleep(0.1)
126
+
127
+ resp = _send_request(sock_path, {
128
+ "cmd": "send",
129
+ "data": "reboot",
130
+ })
131
+
132
+ assert resp["status"] == "ok"
133
+ assert b"reboot\r\n" in backend.sent_data
134
+
135
+ srv.stop()
136
+ logger.close()
137
+
138
+
139
+ def test_ai_send_wait_timeout(tmp_path):
140
+ """AI 发命令等待一个不会出现的 prompt,验证超时后仍返回已收集的数据"""
141
+ backend = ReplayBackend(str(FIXTURES / "basic_commands.rec"), realtime=True)
142
+ backend.open()
143
+
144
+ logger = Logger("ai_test4", directory=str(tmp_path / "logs"))
145
+ sock_path = str(tmp_path / "ai4.sock")
146
+ srv = SocketServer(backend, logger, sock_path, "# ")
147
+ srv.start()
148
+
149
+ stop = threading.Event()
150
+ reader = threading.Thread(target=_start_reader, args=(backend, logger, stop))
151
+ reader.start()
152
+
153
+ time.sleep(0.3)
154
+
155
+ resp = _send_request(sock_path, {
156
+ "cmd": "send_wait",
157
+ "data": "ls",
158
+ "prompt": "IMPOSSIBLE_PROMPT>>> ",
159
+ "timeout": 1,
160
+ })
161
+
162
+ # 超时也应该返回 ok 并附带已收集的输出
163
+ assert resp["status"] == "ok"
164
+ assert "output" in resp
165
+
166
+ stop.set()
167
+ srv.stop()
168
+ reader.join(timeout=2)
169
+ logger.close()
@@ -0,0 +1,42 @@
1
+ import os
2
+ import tempfile
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from ttypal.config import (
8
+ load_board, save_board, list_boards, delete_board, DEFAULT_CONFIG,
9
+ )
10
+
11
+
12
+ @pytest.fixture
13
+ def config_dir(tmp_path, monkeypatch):
14
+ monkeypatch.setattr("ttypal.config.CONFIG_DIR", tmp_path)
15
+ return tmp_path
16
+
17
+
18
+ def test_save_and_load(config_dir):
19
+ cfg = {"serial": {"port": "/dev/ttyUSB0", "baudrate": 115200},
20
+ "log": {}, "socket": {}}
21
+ save_board("test1", cfg)
22
+ loaded = load_board("test1")
23
+ assert loaded["serial"]["port"] == "/dev/ttyUSB0"
24
+ assert loaded["serial"]["baudrate"] == 115200
25
+
26
+
27
+ def test_list_boards(config_dir):
28
+ save_board("alpha", DEFAULT_CONFIG)
29
+ save_board("beta", DEFAULT_CONFIG)
30
+ boards = list_boards()
31
+ assert boards == ["alpha", "beta"]
32
+
33
+
34
+ def test_delete_board(config_dir):
35
+ save_board("todelete", DEFAULT_CONFIG)
36
+ assert "todelete" in list_boards()
37
+ delete_board("todelete")
38
+ assert "todelete" not in list_boards()
39
+
40
+
41
+ def test_load_nonexistent(config_dir):
42
+ assert load_board("nope") is None
@@ -0,0 +1,130 @@
1
+ """
2
+ 集成测试:用 ReplayBackend 跑完整链路
3
+ - socket server 接收命令 → 写入串口
4
+ - logger 记录输出
5
+ """
6
+ import json
7
+ import socket
8
+ import threading
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from ttypal.replay_backend import ReplayBackend
13
+ from ttypal.logger import Logger
14
+ from ttypal.socket_server import SocketServer
15
+
16
+
17
+ def _create_recording(tmp_path):
18
+ rec_file = tmp_path / "session.rec"
19
+ # 模拟设备输出 prompt,然后输出命令结果,再输出 prompt
20
+ events = [
21
+ {"t": 0.0, "dir": "rx", "hex": b"root@board:~# ".hex()},
22
+ {"t": 0.5, "dir": "rx", "hex": b"file1 file2\r\n".hex()},
23
+ {"t": 0.6, "dir": "rx", "hex": b"root@board:~# ".hex()},
24
+ ]
25
+ with open(rec_file, "w") as f:
26
+ for e in events:
27
+ f.write(json.dumps(e) + "\n")
28
+ return str(rec_file)
29
+
30
+
31
+ def test_socket_send(tmp_path):
32
+ rec_path = _create_recording(tmp_path)
33
+ backend = ReplayBackend(rec_path, realtime=False)
34
+ backend.open()
35
+
36
+ logger = Logger("integration", directory=str(tmp_path / "logs"))
37
+ sock_path = str(tmp_path / "test.sock")
38
+ srv = SocketServer(backend, logger, sock_path, "# ")
39
+ srv.start()
40
+
41
+ time.sleep(0.1)
42
+
43
+ # send a command
44
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
45
+ s.connect(sock_path)
46
+ req = json.dumps({"cmd": "send", "data": "ls"}) + "\n"
47
+ s.sendall(req.encode())
48
+ s.shutdown(socket.SHUT_WR)
49
+
50
+ resp_data = b""
51
+ while True:
52
+ chunk = s.recv(4096)
53
+ if not chunk:
54
+ break
55
+ resp_data += chunk
56
+ s.close()
57
+
58
+ resp = json.loads(resp_data)
59
+ assert resp["status"] == "ok"
60
+ assert backend.sent_data == b"ls\r\n"
61
+
62
+ srv.stop()
63
+ logger.close()
64
+
65
+
66
+ def test_socket_send_wait(tmp_path):
67
+ # 创建一个带延迟的录制,模拟命令响应
68
+ rec_file = tmp_path / "session2.rec"
69
+ events = [
70
+ {"t": 0.0, "dir": "rx", "hex": b"# ".hex()},
71
+ {"t": 0.2, "dir": "rx", "hex": b"output line\r\n".hex()},
72
+ {"t": 0.3, "dir": "rx", "hex": b"# ".hex()},
73
+ ]
74
+ with open(rec_file, "w") as f:
75
+ for e in events:
76
+ f.write(json.dumps(e) + "\n")
77
+
78
+ backend = ReplayBackend(str(rec_file), realtime=True)
79
+ backend.open()
80
+
81
+ logger = Logger("integration2", directory=str(tmp_path / "logs2"))
82
+ sock_path = str(tmp_path / "test2.sock")
83
+ srv = SocketServer(backend, logger, sock_path, "# ")
84
+ srv.start()
85
+
86
+ time.sleep(0.2)
87
+
88
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
89
+ s.connect(sock_path)
90
+ req = json.dumps({"cmd": "send_wait", "data": "ls", "prompt": "# ", "timeout": 3}) + "\n"
91
+ s.sendall(req.encode())
92
+ s.shutdown(socket.SHUT_WR)
93
+
94
+ resp_data = b""
95
+ while True:
96
+ chunk = s.recv(4096)
97
+ if not chunk:
98
+ break
99
+ resp_data += chunk
100
+ s.close()
101
+
102
+ resp = json.loads(resp_data)
103
+ assert resp["status"] == "ok"
104
+ assert "output" in resp
105
+
106
+ srv.stop()
107
+ logger.close()
108
+
109
+
110
+ def test_logger_captures_replay_output(tmp_path):
111
+ rec_path = _create_recording(tmp_path)
112
+ backend = ReplayBackend(rec_path, realtime=False)
113
+
114
+ logger = Logger("capture_test", directory=str(tmp_path / "logs3"))
115
+ backend.open()
116
+
117
+ time.sleep(0.2)
118
+ while True:
119
+ data = backend.read()
120
+ if not data:
121
+ break
122
+ logger.write(data)
123
+
124
+ logger.close()
125
+
126
+ log_files = list((tmp_path / "logs3" / "capture_test").glob("*.log"))
127
+ assert len(log_files) == 1
128
+ content = log_files[0].read_text()
129
+ assert "root@board" in content
130
+ assert "file1" in content
@@ -0,0 +1,51 @@
1
+ import tempfile
2
+ from pathlib import Path
3
+
4
+ from ttypal.logger import Logger
5
+
6
+
7
+ def test_logger_creates_file(tmp_path):
8
+ logger = Logger("testboard", directory=str(tmp_path), rotate_size_kb=1)
9
+ logger.write(b"hello world\n")
10
+ logger.close()
11
+
12
+ log_files = list((tmp_path / "testboard").glob("*.log"))
13
+ assert len(log_files) == 1
14
+ content = log_files[0].read_text()
15
+ assert "hello world" in content
16
+
17
+
18
+ def test_logger_adds_timestamp(tmp_path):
19
+ logger = Logger("testboard", directory=str(tmp_path),
20
+ timestamp_format="%H:%M:%S")
21
+ logger.write(b"line1\n")
22
+ logger.close()
23
+
24
+ content = (tmp_path / "testboard").glob("*.log").__next__().read_text()
25
+ # timestamp format: [HH:MM:SS]
26
+ assert content.startswith("[")
27
+ assert "] line1\n" in content
28
+
29
+
30
+ def test_logger_rotation(tmp_path):
31
+ logger = Logger("testboard", directory=str(tmp_path), rotate_size_kb=1)
32
+ # Write more than 1KB to trigger rotation
33
+ for i in range(200):
34
+ logger.write(f"{'x' * 100}\n".encode())
35
+ logger.close()
36
+
37
+ log_files = list((tmp_path / "testboard").glob("*.log"))
38
+ assert len(log_files) > 1
39
+
40
+
41
+ def test_logger_multiline(tmp_path):
42
+ logger = Logger("testboard", directory=str(tmp_path),
43
+ timestamp_format="%S")
44
+ logger.write(b"a\nb\nc\n")
45
+ logger.close()
46
+
47
+ content = (tmp_path / "testboard").glob("*.log").__next__().read_text()
48
+ lines = content.strip().split("\n")
49
+ assert len(lines) == 3
50
+ for line in lines:
51
+ assert line.startswith("[")
@@ -0,0 +1,53 @@
1
+ import json
2
+ import tempfile
3
+ from pathlib import Path
4
+
5
+ from ttypal.recorder import Recorder
6
+
7
+
8
+ def test_record_and_load(tmp_path):
9
+ rec_file = tmp_path / "test.rec"
10
+ recorder = Recorder(output_path=str(rec_file))
11
+
12
+ recorder.record_rx(b"hello")
13
+ recorder.record_tx(b"world")
14
+ recorder.close()
15
+
16
+ events = Recorder.load(str(rec_file))
17
+ assert len(events) == 2
18
+ assert events[0]["dir"] == "rx"
19
+ assert events[0]["hex"] == b"hello".hex()
20
+ assert events[1]["dir"] == "tx"
21
+ assert events[1]["hex"] == b"world".hex()
22
+ assert events[1]["t"] >= events[0]["t"]
23
+
24
+
25
+ def test_ring_buffer(tmp_path):
26
+ recorder = Recorder(ring_size=5)
27
+ for i in range(10):
28
+ recorder.record_rx(bytes([i]))
29
+ ring = recorder.get_ring()
30
+ assert len(ring) == 5
31
+ assert ring[0]["hex"] == bytes([5]).hex()
32
+ assert ring[-1]["hex"] == bytes([9]).hex()
33
+
34
+
35
+ def test_empty_data_ignored(tmp_path):
36
+ rec_file = tmp_path / "test.rec"
37
+ recorder = Recorder(output_path=str(rec_file))
38
+ recorder.record_rx(b"")
39
+ recorder.record_tx(b"")
40
+ recorder.close()
41
+
42
+ events = Recorder.load(str(rec_file))
43
+ assert len(events) == 0
44
+
45
+
46
+ def test_record_tx_string(tmp_path):
47
+ rec_file = tmp_path / "test.rec"
48
+ recorder = Recorder(output_path=str(rec_file))
49
+ recorder.record_tx("ls\r\n")
50
+ recorder.close()
51
+
52
+ events = Recorder.load(str(rec_file))
53
+ assert events[0]["hex"] == b"ls\r\n".hex()