-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharduino_bridge.py
More file actions
155 lines (118 loc) · 4.88 KB
/
arduino_bridge.py
File metadata and controls
155 lines (118 loc) · 4.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# examples/arduino_bridge.py
# Bridge pattern — Pi runs RTP SDK, forwards commands to Arduino via serial
import asyncio
import os
import serial
from dotenv import load_dotenv
load_dotenv()
from rtp import RTPDevice, RTPDeviceConfig, ConnectionConfig, ConnectionType, TaskResult
SERIAL_PORT = os.getenv("SERIAL_PORT", "/dev/ttyUSB0")
BAUD_RATE = int(os.getenv("BAUD_RATE", "9600"))
# ─── Serial Bridge ────────────────────────────────────────────────
class ArduinoBridge:
def __init__(self, port: str, baud: int):
self.port = port
self.baud = baud
self._serial: serial.Serial | None = None
def connect(self):
self._serial = serial.Serial(self.port, self.baud, timeout=1)
print(f"✅ Serial connected: {self.port} @ {self.baud}")
def send(self, command: str) -> str:
"""Send command and wait for response."""
if not self._serial:
raise RuntimeError("Serial not connected")
self._serial.write(f"{command}\n".encode())
response = self._serial.readline().decode().strip()
return response
async def send_async(self, command: str, timeout: float = 30.0) -> str:
"""Async wrapper for serial send."""
loop = asyncio.get_event_loop()
return await asyncio.wait_for(
loop.run_in_executor(None, self.send, command),
timeout=timeout
)
arduino = ArduinoBridge(SERIAL_PORT, BAUD_RATE)
# ─── Device Setup ─────────────────────────────────────────────────
config = RTPDeviceConfig(
name="ArduinoArm-Bridge-01",
description="Arduino robot arm controlled via Raspberry Pi serial bridge",
capabilities=["pick", "place", "weld", "dispense"],
price_per_task="0.03",
payment_address=os.getenv("WALLET_ADDRESS", ""),
api_key=os.getenv("SPRAAY_API_KEY", ""),
connection=ConnectionConfig(
type=ConnectionType.WEBHOOK,
webhook_url=f"http://{os.getenv('PUBLIC_IP')}:3100/rtp/task",
port=3100
),
tags=["arduino", "bridge", "serial", "arm"]
)
device = RTPDevice(config)
# ─── Task Handlers ────────────────────────────────────────────────
@device.on_task("pick")
async def handle_pick(params, task):
location = params.get("from_location", "default")
print(f"🦾 Forwarding PICK to Arduino: {location}")
await task.progress()
response = await arduino.send_async(f"PICK:{location}")
if response == "DONE":
await task.complete(TaskResult(
success=True,
output=f"Arduino picked from {location}"
))
else:
await task.fail(f"Arduino error: {response}")
@device.on_task("place")
async def handle_place(params, task):
location = params.get("to_location", "default")
print(f"📦 Forwarding PLACE to Arduino: {location}")
await task.progress()
response = await arduino.send_async(f"PLACE:{location}")
if response == "DONE":
await task.complete(TaskResult(
success=True,
output=f"Arduino placed at {location}"
))
else:
await task.fail(f"Arduino error: {response}")
@device.on_task("weld")
async def handle_weld(params, task):
duration = params.get("duration_ms", 2000)
print(f"🔧 Forwarding WELD to Arduino: {duration}ms")
await task.progress()
response = await arduino.send_async(
f"WELD:{duration}", timeout=30.0
)
if response == "DONE":
await task.complete(TaskResult(
success=True,
output=f"Welded for {duration}ms"
))
else:
await task.fail(f"Arduino error: {response}")
@device.on_task("dispense")
async def handle_dispense(params, task):
duration = params.get("duration_ms", 1000)
print(f"💧 Forwarding DISPENSE to Arduino: {duration}ms")
await task.progress()
response = await arduino.send_async(
f"DISPENSE:{duration}", timeout=10.0
)
if response == "DONE":
await task.complete(TaskResult(
success=True,
output=f"Dispensed for {duration}ms"
))
else:
await task.fail(f"Arduino error: {response}")
# ─── Main ─────────────────────────────────────────────────────────
async def main():
print("🤖 Arduino Bridge starting...")
print(f"📡 Serial: {SERIAL_PORT} @ {BAUD_RATE}")
arduino.connect()
result = await device.register()
print(f"📡 Registered: {result['robot_id']}")
print(f"💧 Endpoint: {result['endpoint']}")
await device.listen(3100)
if __name__ == "__main__":
asyncio.run(main())