feat(ir-pico): learn and send IR codes from a Pico on USB
CircuitPython on a Pico H drives an IR transceiver: it prints the code for any remote button it hears, and sends a code it's given, NEC, Samsung, or raw pulses for the rest. pico_tty.py drives it over USB serial. wiring.md says how to put it together. The flake starts here: a dev shell (nix develop --command make test) and a check that runs the doctests. Tested: make install, then make send turned on a Vizio TV. Generated-by: Claude Opus 5.5
This commit is contained in:
1 parent
a06364e041
commit
147bfdc55e
12 files changed
+796
No files matched your search
Executable
+141
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
r"""Talk to the Pico's code.py over USB serial: listen for codes, send one, or count raw pulses.
|
||||
|
||||
Usage:
|
||||
pico_tty.py TTY listen SECONDS print what code.py hears ("got 20 DF 10 EF")
|
||||
pico_tty.py TTY send [samsung] HEX... send one code ("send 20 DF 10 EF"; NEC unless named)
|
||||
pico_tty.py TTY send raw US... send pulses: mark, space, mark... in microseconds
|
||||
pico_tty.py TTY repeat N GAP_MS CODE... send it N times, GAP_MS apart: N presses of a button
|
||||
pico_tty.py TTY pulses SECONDS stop code.py, count raw pulses on GP16, restart it
|
||||
|
||||
>>> send_line(['20', 'df', '10', 'ef'])
|
||||
b'send 20 DF 10 EF\r'
|
||||
>>> send_line(['samsung', 'e0', 'e0', '40', 'bf'])
|
||||
b'send samsung E0 E0 40 BF\r'
|
||||
>>> send_line(['raw', '2400', '600', '1200'])
|
||||
b'send raw 2400 600 1200\r'
|
||||
>>> send_line(['20', 'DFX'])
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
SystemExit: not a byte: DFX
|
||||
>>> send_line(['raw', '2400', '6e2'])
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
SystemExit: not microseconds: 6e2
|
||||
|
||||
Wait for the Pico's confirmations, not a fixed 2 s, so presses can come quickly:
|
||||
|
||||
>>> class Port:
|
||||
... def __init__(self, lines): self.lines = lines
|
||||
... def readline(self): return self.lines.pop(0) if self.lines else b''
|
||||
>>> import io
|
||||
>>> out = io.StringIO()
|
||||
>>> tick = iter(range(100)).__next__
|
||||
>>> confirmations(Port([b'sent 20 DF\r\n', b'got 20 DF\r\n', b'sent 20 DF\r\n']), 2, 5, tick, out)
|
||||
2
|
||||
>>> out.getvalue()
|
||||
'sent 20 DF\ngot 20 DF\nsent 20 DF\n'
|
||||
>>> confirmations(Port([b'bad code: x\r\n']), 1, 3, iter(range(100)).__next__, io.StringIO())
|
||||
0
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
GP16_PULSES = [
|
||||
b'import board, pulseio, time\r',
|
||||
b'pin = pulseio.PulseIn(board.GP16, maxlen=1000, idle_state=True)\r',
|
||||
]
|
||||
|
||||
|
||||
PROTOCOLS = ('nec', 'samsung', 'raw')
|
||||
|
||||
|
||||
def send_line(words):
|
||||
protocol = [words[0]] if words and words[0] in PROTOCOLS else []
|
||||
octets = words[len(protocol):]
|
||||
if protocol == ['raw']:
|
||||
for us in octets:
|
||||
if not us.isdigit() or len(us) > 5:
|
||||
raise SystemExit(f'not microseconds: {us}')
|
||||
return ('send ' + ' '.join(words) + '\r').encode()
|
||||
for o in octets:
|
||||
if len(o) != 2 or any(c not in '0123456789abcdefABCDEF' for c in o):
|
||||
raise SystemExit(f'not a byte: {o}')
|
||||
return ('send ' + ' '.join(protocol + [o.upper() for o in octets]) + '\r').encode()
|
||||
|
||||
|
||||
def lines_for(port, seconds, now, stdout):
|
||||
end = now() + seconds
|
||||
while now() < end:
|
||||
line = port.readline()
|
||||
if line:
|
||||
stdout.write(line.decode(errors='replace').rstrip() + '\n')
|
||||
stdout.flush()
|
||||
|
||||
|
||||
def confirmations(port, count, seconds, now, stdout):
|
||||
"""Echo the Pico's lines until it has said "sent" count times, or seconds pass; return how many."""
|
||||
end = now() + seconds
|
||||
seen = 0
|
||||
while seen < count and now() < end:
|
||||
line = port.readline()
|
||||
if line:
|
||||
text = line.decode(errors='replace').rstrip()
|
||||
stdout.write(text + '\n')
|
||||
stdout.flush()
|
||||
seen += text.startswith('sent ')
|
||||
return seen
|
||||
|
||||
|
||||
def repl(port, cmd, pause):
|
||||
port.write(cmd)
|
||||
pause(0.3)
|
||||
return port.read(4096)
|
||||
|
||||
|
||||
def pulses(port, seconds, pause, stdout):
|
||||
for cmd in [b'\x03', b'\x03', b'\r'] + GP16_PULSES:
|
||||
repl(port, cmd, pause)
|
||||
logging.info('counting pulses for %ss: press a remote button now', seconds)
|
||||
pause(seconds)
|
||||
out = repl(port, b"print('n=', len(pin))\r", pause).decode(errors='replace')
|
||||
counts = [ln for ln in out.splitlines() if ln.startswith('n=')]
|
||||
stdout.write((counts[-1] if counts else repr(out)) + '\n')
|
||||
repl(port, b'pin.deinit()\r', pause)
|
||||
repl(port, b'\x04', pause) # soft reboot: code.py runs again
|
||||
|
||||
|
||||
def main(argv, open_port, now, pause, stdout):
|
||||
[_, tty, verb, *args] = argv
|
||||
port = open_port(tty)
|
||||
if verb == 'listen':
|
||||
logging.info('listening for %ss', args[0])
|
||||
lines_for(port, float(args[0]), now, stdout)
|
||||
elif verb == 'send':
|
||||
port.write(send_line(args))
|
||||
confirmations(port, 1, 2, now, stdout)
|
||||
elif verb == 'repeat':
|
||||
[times, gap_ms, *octets] = args
|
||||
line = send_line(octets)
|
||||
for i in range(int(times)):
|
||||
if i:
|
||||
pause(int(gap_ms) / 1000)
|
||||
port.write(line)
|
||||
confirmations(port, int(times), 2, now, stdout)
|
||||
elif verb == 'pulses':
|
||||
pulses(port, float(args[0]), pause, stdout)
|
||||
else:
|
||||
raise SystemExit(__doc__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
def _script_io():
|
||||
from sys import argv, stdout
|
||||
from time import sleep, time
|
||||
|
||||
import serial
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')
|
||||
main(list(argv), lambda tty: serial.Serial(tty, 115200, timeout=0.5), time, sleep, stdout)
|
||||
|
||||
_script_io()
|
||||
Reference in new issue
Block a user