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
@@ -0,0 +1,3 @@
|
|||||||
|
result
|
||||||
|
__pycache__/
|
||||||
|
ir-pico/cache/
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Contributing to pdtv26
|
||||||
|
|
||||||
|
The [README](README.md) says what pdtv26 does and why; this is how to work on it.
|
||||||
|
|
||||||
|
## Working on it
|
||||||
|
|
||||||
|
The tools come from the flake: `nix develop --command make test` in any folder, or `nix develop` once and then `make`. `nix flake check` runs every folder's tests. `make help` in each folder lists what it does, and each module's docstring says what it is. Docs are only for what isn't code, such as [wiring](ir-pico/wiring.md).
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@@ -20,3 +20,13 @@ Agent: Here's the game. It started ten minutes ago.
|
|||||||
```
|
```
|
||||||
|
|
||||||
The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind two **Power** buttons, the **Input** button, and the cable box's remote. Our elders have done their share; let the agent do this.
|
The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind two **Power** buttons, the **Input** button, and the cable box's remote. Our elders have done their share; let the agent do this.
|
||||||
|
|
||||||
|
## Parts
|
||||||
|
|
||||||
|
The agent is built from parts you can buy and solder:
|
||||||
|
|
||||||
|
- **The IR emitter:** a Raspberry Pi Pico H with an IR transceiver ([wiring](ir-pico/wiring.md)), on a USB cord, aimed at the equipment.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[Apache 2.0](LICENSE)
|
||||||
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1796098639,
|
||||||
|
"narHash": "sha256-1y2szwdr6vwZPJjJIPUh8pK+OFvCTaKpjpRpqIEb+dA=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "8c5f4a7eea85fbc561588082cbc4da65305f3cda",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-26.05",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
description = "Peace and dignity at the TV: delegating the remotes to an agent";
|
||||||
|
|
||||||
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs }:
|
||||||
|
let
|
||||||
|
systems = [ "x86_64-linux" "aarch64-linux" ];
|
||||||
|
forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
|
||||||
|
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]);
|
||||||
|
in
|
||||||
|
{
|
||||||
|
# nix develop --command make test
|
||||||
|
devShells = forAll (pkgs: {
|
||||||
|
default = pkgs.mkShellNoCC {
|
||||||
|
packages = [ (python pkgs) pkgs.gnumake pkgs.gawk pkgs.curl pkgs.picocom ];
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
checks = forAll (pkgs: {
|
||||||
|
ir-pico = pkgs.runCommand "ir-pico-doctests" { nativeBuildInputs = [ (python pkgs) ]; } ''
|
||||||
|
cd ${./ir-pico}
|
||||||
|
python3 -I -m doctest ir_commands.py pico_tty.py
|
||||||
|
touch $out
|
||||||
|
'';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# ir-pico: a Raspberry Pi Pico H that drives an IR transceiver, so a computer on USB
|
||||||
|
# can learn a remote's codes and send them. Wiring: wiring.md.
|
||||||
|
# Tools come from the flake: nix develop --command make test
|
||||||
|
#
|
||||||
|
# flash and install copy files to the Pico's drives, which a desktop automounts
|
||||||
|
# under /run/media/$USER (or set MEDIA=). console, listen, send, and pulses talk
|
||||||
|
# to it over USB serial: TTY=/dev/serial/by-id/usb-Raspberry_Pi_Pico_... names one
|
||||||
|
# Pico for good; the default, /dev/ttyACM0, is whichever came first.
|
||||||
|
#
|
||||||
|
# hold BOOTSEL, plug in the Pico, then:
|
||||||
|
# make flash install
|
||||||
|
|
||||||
|
CP_VERSION = 10.3.2
|
||||||
|
BOARD = raspberry_pi_pico
|
||||||
|
UF2 = adafruit-circuitpython-$(BOARD)-en_US-$(CP_VERSION).uf2
|
||||||
|
UF2_URL = https://downloads.circuitpython.org/bin/$(BOARD)/en_US/$(UF2)
|
||||||
|
MEDIA = /run/media/$(USER)
|
||||||
|
BOOT = $(MEDIA)/RPI-RP2
|
||||||
|
CIRCUITPY = $(MEDIA)/CIRCUITPY
|
||||||
|
|
||||||
|
IRREMOTE_VERSION = 5.0.8
|
||||||
|
IRREMOTE_URL = https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_IRRemote/$(IRREMOTE_VERSION)/adafruit_irremote.py
|
||||||
|
TTY = /dev/ttyACM0
|
||||||
|
SECONDS = 20
|
||||||
|
CODE = 20 DF 10 EF
|
||||||
|
|
||||||
|
.PHONY: help flash check install console listen send pulses test
|
||||||
|
.DELETE_ON_ERROR:
|
||||||
|
|
||||||
|
## list targets
|
||||||
|
help:
|
||||||
|
@awk -f ../make-help.awk $(MAKEFILE_LIST)
|
||||||
|
|
||||||
|
## download the CircuitPython firmware (once; kept in cache/)
|
||||||
|
cache/$(UF2):
|
||||||
|
mkdir -p cache
|
||||||
|
curl -fsSL -o $@ $(UF2_URL)
|
||||||
|
sha256sum $@
|
||||||
|
|
||||||
|
## copy CircuitPython onto the Pico in BOOTSEL mode; it reboots as CIRCUITPY
|
||||||
|
flash: cache/$(UF2)
|
||||||
|
test -f $(BOOT)/INFO_UF2.TXT || { echo "no $(BOOT): hold BOOTSEL and plug in the Pico" >&2; exit 1; }
|
||||||
|
cp $< $(BOOT)/ && sync
|
||||||
|
|
||||||
|
## the Pico as CircuitPython: its drive, version, and serial port
|
||||||
|
check:
|
||||||
|
cat $(CIRCUITPY)/boot_out.txt
|
||||||
|
ls -l /dev/serial/by-id/ | grep -i pico
|
||||||
|
|
||||||
|
## download the IR remote library (once; kept in cache/)
|
||||||
|
cache/adafruit_irremote-$(IRREMOTE_VERSION).py:
|
||||||
|
mkdir -p cache
|
||||||
|
curl -fsSL -o $@ $(IRREMOTE_URL)
|
||||||
|
sha256sum $@
|
||||||
|
|
||||||
|
## copy code.py and its library onto CIRCUITPY; the Pico restarts it
|
||||||
|
install: code.py ir_commands.py cache/adafruit_irremote-$(IRREMOTE_VERSION).py
|
||||||
|
test -d $(CIRCUITPY) || { echo "no $(CIRCUITPY)" >&2; exit 1; }
|
||||||
|
mkdir -p $(CIRCUITPY)/lib
|
||||||
|
cp cache/adafruit_irremote-$(IRREMOTE_VERSION).py $(CIRCUITPY)/lib/adafruit_irremote.py
|
||||||
|
cp ir_commands.py $(CIRCUITPY)/ir_commands.py
|
||||||
|
cp code.py $(CIRCUITPY)/code.py && sync
|
||||||
|
|
||||||
|
## talk to code.py over USB serial (needs the dialout group); quit: C-a C-x
|
||||||
|
console:
|
||||||
|
picocom -b 115200 $(TTY)
|
||||||
|
|
||||||
|
## print the codes code.py hears for SECONDS (default 20)
|
||||||
|
listen:
|
||||||
|
python3 -I pico_tty.py $(TTY) listen $(SECONDS)
|
||||||
|
|
||||||
|
## send CODE once (default: a Vizio TV's Power, which toggles it)
|
||||||
|
send:
|
||||||
|
python3 -I pico_tty.py $(TTY) send $(CODE)
|
||||||
|
|
||||||
|
## count raw IR pulses on GP16 for SECONDS, decoder bypassed: is the receiver wired?
|
||||||
|
pulses:
|
||||||
|
python3 -I pico_tty.py $(TTY) pulses $(SECONDS)
|
||||||
|
|
||||||
|
## doctests for the plain-Python parts; no Pico needed
|
||||||
|
test:
|
||||||
|
python3 -I -m doctest ir_commands.py pico_tty.py && echo doctests pass
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""IR remote on a Pico: learn codes from a remote, and send them.
|
||||||
|
|
||||||
|
Runs under CircuitPython (make install copies it to CIRCUITPY). Talks over
|
||||||
|
the USB serial console (make console):
|
||||||
|
|
||||||
|
- Point a remote at the receiver and press a button: it prints the code,
|
||||||
|
e.g. ``got 20 DF 10 EF``.
|
||||||
|
- Type ``send 20 DF 10 EF`` and Enter: the emitter sends that code (NEC timing).
|
||||||
|
Samsung codes carry their name: ``got samsung E0 E0 40 BF``, ``send samsung E0 E0 40 BF``.
|
||||||
|
- Any other remote (Sony's, ...) comes back raw, mark and space lengths in us:
|
||||||
|
``got raw 2400 600 1200 ...``; ``send raw 2400 600 1200 ...`` plays it back,
|
||||||
|
three frames 45 ms apart, as a short press of the button does.
|
||||||
|
The carrier is 38 kHz for all; Sony's 40 kHz receivers take it, a bit less keenly.
|
||||||
|
|
||||||
|
Wiring, IR board (STEMMA JST PH) to Pico, as wiring.md lays it out:
|
||||||
|
VIN -> 3V3(OUT) (pin 36) GND -> GND (pin 38)
|
||||||
|
IR In (send) -> GP15 (pin 20) IR Out (receive) -> GP16 (pin 21)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import array
|
||||||
|
import time
|
||||||
|
|
||||||
|
import board
|
||||||
|
import pulseio
|
||||||
|
import supervisor
|
||||||
|
|
||||||
|
import adafruit_irremote
|
||||||
|
|
||||||
|
from ir_commands import RAW_FRAMES, RAW_PERIOD_S, code_text, parse_send, protocol_of, raw_pulses
|
||||||
|
|
||||||
|
SEND_PIN = board.GP15
|
||||||
|
RECEIVE_PIN = board.GP16
|
||||||
|
|
||||||
|
# NEC: 9 ms header mark, 4.5 ms space; 560 us marks; 1 = 1690 us space.
|
||||||
|
NEC = adafruit_irremote.GenericTransmit(
|
||||||
|
header=[9000, 4500], one=[560, 1690], zero=[560, 560], trail=560
|
||||||
|
)
|
||||||
|
# Samsung32: NEC's bits behind a 4.5 ms mark, 4.5 ms space header.
|
||||||
|
SAMSUNG = adafruit_irremote.GenericTransmit(
|
||||||
|
header=[4500, 4500], one=[560, 1690], zero=[560, 560], trail=560
|
||||||
|
)
|
||||||
|
SENDERS = {"nec": NEC, "samsung": SAMSUNG}
|
||||||
|
|
||||||
|
|
||||||
|
def heard(message):
|
||||||
|
"""What to print for a burst: its code, raw pulses, or None (noise, NEC repeats)."""
|
||||||
|
if isinstance(message, adafruit_irremote.NECRepeatIRMessage):
|
||||||
|
return None
|
||||||
|
if isinstance(message, adafruit_irremote.IRMessage):
|
||||||
|
protocol = protocol_of(message.pulses)
|
||||||
|
if protocol != "raw":
|
||||||
|
return "got " + code_text(protocol, message.code)
|
||||||
|
elif len(message.pulses) < 10:
|
||||||
|
return "unparsed: " + message.reason + " " + str(len(message.pulses)) + " pulses"
|
||||||
|
return "got " + code_text("raw", raw_pulses(message.pulses))
|
||||||
|
|
||||||
|
|
||||||
|
def send_raw(pulseout, pulses):
|
||||||
|
durations = array.array("H", pulses)
|
||||||
|
gap = max(RAW_PERIOD_S - sum(pulses) / 1e6, 0.01)
|
||||||
|
for i in range(RAW_FRAMES):
|
||||||
|
if i:
|
||||||
|
time.sleep(gap)
|
||||||
|
pulseout.send(durations)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
pulsein = pulseio.PulseIn(RECEIVE_PIN, maxlen=200, idle_state=True)
|
||||||
|
pulseout = pulseio.PulseOut(SEND_PIN, frequency=38000, duty_cycle=2**15)
|
||||||
|
decoder = adafruit_irremote.NonblockingGenericDecode(pulsein)
|
||||||
|
print("ir-pico ready: press a remote button, or type: send 20 DF 10 EF")
|
||||||
|
while True:
|
||||||
|
for message in decoder.read():
|
||||||
|
line = heard(message)
|
||||||
|
if line:
|
||||||
|
print(line)
|
||||||
|
if supervisor.runtime.serial_bytes_available:
|
||||||
|
line = input()
|
||||||
|
try:
|
||||||
|
data = parse_send(line)
|
||||||
|
except ValueError as err:
|
||||||
|
print("bad code:", err)
|
||||||
|
continue
|
||||||
|
if data is None:
|
||||||
|
print("say: send [samsung] XX XX ..., or send raw MARK SPACE MARK ...")
|
||||||
|
continue
|
||||||
|
protocol, data = data
|
||||||
|
pulsein.pause() # don't hear our own echo
|
||||||
|
if protocol == "raw":
|
||||||
|
send_raw(pulseout, data)
|
||||||
|
else:
|
||||||
|
SENDERS[protocol].transmit(pulseout, data)
|
||||||
|
pulsein.clear()
|
||||||
|
pulsein.resume()
|
||||||
|
print("sent", code_text(protocol, data))
|
||||||
|
|
||||||
|
|
||||||
|
main()
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Plain-Python parts of the IR remote: no hardware, so they test anywhere.
|
||||||
|
|
||||||
|
A code carries its protocol, in the same form both ways (what ``got`` prints,
|
||||||
|
``send`` takes): NEC bare (``20 DF 10 EF``), the rest by name
|
||||||
|
(``samsung E0 E0 40 BF``, ``raw 2400 600 1200 ...``).
|
||||||
|
"""
|
||||||
|
|
||||||
|
PROTOCOLS = ("nec", "samsung", "raw")
|
||||||
|
MAX_RAW = 199 # PulseIn keeps 200
|
||||||
|
# Sony's devices want 3 frames per press, and other protocols take repeats as a held
|
||||||
|
# button, so one raw send is 3 frames: one short press.
|
||||||
|
RAW_FRAMES = 3
|
||||||
|
RAW_PERIOD_S = 0.045 # frame to frame, as Sony's remotes do
|
||||||
|
|
||||||
|
|
||||||
|
def protocol_of(pulses):
|
||||||
|
"""Tell NEC from Samsung by the header mark and space, in microseconds; anything else is raw.
|
||||||
|
|
||||||
|
The two share bit timing: NEC's header mark is 9 ms; Samsung's is 4.5 ms, then
|
||||||
|
a 4.5 ms space.
|
||||||
|
|
||||||
|
>>> protocol_of([9050, 4480, 560])
|
||||||
|
'nec'
|
||||||
|
>>> protocol_of([4520, 4470, 560])
|
||||||
|
'samsung'
|
||||||
|
|
||||||
|
Sony's 2.4 ms header used to pass for Samsung's:
|
||||||
|
|
||||||
|
>>> protocol_of([2390, 610, 1200])
|
||||||
|
'raw'
|
||||||
|
"""
|
||||||
|
if pulses[0] > 6750:
|
||||||
|
return "nec"
|
||||||
|
if pulses[0] > 3500 and pulses[1] > 3500:
|
||||||
|
return "samsung"
|
||||||
|
return "raw"
|
||||||
|
|
||||||
|
|
||||||
|
def raw_pulses(pulses):
|
||||||
|
"""A burst as a raw code sends it: to the nearest 10 us, ending on a mark.
|
||||||
|
|
||||||
|
A raw code is the burst's mark and space lengths in microseconds, mark first.
|
||||||
|
Sent back, it needs no protocol.
|
||||||
|
|
||||||
|
>>> raw_pulses([2394, 606, 1203, 597, 598, 12])
|
||||||
|
[2390, 610, 1200, 600, 600]
|
||||||
|
"""
|
||||||
|
out = [max(10, int(round(p / 10)) * 10) for p in pulses[:MAX_RAW]]
|
||||||
|
return out if len(out) % 2 else out[:-1]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_send(line):
|
||||||
|
"""Parse a ``send`` command into its protocol and the bytes (or, raw, pulses) to transmit.
|
||||||
|
|
||||||
|
>>> parse_send("send 20 DF 10 EF")
|
||||||
|
('nec', [32, 223, 16, 239])
|
||||||
|
>>> parse_send("send samsung E0 E0 40 BF")
|
||||||
|
('samsung', [224, 224, 64, 191])
|
||||||
|
>>> parse_send("send raw 2400 600 1200")
|
||||||
|
('raw', [2400, 600, 1200])
|
||||||
|
>>> parse_send("send samsung") is None
|
||||||
|
True
|
||||||
|
>>> parse_send("hello") is None
|
||||||
|
True
|
||||||
|
|
||||||
|
A raw burst starts and ends on a mark, and each length fits PulseOut's 16 bits:
|
||||||
|
|
||||||
|
>>> parse_send("send raw 2400 600")
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: raw: an odd number of pulses, 1 to 199
|
||||||
|
>>> parse_send("send raw 70000")
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: raw: each 1 to 65535 us
|
||||||
|
"""
|
||||||
|
words = line.split()
|
||||||
|
if len(words) < 2 or words[0] != "send":
|
||||||
|
return None
|
||||||
|
protocol = "nec"
|
||||||
|
if words[1] in PROTOCOLS:
|
||||||
|
protocol, words = words[1], words[1:]
|
||||||
|
if len(words) < 2:
|
||||||
|
return None
|
||||||
|
if protocol != "raw":
|
||||||
|
return protocol, [int(w, 16) for w in words[1:]]
|
||||||
|
pulses = [int(w) for w in words[1:]]
|
||||||
|
if len(pulses) % 2 == 0 or len(pulses) > MAX_RAW:
|
||||||
|
raise ValueError("raw: an odd number of pulses, 1 to %d" % MAX_RAW)
|
||||||
|
if not all(0 < p < 65536 for p in pulses):
|
||||||
|
raise ValueError("raw: each 1 to 65535 us")
|
||||||
|
return protocol, pulses
|
||||||
|
|
||||||
|
|
||||||
|
def hex_bytes(data):
|
||||||
|
"""Format bytes as the console shows them.
|
||||||
|
|
||||||
|
>>> hex_bytes((32, 223, 16, 239))
|
||||||
|
'20 DF 10 EF'
|
||||||
|
"""
|
||||||
|
return " ".join("%02X" % b for b in data)
|
||||||
|
|
||||||
|
|
||||||
|
def code_text(protocol, data):
|
||||||
|
"""A code as listen reports it and send takes it: NEC bare, others named.
|
||||||
|
|
||||||
|
>>> code_text("nec", (32, 223, 16, 239))
|
||||||
|
'20 DF 10 EF'
|
||||||
|
>>> code_text("samsung", (224, 224, 103, 152))
|
||||||
|
'samsung E0 E0 67 98'
|
||||||
|
>>> code_text("raw", [2400, 600, 1200])
|
||||||
|
'raw 2400 600 1200'
|
||||||
|
"""
|
||||||
|
if protocol == "raw":
|
||||||
|
return "raw " + " ".join(str(p) for p in data)
|
||||||
|
return hex_bytes(data) if protocol == "nec" else protocol + " " + hex_bytes(data)
|
||||||
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()
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Wiring the IR emitter
|
||||||
|
|
||||||
|
A Raspberry Pi Pico H drives an Adafruit IR transceiver, so a computer on USB can learn a remote's codes and send them. The pins here must match [code.py](code.py)'s.
|
||||||
|
|
||||||
|
## Parts
|
||||||
|
|
||||||
|
- [Adafruit IR remote transceiver](https://www.adafruit.com/product/5990) (5990): a 940 nm emitter and a 38 kHz receiver, STEMMA JST PH 2 mm
|
||||||
|
- Raspberry Pi Pico H: the H has its headers soldered on
|
||||||
|
- a breakaway 0.1" header strip: 4 pins for the IR board
|
||||||
|
- a breadboard and 4 female-to-female jumpers, or short wires soldered direct, with heat shrink, for something more compact
|
||||||
|
- a micro-USB **data** cable: a charge-only cable gives power but no serial port
|
||||||
|
|
||||||
|
No soldering at all, by mail: Adafruit's [JST PH 2 mm 4-pin to female socket cable](https://www.adafruit.com/product/3950) (3950) in place of the header pins and jumpers. Not a STEMMA QT or Qwiic cable: that's JST SH, 1 mm, and won't fit.
|
||||||
|
|
||||||
|
## On a breadboard
|
||||||
|
|
||||||
|
The Pico H plugs straight in, straddling the center gap. The IR board needs 4 pins first: snap 4 off the breakaway header strip, plug their long ends into the breadboard, set the board on them, and solder.
|
||||||
|
|
||||||
|
Breadboard held long side horizontal: columns 1–30 across, rows a–j down, the gap between e and f. Each column's a–e is one strip, and f–j another.
|
||||||
|
|
||||||
|
```
|
||||||
|
1 2 3 4 5 ... 20 23 24 25 26
|
||||||
|
a . . . . . . o o o o <- IR board's 4 pins; board off the top edge
|
||||||
|
b . . G . P R . . . .
|
||||||
|
c # # # # # ... # . . . . <- Pico pins 40..21: c1 VBUS, c3 GND, c5 3V3(OUT), c20 GP16
|
||||||
|
d . . . . . . . . . .
|
||||||
|
e . . . . . . . . . .
|
||||||
|
------------------- center gap -------------------
|
||||||
|
f . . . . . .
|
||||||
|
g . . . . . .
|
||||||
|
h # # # # # ... # <- Pico pins 1..20: h20 GP15
|
||||||
|
i . . . . . S
|
||||||
|
j . . . . . .
|
||||||
|
^ Pico's USB end at column 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Four jumpers, from the Pico's strips to the IR board's (read the board's labels for which pin is which):
|
||||||
|
|
||||||
|
| from | Pico pin | to IR board | |
|
||||||
|
|---|---|---|---|
|
||||||
|
| P: b5 | 36, 3V3(OUT) | VIN | power |
|
||||||
|
| G: b3 | 38, GND | GND | |
|
||||||
|
| R: b20 | 21, GP16 | IR Out | receive |
|
||||||
|
| S: i20 | 20, GP15 | IR In | send; crosses the gap |
|
||||||
|
|
||||||
|
Power is 3.3 V, not 5 V: the Pico's pins can't take 5 V, and the receiver's output may be pulled up to VIN. The emitter reaches less far at 3.3 V; across a room should be fine.
|
||||||
|
|
||||||
|
Then `make flash install` (see [the Makefile](Makefile)), and `make pulses` to see that the receiver is wired: press any remote button at it while it counts.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# make-help.awk
|
||||||
|
#
|
||||||
|
# Purpose:
|
||||||
|
# Generate `make help` output by pairing:
|
||||||
|
# - a comment line: `## Description...`
|
||||||
|
# - the next target line: `target: ...`
|
||||||
|
#
|
||||||
|
# If you think in Python/JS terms:
|
||||||
|
# - `pending_doc` is a small state variable (like a closure var in a parser loop).
|
||||||
|
# - each input line is processed as a record.
|
||||||
|
# - when we see `## ...`, we store it.
|
||||||
|
# - when we see `target:`, we print `target -> stored description` and clear state.
|
||||||
|
|
||||||
|
BEGIN {
|
||||||
|
pending_doc = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
# Capture human-facing docs from lines like:
|
||||||
|
# ## Build the image.
|
||||||
|
/^## / {
|
||||||
|
pending_doc = substr($0, 4)
|
||||||
|
next
|
||||||
|
}
|
||||||
|
|
||||||
|
# Match make targets like:
|
||||||
|
# build: deps...
|
||||||
|
# Ignore special targets (.PHONY etc.) and variable assignments.
|
||||||
|
/^[a-zA-Z0-9_.-]+:/ {
|
||||||
|
if (pending_doc != "") {
|
||||||
|
split($0, parts, ":")
|
||||||
|
target = parts[1]
|
||||||
|
printf " %-12s - %s\n", target, pending_doc
|
||||||
|
pending_doc = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user