-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpi_servo_robot.py
More file actions
131 lines (107 loc) · 4.26 KB
/
pi_servo_robot.py
File metadata and controls
131 lines (107 loc) · 4.26 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
# examples/pi_servo_robot.py
# Raspberry Pi servo robot using the Python SDK
# pip install spraay-rtp[pi]
import asyncio
import os
from dotenv import load_dotenv
load_dotenv()
from rtp import RTPDevice, RTPDeviceConfig, ConnectionConfig, ConnectionType, TaskResult
# ─── Servo Control ────────────────────────────────────────────────
try:
import pigpio
pi = pigpio.pi()
SERVO_PIN = 17
POSITIONS = {
"home": 1500,
"pick": 500,
"place": 2500,
"scan": 1000,
}
async def move_servo(pulse_width: int, hold_ms: int = 1000):
pi.set_servo_pulsewidth(SERVO_PIN, pulse_width)
await asyncio.sleep(hold_ms / 1000)
except ImportError:
# Not on a Pi — simulate servo movements
print("⚠️ pigpio not found — simulating servo movements")
POSITIONS = {"home": 1500, "pick": 500, "place": 2500, "scan": 1000}
async def move_servo(pulse_width: int, hold_ms: int = 1000):
print(f" 🔄 Servo → {pulse_width}μs")
await asyncio.sleep(hold_ms / 1000)
# ─── Device Setup ─────────────────────────────────────────────────
config = RTPDeviceConfig(
name="ServoBot-Pi-01",
description="Raspberry Pi servo arm — Python SDK",
capabilities=["pick", "place", "scan", "move"],
price_per_task="0.01",
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', 'localhost')}:3100/rtp/task",
port=3100,
secret=os.getenv("WEBHOOK_SECRET")
),
tags=["raspberry-pi", "servo", "python", "demo"]
)
device = RTPDevice(config)
# ─── Task Handlers ────────────────────────────────────────────────
@device.on_task("pick")
async def handle_pick(params, task):
print(f"🦾 PICK: {params.get('item', 'item')}")
await task.progress()
await move_servo(POSITIONS["pick"])
await move_servo(POSITIONS["home"])
await task.complete(TaskResult(
success=True,
output=f"Picked {params.get('item', 'item')}"
))
@device.on_task("place")
async def handle_place(params, task):
print(f"📦 PLACE: {params.get('to_location', 'destination')}")
await task.progress()
await move_servo(POSITIONS["place"])
await move_servo(POSITIONS["home"])
await task.complete(TaskResult(
success=True,
output=f"Placed at {params.get('to_location', 'destination')}"
))
@device.on_task("scan")
async def handle_scan(params, task):
print(f"📷 SCAN: {params.get('target', 'target')}")
await task.progress()
await move_servo(POSITIONS["scan"])
await asyncio.sleep(2) # hold for scan
await move_servo(POSITIONS["home"])
await task.complete(TaskResult(
success=True,
output=f"Scanned {params.get('target')}",
data={
"value": f"ITEM-{__import__('random').randint(1000, 9999)}",
"confidence": 0.97
}
))
@device.on_task("move")
async def handle_move(params, task):
angle = min(180, max(0, params.get("angle", 90)))
pulse_width = int(500 + (angle / 180) * 2000)
print(f"🔄 MOVE: {angle}°")
await task.progress()
await move_servo(pulse_width)
await task.complete(TaskResult(
success=True,
output=f"Moved to {angle}°",
data={"angle": angle, "pulse_width": pulse_width}
))
# ─── Main ─────────────────────────────────────────────────────────
async def main():
print("🤖 ServoBot-Pi-01 starting (Python SDK)...")
# Home the servo
await move_servo(POSITIONS["home"])
print("✅ Servo homed")
# Register and start
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())