Author SHA1 Message Date
czcionka e183d23950 Docs and code: translate Polish comments, messages and documentation to English
check / check-without-hardware (push) Successful in 6m45s
- README, CHANGELOG, RELEASE_NOTES, THIRD_PARTY_NOTICES and docs/*.md
  translated to English; cross-markdown anchors updated
- C/C++/Python/shell comments and user-facing messages translated
- identifiers, protocol names, commands and literals unchanged
- native tests re-verified: 24/24 PASS; tpms_frame.py self-test PASS
2026-10-30 18:01:32 +00:00
czcionka 1563e34d05 Dokumentacja: kalibracja cisnienia potwierdzona z autem (260 kPa = 260 kPa)
check / check-without-hardware (push) Successful in 8m36s
2026-10-30 14:19:53 +00:00
czcionka f50d5a365e Protokol: kalibracja pola cisnienia P wg wyswietlacza auta (2,73 kPa/bit)
check / check-without-hardware (push) Failing after 8m35s
2026-10-30 14:09:53 +00:00
czcionka 9f48c13b05 Sen: mikrodrzemki z widocznym mignieciem LED i przycisk BOOT (GPIO0) jako PIN_BUTTON 2026-10-30 14:09:52 +00:00
czcionka 6013a012fc Upload files to "docs"
check / check-without-hardware (push) Successful in 8m2s
2026-10-29 19:57:50 +00:00
czcionka 2746809228 Upload files to "docs"
check / check-without-hardware (push) Successful in 9m15s
2026-10-29 19:29:14 +00:00
czcionka 814b895fdf Upload files to "docs"
check / check-without-hardware (push) Successful in 10m7s
2026-10-29 18:47:01 +00:00
czcionka 2b91875c06 Update .gitea/workflows/check.yml
check / check-without-hardware (push) Successful in 7m28s
2026-10-28 20:13:23 +00:00
czcionka d4eccbc78d CI: upload artefaktow przez fork gitea-upload-artifact (blokada GHES)
check / check-without-hardware (push) Successful in 7m28s
2026-10-28 20:02:46 +00:00
czcionka 7cb2db7051 CI: omin blokade GHES w upload-artifact@v4 dla instancji Gitei
check / check-without-hardware (push) Failing after 7m18s
2026-10-28 19:45:47 +00:00
czcionka e986da3013 CI: instaluj nodejs przed akcjami JS w kontenerze python-slim
check / check-without-hardware (push) Failing after 7m36s
2026-10-28 19:28:35 +00:00
czcionka 9b64a95d18 CI: przypisz check-without-hardware do etykiety runnera ubuntu-24.04
check / check-without-hardware (push) Failing after 52s
2026-10-28 19:19:57 +00:00
czcionka 882962b156 Audyt: poprawki integracji ESP32-S2/CC1101/LM317T i testy regresji
check / check-without-hardware (push) Canceled after 0s
- EXT1 wake: pociagniecia RTC przycisku/LF przed deep sleep (pull-up
  cyfrowy nie dziala przy wylaczonej domenie RTC_PERIPH)
- konsola: odrzucanie NaN/nieskonczonosci; przenosny modul parse z testami
- zasilanie: dzielnik ADC R2 180 kOhm (zakres do ~16 V zamiast nasycania
  ADC powyzej ~11,8 V)
- package_release: merge_bin --flash-freq 80m zgodne z lolin_s2_mini
- tpms_frame.py: saturacja temperatury zgodna z firmware
- testy: sciezka checksum w negatywach, test_parse, poprawny diagram bitow
2026-10-28 19:10:25 +00:00
czcionka d53299ba11 Sprzet: ESP32-S2-MINI, CC1101 SMA, LM317T i zasilanie z zapalniczki
check / check-without-hardware (push) Canceled after 0s
2026-10-28 15:34:33 +00:00
czcionka 40c152afca Sprzet: ESP32-C3 SuperMini i zasilanie LF33CV
check / check-without-hardware (push) Canceled after 0s
2026-10-27 22:35:46 +00:00
czcionka 84078a914f Testy: synchronizuj pelne scenariusze state-machine
check / check-without-hardware (push) Canceled after 0s
check / check-without-hardware (pull_request) Canceled after 0s
2026-10-27 18:18:08 +00:00
czcionka edc6fb1f5f Dokumentacja RC: setup bezpieczenstwo protokol walidacja i release
check / check-without-hardware (push) Canceled after 0s
2026-10-27 18:17:38 +00:00
czcionka 046c6dc26a Dokumentacja RC: Quick Start bezpieczenstwo hardware i HIL
check / check-without-hardware (push) Canceled after 0s
2026-10-27 18:17:27 +00:00
czcionka 1fdb0c7cce Dokumentacja: Quick Start bezpieczenstwo protokol HIL i RC
check / check-without-hardware (push) Canceled after 0s
2026-10-27 18:17:25 +00:00
czcionka 17d2cea3ea Automatyzacja: check_all Docker CI i reprodukowalne artefakty
check / check-without-hardware (push) Canceled after 0s
2026-10-27 18:17:08 +00:00
czcionka d3a061262b Automatyzacja: check_all Docker CI i reprodukowalne artefakty
check / check-without-hardware (push) Canceled after 0s
2026-10-27 18:16:57 +00:00
czcionka af5324cd4a Walidacja RF: 4 nagrania 3 syntetyczne i negatywy 2026-10-27 18:16:44 +00:00
czcionka 72af53003e Walidacja RF: przypiete rtl_433 cztery nagrania i negatywy 2026-10-27 18:16:43 +00:00
czcionka 6d2c620f95 Walidacja RF: przypiete nagrania syntetyka i negatywy 2026-10-27 18:16:34 +00:00
czcionka 78406ecf40 Firmware: NVS UART CC1101 MARCSTATE i bezpieczny RTC 2026-10-27 18:16:32 +00:00
czcionka 2919efd70a Firmware: konfiguracja NVS konsola CC1101 i bezpieczny sen 2026-10-27 18:16:24 +00:00
czcionka 032811a88c Firmware: NVS UART bezpieczny sleep i kontrola CC1101 2026-10-27 18:16:19 +00:00
czcionka d7fc88c227 Testy ramki: cztery nagrania i przypadki negatywne 2026-10-27 18:16:12 +00:00
czcionka 878c576fdc Testy ramek: cztery niezalezne nagrania i przypadki negatywne 2026-10-27 18:16:06 +00:00
czcionka 9160d71d88 Testy: NVS i scenariusze Clone IDs LEARN SINGLE ACC 2026-10-27 18:14:21 +00:00
czcionka 9a4d7f5f73 Build: pelne SHA CC1101 i Werror dla firmware 2026-10-27 18:13:25 +00:00
czcionka 824b1dbf0e Maszyna stanow: przenosny NORMAL LEARN SINGLE z timeoutami 2026-10-27 17:49:34 +00:00
czcionka e2ffb8d8cf Ramka: odrzucaj nieprawidlowe ID i usun zgadywany lowbat 2026-10-27 17:49:04 +00:00
czcionka 3dad173002 Konfiguracja: walidowany i wersjonowany model NVS 2026-10-27 17:48:40 +00:00
54 changed files with 3781 additions and 2334 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
name: check
on:
push:
branches: [main]
pull_request:
jobs:
check-without-hardware:
runs-on: ubuntu-24.04
container: python:3.12.12-slim-bookworm
steps:
# nodejs is needed by the JS actions (checkout, upload-artifact) and must be
# installed before the first "uses" step.
- name: Install build dependencies
run: |
apt-get update
apt-get install -y --no-install-recommends build-essential cmake git libusb-1.0-0-dev librtlsdr-dev pkg-config ca-certificates nodejs
- uses: actions/checkout@v4
- name: Install pinned Python tools
run: pip install --no-cache-dir --disable-pip-version-check -r tools/requirements.txt
- name: All tests without hardware
run: bash ./tools/check_all
- name: Upload validation reports
# The official upload-artifact@v4+ refuses to run outside github.com
# (other instances are treated as GHES), and GITHUB_SERVER_URL from the
# job context overrides the step env, so the env workaround does not
# work. This is a fork recommended by the Gitea community: the official
# v4 code with only isGhes() returning false. Pinned to a commit of the
# v4 branch instead of a floating ref.
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: validation-reports
path: artifacts/validation/
+4
View File
@@ -1,6 +1,10 @@
.pio/
.vscode/
.venv/
.cache/
artifacts/
*.o
*.elf
*.bin
__pycache__/
*.pyc
+129
View File
@@ -0,0 +1,129 @@
# Changelog
## Work in progress after 2.0.0-rc.1
- Micro-naps instead of one long sleep (`config.h`: `NAP_PERIOD_MS`):
the LED blinks approximately every 2 s also between transmissions, and after
every timer wake a blink is visible (`NAP_AWAKE_MS`). Sleep is the remainder
of the period after boot time + window; TX of frames remains on the interval
(sleep counter in RTC memory, `interval` takes effect on the next cycle).
`power_deep_sleep` takes milliseconds. Previously, waking from the timer
turned the LED off in the same `loop()` — the blink lasted a few ms and the
wake-up was invisible.
- Button: the board's BOOT button by default (`PIN_BUTTON = 0`, GPIO0) —
EXT1 behaviour confirmed on hardware. An external button on GPIO3 is
selected with `-DPIN_BUTTON=3`. Note: GPIO0 is a strapping pin (held at
power-up/reset it starts the bootloader). Every button gesture opens a 10 s
console window (per `POWER.md`) — the device does not fall asleep
immediately after, e.g., leaving LEARN/SINGLE. LEARN/SINGLE still do not
sleep (unchanged).
- Calibration of the pressure field `P` against the car display: the rtl_433
scale (2.5 kPa/bit) is not confirmed (the captures have `P=0`), and the car
showed 284 kPa for 260 kPa. The scaling correction
`TPMS_PRESSURE_KPA100_PER_RAW` (273 = 2.73 kPa/bit; `P=95` for 260 kPa) was
applied in the firmware, the Python model, and the `verify_rtl433.py`
expectations. Confirmed on hardware: 260 kPa → 260 kPa on the car display.
- Hardware–firmware integration audit (2026-10-28), consistency of
ESP32-S2-MINI + CC1101 SMA + LM317T:
- EXT1 wake: the RTC pulls for the button and LF are configured before deep
sleep. A digital pull-up (`pinMode`) does not work with the RTC_PERIPH
domain disabled (ESP-IDF documentation), so the wake pins floated and
EXT1 could wake randomly. An external 10 kΩ is also recommended.
- Console: number parsing rejects NaN and infinity (previously
`pressure nan` / `rf freq nan` passed validation; NaN ended up in NVS as
pressure, and `rf freq nan` blocked later writes). The parsing logic was
extracted into the portable `parse` module with native tests.
- Power: ADC divider R2 270 kΩ → 180 kΩ. The previous divider saturated the
ADC (2.5 V full scale) already above about 11.8 V and did not measure the
12 V installation under a 12.6–14.4 V operating range.
- `tools/package_release.sh`: the full `merge_bin` image uses `--flash-freq
80m` consistent with the `lolin_s2_mini` manifest; the previous `40m`
overwrote the bootloader header (80 MHz) with a parameter that differed
from the build.
- `tools/tpms_frame.py`: temperature saturation to 0–255 consistent with
the firmware (temperatures ≤ −19 °C corrupted the frame in the Python
model).
- Tests: the negative checksum case now inverts the whole Manchester cell
(previously it exercised a Manchester violation instead of the sum); a new
`test_parse` suite (ranges, NaN/inf); corrected the bit diagram in
`PROTOCOL.md`.
- Target hardware changed to ESP32-S2-MINI (ESP32-S2FN4R2, e.g.
ARD-ESP32-S2-MINI, board `lolin_s2_mini`); updated the PlatformIO target,
native USB CDC, SPI/button/ADC pinout, and built-in LED polarity
(GPIO15, active HIGH). Supply ADC on GPIO1, optional LF on GPIO14.
`btStop()` is compiled only on chips with Bluetooth — the ESP32-S2 has none.
- CC1101 433 MHz SPI radio module with an SMA connector and antenna
(ARD-CC1101-ANT).
- External power through an adjustable LM317T (TO-220 metal, 1.25–37 V,
1.5 A): the correct ADJ–VOUT–IN pinout, TAB = VOUT, a 240/390 Ω divider
giving about 3.28 V, capacitors, and protection and thermal requirements.
- Target power from the car cigarette-lighter socket: a USB charger (variant
A) or the LM317T (variant B). With an ignition-switched socket the emulator
draws no current while parked; the lack of parking transmission is
acceptable because the car ECU does not read TPMS with the ignition off.
- ESP32-S2 release images use `esptool --chip esp32s2` and a bootloader at
address `0x1000`; older images for ESP32-C3 and ESP32-WROOM are incompatible.
## 2.0.0-rc.1 — 2026-10-27
Release candidate without a physical CC1101 test and a car test.
### Added
- Persistent NVS configuration with versioning, CRC32, range validation,
unique IDs, factory reset, and safe defaults.
- Console: Clone IDs, a new-ID generator, pressures/temperature, intervals,
limited RF, LEARN/SINGLE, and diagnostics without recompilation.
- Portable state machine with fake clock/radio, timeouts, and the
FL→FR→RR→RL order. Restart, ACC, radio-failure, and `millis()` wrap tests.
- Independent validation of four reference recordings and synthetic CU8 with
the pinned rtl_433; negative checksum/Manchester/truncation tests.
- `tools/check_all`, Dockerfile, Gitea Actions, image scripts, and SHA-256.
- User, hardware, power, safety, and HIL documentation.
### Changed
- Defaults of 260 kPa and −10 dBm, OOK only. The 30-byte Manchester encoder
is preserved and passes independent decoding.
- The CC1101 waits for `MARCSTATE=IDLE`, checks underflow and leftover bytes,
instead of relying only on timing and `TXBYTES=0`.
- A plain RTC wake does not open the console window; transmission and the
return to sleep limit the estimated consumption. The console window remains
open after user interaction.
- Full build with `-Wall -Wextra -Werror`; cppcheck with zero defects.
### Removed / fixed
- Removed the guessed `TPMS_FLAGS_LOWBAT_MASK` and the coupling between the
emulator's low supply and the simulated sensor. The supply is only a local
warning.
- Removed FSK from the main flow: no evidence for the analysed profile.
- Removed `PARKING_SHUTDOWN`; every deep sleep has an RTC alarm, so an ACC
restart cannot leave the device permanently asleep.
- The default, unvalidated LF input is disabled. Basic LEARN does not require
the EL-50448.
- Removed the recommendation of MCP1703 + 24 V TVS as automotive protection
and the promises of multi-year battery operation. The 12 V supply has
design requirements, not HIL.
### Audit iterations
1. **Initial state:** 7/7 native and build PASS, but configuration through
recompilation, a monolithic state machine, lowbat, and power needed
repair. Created `archive/pre-opencode`.
2. **Data model:** added NVS/CRC/validation and portable modes. The first
test caught wrong test expectations for a pending tick and immediate TX;
after correction, 20/20 native and the ESP32 build PASS.
3. **RF validation:** an audit of four recordings confirmed 16 repetitions
and variable gaps. A single vector was replaced with the full script;
64/64 references, 3/3 synthetic, and 3/3 negative PASS.
4. **Energy:** a console window after every RTC wake was detected; it was
limited to interaction. Consumption is still clearly marked as estimated.
5. **Static analysis:** cppcheck flagged memset-initialised float structs;
replaced with value initialisation and reached 0 defects.
### Not physically verified
CC1101 on an antenna/analyser, RTL-SDR with the prototype, consumption,
brownout, ACC, a flash update, Clone IDs and LEARN with the specific Opel. No
"validated" label.
+11
View File
@@ -0,0 +1,11 @@
FROM python:3.12.12-slim-bookworm
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential cmake git libusb-1.0-0-dev librtlsdr-dev pkg-config ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /work
COPY tools/requirements.txt tools/requirements.txt
RUN pip install --no-cache-dir --disable-pip-version-check -r tools/requirements.txt
COPY . .
RUN chmod +x tools/check_all tools/*.sh
CMD ["bash", "./tools/check_all"]
+338
View File
@@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+150 -663
View File
@@ -1,694 +1,181 @@
# Symulator 4 czujników TPMS Schrader EG53MA4 (ESP32 + CC1101)
# Schrader EG53MA4 TPMS Simulator — ESP32-S2-MINI + CC1101
Firmware dla ESP32 DevKit + moduł CC1101 (433 MHz), symulujący **4 czujniki
ciśnienia w oponach** (po jednym na koło) dla **Opla Astry J Sedan 2016**
(rynek EU, TPMS bezpośredni, czujniki typu Schrader / Opel OEM 13348393,
protokół **Schrader EG53MA4**).
**Version 2.0.0-rc.1 — release candidate without hardware validation.**
> ## ⚠️ ZASTRZEŻENIE
> Projekt **wyłącznie do celów diagnostycznych i testowych**.
> Symulator dostarcza **sztuczne dane ciśnienia i temperatury** i **nie
> zastępuje prawdziwych czujników TPMS**. TPMS jest elementem bezpieczeństwa
> czynnego pojazdu — **nie używaj tego urządzenia podczas jazdy po drogach
> publicznych**. Nadawanie w paśmie 433 MHz może podlegać lokalnym
> przepisom (np. w Polsce praca krótkiego zasięgu w 433 MHz jest dozwolona
> z ograniczeniami mocy) — sprawdź przepisy obowiązujące w Twoim kraju.
A workshop device that transmits four independent TPMS identifiers with the
OOK/Manchester Schrader EG53MA4 profile on 433.92 MHz. By default each wheel
reports **260 kPa (2.6 bar; protocol byte `0x68`)**. The target scenario is
diagnostics of an Opel Astra J Sedan 1.4 LPG (2016, EU), but **compatibility
must be confirmed for the specific car**: via VIN/service listings, markings of
factory sensors, a diagnostic readout, or a reception test. OE number
13506028, related part numbers, or a listing offer alone do not confirm the
radio profile.
---
> **This is not a homologated sensor nor a replacement for a working TPMS.
> Do not use while driving.** Synthetic pressure can hide a punctured or
> underinflated tyre and delay the warning. Before and after the test, check
> all tyres with an independent gauge. See [SAFETY](docs/SAFETY.md).
## 1. Spis treści
## What is done, and what is not
1. [Spis treści](#1-spis-treści)
2. [Jak to działa](#2-jak-to-działa)
3. [Budowa projektu](#3-budowa-projektu)
4. [Kompilacja](#4-kompilacja)
5. [(a) Okablowanie i lista podzespołów](#5-a-okablowanie)
6. [(b) Konfiguracja ID i ciśnień](#6-b-konfiguracja-id-i-cisnień)
7. [(c) Test nadawania — RTL-SDR + rtl_433](#7-c-test-nadawania--rtl-sdr--rtl_433)
8. [(d) Programowanie czujników w aucie (tryb learn)](#8-d-programowanie-czujników-w-aucie-tryb-learn)
9. [(e) Pomiar poboru prądu](#9-e-pomiar-poboru-prądu)
10. [(f) Weryfikacja, że błąd zniknął](#10-f-weryfikacja-że-błąd-zniknął)
11. [Tryby pracy i sterowanie](#11-tryby-pracy-i-sterowanie)
12. [Konsola szeregowa](#12-konsola-szeregowa)
13. [Budżet prądu](#13-budżet-prądu)
14. [Protokół — szczegóły techniczne](#14-protokół--szczegóły-techniczne)
15. [Rozwiązywanie problemów](#15-rozwiązywanie-problemów)
- Done: ESP32 build, frame/NVS/state-machine tests, synthetic CU8 decoded by
an independent `rtl_433`, persistent configuration from the console, Clone
IDs and LEARN.
- **Not done:** measurement of a real CC1101, RTL-SDR with an antenna, a test
with a car, current measurement, and automotive tests. That is why the
result is RC, not "validated".
- The only base profile is **OOK**. Do not switch to FSK "just to try it".
- The ESP32 does not generate the 433 MHz carrier — a separate CC1101 433 MHz
is required.
---
## Concept sketch
## 2. Jak to działa
```text
Bench prototype:
USB-C ──> [ESP32-S2-MINI] ── SPI ──> [CC1101 433 MHz] ──> SMA antenna
│ │ │
│ └── GPIO0: button (BOOT) └── common GND, 3.3 V only
└── GPIO15: built-in LED (active HIGH)
Urządzenie zachowuje się jak 4 czujniki TPMS Schrader EG53MA4:
Target supply from the car cigarette-lighter socket:
variant A: socket ──> [USB car charger] ──> board USB-C
variant B: socket ──> fuse/TVS ──> [LM317T 3.3 V] ──> 3V3 + CC1101 VCC
* co `TX_INTERVAL_S` (domyślnie 30 s) budzi się z **deep sleep**,
konfiguruje CC1101 i wysyła **burst 3 ramek** dla każdego z 4 kół
(tak jak prawdziwy czujnik, który powtarza pakiet 3–6 razy),
* ramka zawiera: `flags` + 24-bit ID czujnika + ciśnienie (2,5 kPa/bit)
+ temperaturę (°F) + sumę kontrolną — **zgodnie z dekoderem rtl_433
`schrader_EG53MA4`**,
* dane kodowane są Manchesterem **G.E.T. MC** (chip 120 µs),
modulacja **ASK/OOK 433.92 MHz** (opcjonalnie **2-FSK, dewiacja 47.6 kHz**),
* między transmisjami ESP32 śpi (budzik RTC + budzenie przyciskiem lub
wejściem LF), CC1101 jest w trybie SLEEP,
* tryb **LEARN** pozwala wprowadzić ID do pamięci auta po kolei
(przód lewy → przód prawy → tył prawy → tył lewy),
* tryb **SINGLE** wymusza nadawanie jednego wskazanego ID.
Wszystkie dane (ID, ciśnienia, temperatury, interwały) są **sztuczne**
i konfigurowalne w `src/config.h`.
---
## 3. Budowa projektu
```
tpms/
├── platformio.ini # konfiguracja budowania (ESP32 Arduino + testy natywne)
├── src/
│ ├── config.h # <<< WSZYSTKIE USTAWIENIA (ID, piny, interwały) >>>
│ ├── main.cpp # maszyna stanów: NORMAL / LEARN / SINGLE, deep sleep
│ ├── tpms_frame.h/.cpp # generator ramki + kodowanie Manchester (bez Arduino)
│ ├── radio.h/.cpp # konfiguracja CC1101, nadawanie, tryb SLEEP
│ ├── power.h/.cpp # pomiar napięcia, gpio_hold, deep sleep
│ ├── ui.h/.cpp # przycisk (gesty) + LED statusowy
│ ├── console.h/.cpp # konsola szeregowa (debug bez samochodu)
│ └── app.h # API aplikacji (tryby)
├── test/test_tpms_frame/ # testy jednostkowe generatora ramek (native)
└── tools/
├── tpms_frame.py # referencyjna implementacja ramki + self-test
├── gen_cu8.py # synteza nagrania IQ (OOK/FSK) do testów z rtl_433
└── verify_rtl433.sh # automatyczna weryfikacja ramek przez rtl_433
Configuration: USB CDC 115200 → NVS → 4 × {ID, pressure, temperature}
```
Referencje protokołu (źródła, na których oparto kod):
Set the LM317T output with the divider to **3.3 V and connect it to 3V3, not
to 5V**. Do not connect 12 V to GPIO, 3V3, or 5V. When powering from an
external 3.3 V source, disconnect USB unless source separation has been
verified for the specific board revision. In most cars the cigarette-lighter
socket is powered only after the ignition is switched on — **check this in
your own car**. Then the emulator draws no current while parked; the car
computer does not read TPMS state with the ignition off anyway, so lacking
parking transmission does not matter. Full pinout, the LM317T divider, and
capacitors: [HARDWARE](docs/HARDWARE.md).
* `rtl_433/src/devices/schraeder.c` (historycznie: `tpms_schrader.c`) —
dekoder **Schrader TPMS EG53MA4, Saab, Opel, Vauxhall, Chevrolet**
(Opel OEM 13348393): format ramki, checksum, skale ciśnienia/temperatury:
<https://github.com/merbanan/rtl_433>
* `rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01/` — referencyjne nagrania
RF prawdziwych czujników (na ich podstawie odtworzono timing i modulację):
<https://github.com/merbanan/rtl_433_tests>
* <https://github.com/merbanan/rtl_433/issues/2978> — wzorzec struktury
symulatora TPMS na ESP32+CC1101 (inicjalizacja CC1101, Manchester, CRC,
wysyłanie cykliczne)
* <https://github.com/avicarmeli/TPMS-SDR> — okablowanie ESP32↔CC1101,
struktura projektu
## Quick Start
---
### 1. Assemble the prototype
## 4. Kompilacja
Buy the parts from the [BOM](docs/HARDWARE.md#laboratory-prototype-bom).
Connect the CC1101 and the button according to the pin table; the LED is
already on the S2 Mini board. On the bench, power the device through a tested
USB-C cable that carries data. Do not install anything in the car yet.
### PlatformIO (zalecane)
### 2. Install the tools and verify the project
Required: Python 3, Git, CMake, a C/C++ compiler, `pkg-config`, and the
libusb and librtlsdr headers. The easiest way is Docker:
```bash
pio run -e esp32dev # kompilacja
pio run -e esp32dev -t upload # wgrywanie
pio device monitor # monitor szeregowy 115200
pio test -e native # testy generatora ramek (bez sprzętu)
docker build -t tpms-rc .
docker run --rm -v "$PWD/artifacts:/work/artifacts" tpms-rc
```
Biblioteka CC1101 (`SmartRC-CC1101-Driver-Lib`, dawniej
`ELECHOUSE_CC1101_SRC_DRV`) jest pobierana automatycznie z `platformio.ini`
(przypięta do commita zweryfikowanego buildu). **Wymagana wersja ≥ 2.5.7**
(wspólne API `setSpiPin`/`setGDO0` dla 2.5.x i 3.x; starsze 1.x używały
`setSCK`/`setMISO`/... i nie są obsługiwane).
### arduino-cli (alternatywa)
Without Docker, the script creates a `.venv` with PlatformIO, fetches the
pinned `rtl_433`, and the reference recordings:
```bash
arduino-cli core install esp32:esp32
arduino-cli lib install "SmartRC-CC1101-Driver-Lib" # albo: lib ZIP z githuba
arduino-cli compile --fqbn esp32:esp32:esp32 --libraries . .
bash tools/check_all
```
(Utwórz folder `src/` jako szkic albo użyj `--build-property` z
`build.extra_flags`; najwygodniej jednak otworzyć katalog w PlatformIO.)
The last message must read `PASS: all hardware-free tests...`.
It is not a test of physical radio.
### Weryfikacja bez sprzętu (opcjonalna)
### 3. Build and flash
```bash
python3 tools/tpms_frame.py --self-test # zgodność z dekoderem rtl_433
RTL433=rtl_433 ./tools/verify_rtl433.sh # pełne testy z prawdziwym rtl_433
.venv/bin/pio run -e esp32s2mini
.venv/bin/pio run -e esp32s2mini -t upload
.venv/bin/pio device monitor --baud 115200
```
`tools/verify_rtl433.sh` generuje syntetyczne nagrania IQ takie, jakie
odbiornik RTL-SDR zobaczy w eterze, i sprawdza, czy **prawdziwy rtl_433**
dekoduje je jako poprawny czujnik Schrader z oczekiwanym ID/ciśnieniem/
temperaturą. Ostatni wynik testów projektu:
If the port is not detected automatically, add `--upload-port /dev/ttyACM0`
(for `run`) or `--port /dev/ttyACM0` (for `device monitor`). Depending on the
system and USB mode it may also be `/dev/ttyUSB0`. In the PlatformIO monitor,
the exit shortcut is usually `Ctrl+]`. If the upload does not start, hold
**BOOT**, press and release **RESET**, then release BOOT.
```
== OOK (domyslna modulacja, wbudowany dekoder Schrader-EG53MA4) ==
OK c1.cu8 id=2FC871 260.0 kPa 73.0 F
OK c2.cu8 id=3495AC 220.0 kPa 23.0 F
OK c3.cu8 id=ABCDEE 262.5 kPa 75.0 F
== FSK (wariant konfigurowalny, dekoder flex) ==
OK c4.cu8 (FSK) bitstream zgodny: 00000000004c9000702fc871684965
WSZYSTKO OK - ramki dekoduja sie poprawnie przez rtl_433
After startup, type `stay 300` and press Enter. You have 5 minutes to
configure; the `info` command shows active values. Every configuration change
is saved to NVS immediately and survives a restart — **do not edit IDs in
code**.
### 4A. Preferred: Clone IDs
If you know the original 24-bit IDs (e.g. from an earlier `rtl_433` readout),
enter them in FL, FR, RR, RL order. Example — replace the values with your
own:
```text
stay 300
id 1 2FC871
id 2 2EAAF9
id 3 3495AC
id 4 2FC780
pressure all 260
info
send
```
---
## 5. (a) Okablowanie
### Lista podzespołów (BOM) — co kupić
Koszty orientacyjne (zł, z dostawą z AliExpress/Allegro, stan na 2026 r.).
Wystarczy **jedna sztuka** każdego podzespołu.
**Obowiązkowe:**
| Lp. | Podzespół | Parametry / typ | Uwagi | Koszt orient. |
|-----|-----------|-----------------|-------|----------------|
| 1 | ESP32 DevKit (WROOM-32) | moduł ESP32-WROOM-32, USB | Do testów na biurku OK. **Do montażu w aucie kup sam moduł ESP32-WROOM-32E** (bez mostka USB/LDO) + płytkę — patrz sekcja 13 o poborze prądu | 15–30 zł |
| 2 | Moduł CC1101 **433 MHz** | 8-pin, SPI, złącze goldpin | Koniecznie wersja 433 MHz (nie 868/915); dokup/drut antenowy ~17 cm; sprawdzić złącze ANT | 10–25 zł |
| 3 | Przycisk monostabilny | NO, wpuszczany lub panelowy | Tryby pracy (learn/single) | 2–5 zł |
| 4 | LED + rezystor 330 Ω | LED 3 mm/5 mm dowolny kolor | Status trybów | 1–3 zł |
| 5 | Rezystor 10 kΩ | 1 szt. | Podciągnięcie przycisku do 3V3 | < 1 zł |
| 6 | Rezystory 1 MΩ + 270 kΩ | po 2 szt. | Dzielniki pomiaru napięcia i ACC (~9 µA/szt. przy 12 V) | < 1 zł |
| 7 | Kondensatory | 100 µF/16 V elektrolityczny + 2× 100 nF ceramiczny | Odsprzężenie zasilania CC1101 i ESP32 (obowiązkowo przy długich przewodach) | 1–3 zł |
| 8 | Bezpiecznik + uchwyt | 1 A, zwłoczny | Szeregowo z +12 V | 2–5 zł |
| 9 | Przewody, złącza | goldpiny 2,54 mm, kostki, ekran SPI | Przewody SPI możliwie krótkie (< 10 cm) | 5–15 zł |
| 10 | Obudowa | IP65, min. 80×60×30 mm | Montaż w komorze silnika/bagażniku | 10–25 zł |
**Zasilanie — wybierz wariant (konfigurowalne w `config.h`, `POWER_SUPPLY_MODE`):**
| Lp. | Podzespół | Parametry / typ | Uwagi | Koszt orient. |
|-----|-----------|-----------------|-------|----------------|
| 11a | **Wariant 12 V**: LDO 3,3 V o niskim Iq i **wejściu ≥ 16 V** | np. **MCP1703-3302** (Vin 2,7–16 V, Iq ≈ 2 µA) | + zabezpieczenie wejścia: bezpiecznik, **TVS 24 V**, rezystor/dioda szeregowa (przepięcia load-dump!). Sprawdź moc strat: (14,4−3,3) V × ~30 mA ≈ 0,33 W — stosuj obudowę SOT-223/TO-92 i nie przeciążaj | 2–8 zł |
| 11b | **Wariant 12 V** (wydajniejszy): buck o szerokim wejściu | np. **LM5164-Q1** (Vin 6–100 V, Iq ≈ 10 µA, 1 A) lub inny buck automotive | Wymaga cewki i płytki; **TPS62740 (Vin 2,2–5,5 V) i tanie bucki (LM2596, MP1584, Mini360, Iq mA) NIE nadają się do 12 V / snu < 50 µA** | 20–50 zł |
| 12 | **Wariant bateryjny**: ogniwo 3,6 V lub LiPo | Li-SOCl2 3,6 V (AA/half-AA, np. ER14505) + uchwyt **bezposrednio**; LiPo 3,7 V **przez LDO 3,3 V** (np. MCP1700, Vin max 6 V) | **Nie zasilaj LiPo 4,2 V wprost** — max ESP32 to 3,6 V, CC1101 to 3,9 V! | 10–30 zł |
**Opcjonalne (ulepszenia i testy):**
| Lp. | Podzespół | Parametry / typ | Uwagi | Koszt orient. |
|-----|-----------|-----------------|-------|----------------|
| 13 | Front-end LF 125 kHz | cewka rezonansowa (ferrytowa ramka z programatora TPMS), dioda Schottkyego (BAT54/1N5711), 100 pF + 100 kΩ, komparator LM393 | Reakcja na aktywację czujnika programatorem przy kole (`PIN_LF_TRIGGER`) | 10–30 zł |
| 14 | Dzielnik ACC | 1 MΩ + 270 kΩ + 100 nF | Sygnał zapłonu 12 V → GPIO32 (tryb ignition-aware) | < 2 zł |
| 15 | RTL-SDR (dongle) | R820T2/RTL2832U | Testy z `rtl_433` (sekcja 7) — można wypożyczyć | 60–150 zł |
| 16 | Kabel USB + ew. programator | do wgrywania firmware | W DevKit kabel USB-A/Micro-USB wystarczy | 5–15 zł |
**Narzędzia (do pomiarów, sekcja 9):** multimetr z zakresem µA (obowiązkowo do
pomiaru snu), opcjonalnie INA219/INA226 lub oscyloskop do pomiaru prądu w burst.
**Na skróty — zestaw minimalny „na biurko"** (testy RF + nauka): pozycje 1–10
z wariantem 12 V lub zasilaniem z powerbanka 5 V przez DevKit (testy RF nie
wymagają spełnienia budżetu prądu).
Gdzie kupić: AliExpress (CC1101, LM5164, ESP32), Allegro/sklepy elektroniczne
(pasywne elementy, obudowa, bezpieczniki, TVS). Przy zamawianiu CC1101 sprawdź, czy
moduł jest oznaczony **433 MHz** — wersje 868/915 MHz nie zadziałają bez
przestrojenia.
### Podłączenie
| ESP32 DevKit | CC1101 | Uwagi |
|--------------|-------------|----------------------------------------|
| 3V3 | VCC | **3.3 V!** (CC1101 nie toleruje 5 V) |
| GND | GND | masa wspólna |
| GPIO18 | SCK (SCLK) | `PIN_CC1101_SCK` |
| GPIO19 | MISO (SO) | `PIN_CC1101_MISO` |
| GPIO23 | MOSI (SI) | `PIN_CC1101_MOSI` |
| GPIO5 | CS (CSn/SS) | `PIN_CC1101_CS` |
| GPIO2 | GDO0 | `PIN_CC1101_GDO0` |
| — | GDO2 | nieużywany (zostaw odłączony) |
Pozostałe elementy (numery pinów konfigurowalne w `config.h`):
| Element | Pin ESP32 | Podłączenie |
|-------------------------|-----------|------------------------------------------------|
| Przycisk trybów | GPIO26 | GPIO —— przycisk —— GND, rezystor 10 kΩ do 3V3 (aktywny niski, `BTN_ACTIVE_LEVEL 0`) |
| LED statusowy | GPIO27 | GPIO —— 330 Ω —— LED —— GND |
| Wejście LF 125 kHz (opcjonalnie) | GPIO25 | wyjście detektora LF (impuls do 3,3 V), stan spoczynkowy **niski**; bez modułu: ustaw `PIN_LF_TRIGGER -1` |
| ACC / zapłon (opcjonalnie) | GPIO32 | dzielnik 12 V → ~3 V (1 MΩ / 270 kΩ + 100 nF), wejście **INPUT** (bez podciągania); **domyślnie wyłączone** (`PIN_ACC -1`) — ustaw 32 po podłączeniu |
| Pomiar napięcia | GPIO34 | węzeł środkowy dzielnika `R1=1 MΩ / R2=270 kΩ` (ADC1) + 100 nF |
Zasilanie (wybór w `config.h`, `POWER_SUPPLY_MODE`):
```
POWER_12V (na stałe z akumulatora) - UWAGA: zakres samochodowy to nie
same "12 V": 14,4 V przy ladowaniu
i przepięcia load-dump > 40 V:
+12 V ──[bezpiecznik 1 A]──[TVS 24 V do masy]──[rezystor/dioda]── regulator
── 3,3 V ── ESP32 + CC1101
Regulator (wybierz jeden):
- LDO o Iq ~2 µA i wejściu >= 16 V, np. MCP1703-3302
(straty: (14,4-3,3) V x ~30 mA = ~0,33 W - zwróć uwagę na obudowę),
- albo buck automotive o szerokim wejściu, np. LM5164-Q1 (6-100 V,
Iq ~10 µA) - wydajniejszy, wymaga cewki.
TPS62740 (Vin 2,2-5,5 V!) i tanie bucki (LM2596/MP1584/Mini360, Iq mA)
NIE nadają się do tej aplikacji.
POWER_BATTERY:
Li-SOCl2 3,6 V ── bezposrednio 3V3 (ESP32 wymaga >= 3,0 V pod obciazeniem)
LiPo 3,7 V ── PRZEZ LDO 3,3 V (np. MCP1700). Bezposrednie zasilanie
LiPo 4,2 V przekracza max ESP32 (3,6 V) i CC1101 (3,9 V)!
```
```
+12V ──[bezpiecznik]──[TVS]──> regulator IN
Pomiar: +12V ──[R1 1M]──+── GPIO34 ( + 100 nF do masy )
└──[R2 270k]── GND
(12 V -> 2,55 V, 14,4 V -> 3,05 V, prad dzielnika ~9 uA)
```
Ważne:
* **moduły DevKit z mostkiem USB-UART (CH340/CP2102) i LDO AMS1117 pobierają
w deep sleep 0,5–2 mA** — w aucie użyj gołego modułu ESP32-WROOM na własnej
płytce z przetwornicą o niskim Iq (patrz sekcja 13),
* CC1101 zasilaj **3,3 V**, antena 433 MHz (kawałek drutu ~17 cm) przy złączu
CC1101; trzymaj przewody SPI krótkie,
* masa dzielnika pomiarowego i CC1101 musi być wspólna z ESP32.
**Opcjonalny front-end LF 125 kHz** (reakcja na aktywację czujnika
programatorem TPMS przy kole): cewka rezonansowa ~125 kHz (kilka zwojów,
np. ferrytowa ramka z programatora) + detektor obwiedni (dioda Schottkyego
+ kondensator + rezystor rozładowczy + bramka komparatora/logiki) →
impuls 3,3 V na `PIN_LF_TRIGGER`. Stan spoczynkowy musi być **niski**
(wejście ESP32 ma wewnętrzne podciągnięcie do dołu włączone przez firmware).
Bez modułu LF jego rolę pełni przycisk — patrz sekcja 8.
---
## 6. (b) Konfiguracja ID i ciśnień
Wszystko w **`src/config.h`**:
```c
/* ID poszczególnych kół (24 bity) */
#define SENSOR_FL_ID 0x2FC871u // przód lewy
#define SENSOR_FR_ID 0x2EAAF9u // przód prawy
#define SENSOR_RR_ID 0x3495ACu // tył prawy
#define SENSOR_RL_ID 0x2FC780u // tył lewy
/* Ciśnienie startowe: DOMYŚLNIE 2,6 bar = 260 kPa dla wszystkich kół */
#define SENSOR_FL_PRESS_KPA 260.0f
#define SENSOR_FR_PRESS_KPA 260.0f
#define SENSOR_RR_PRESS_KPA 260.0f
#define SENSOR_RL_PRESS_KPA 260.0f
/* Temperatura otoczenia (st. C) */
#define SENSOR_TEMP_C 23
```
Rozdzielczość protokołu: **2,5 kPa/bit** (zakres 0–637,5 kPa),
temperatura w ramce w °F (przeliczenie automatyczne).
### Jakie ID wpisać? — to jest kluczowa decyzja
| Strategia | Kiedy stosować | Co zrobić |
|---|---|---|
| **A. Oryginalne ID (najlepsze)** | Auto ma już zapamiętane 4 ID starych czujników | **Przed** wymianą odczytaj ID oryginalnych czujników: `rtl_433 -f 433.92M` (pole `id` modelu `Schrader-EG53MA4`), wgraj je do `config.h`. ECU słyszy „znajome" czujniki i **nie trzeba nic programować**. |
| **B. Nowe ID + procedura nauki** | Oryginalne ID nieznane / ECU nie pamięta | Wpisz dowolne unikalne ID (jak wyżej) i wykonaj **procedurę learn** w aucie (sekcja 8), aby ECU zarejestrowało nowe ID. |
Dodatkowo (w razie potrzeby):
```c
#define TPMS_FLAGS 0x4C900070u // słowo "flags" z prawdziwych czujników
#define TPMS_FLAGS_LOWBAT_MASK 0x00000008u // bit "rozładowana bateria"
```
Wartość `TPMS_FLAGS` domyślnie pochodzi z nagrań prawdziwych czujników
EG53MA4 (stała `4c900070`). Bitu niskiej baterii rtl_433 nie analizuje —
jeśli Twój sterownik pokazuje ostrzeżenie „service TPMS" mimo dobrych
ciśnień, spróbuj zmienić `TPMS_FLAGS_LOWBAT_MASK` (lub wyczyść bit przez
`flags` w konsoli) i powtórz naukę.
Po zmianach: `pio run -e esp32dev -t upload`.
---
## 7. (c) Test nadawania — RTL-SDR + rtl_433
Zanim włożysz urządzenie do auta, sprawdź transmisję „w eterze":
1. Zasil urządzenie (powerbank / 3,3 V), ustaw `monitor` szeregowy.
2. Na komputerze z RTL-SDR:
```bash
rtl_433 -f 433.92M
```
3. Urządzenie co 30 s wysyła po 3 ramki dla każdego koła. Powinieneś widzieć:
```
time : ...
model : Schrader-EG53MA4 type: TPMS flags: 4c900070 ID : 2FC871
Pressure : 260.0 kPa Temperature: 73.0 F Integrity : CHECKSUM
```
dla kolejno: `2FC871` (FL), `2EAAF9` (FR), `3495AC` (RR), `2FC780` (RL),
każde 260.0 kPa i 73.0 F (23 °C).
4. Bez RTL-SDR możesz wywołać ramki z konsoli: `send`, `hex` (hexdump).
**Wariant FSK** (`TPMS_MODULATION MODE_FSK` w `config.h`) — rtl_433 nie ma
dla tego wariantu wbudowanego dekodera EG53MA4 (deklaracja OOK), weryfikuj
przez dekoder flex:
```bash
rtl_433 -f 433.92M -X 'n=schrader,m=FSK_MC_ZEROBIT,s=120,l=120,r=300'
```
> Uwaga praktyczna: nazwy plików `.cu8` do testów **nie mogą** zawierać
> słów `ook`, `fsk`, `am`, `fm` (parser formatów rtl_433 je rozpoznaje).
> Np. `tpms_sim.cu8` jest OK, `sim_ook.cu8` — nie.
---
## 8. (d) Programowanie czujników w aucie (tryb learn)
### Kolejność kół w Astrze J
**przód lewy (FL) → przód prawy (FR) → tył prawy (RR) → tył lewy (RL)**
(kolejność konfigurowalna przez `LEARN_ORDER_0..3` / kolejność wpisów w tablicy
`SENSOR[]` w `main.cpp`).
### Sterowanie (przycisk `PIN_BUTTON`)
| Gest | Tryb NORMAL | Tryb LEARN | Tryb SINGLE |
|--------------------------|--------------------------|--------------------------|--------------------------|
| krótkie naciśnięcie | natychmiast burst 4 kół | **następne koło** | **następne koło** |
| długie (≥1,5 s) | → **LEARN** | → NORMAL | → LEARN |
| bardzo długie (≥4 s) | → **SINGLE** | → SINGLE | → NORMAL |
(Przycisk nie jest drzemany przy wciśniętym — urządzenie nie wejdzie w sen,
dopóki go nie puścisz; bardzo długi gest zdąży się zawsze zarejestrować.)
LED: seria **N mrugnięć = N-ty numer koła** (1–4) przy zmianie koła,
wzorzec stały: NORMAL — 1 mrugnięcie co 2 s, LEARN — 3 mrugnięcia co 0,5 s,
SINGLE — 2 mrugnięcia co 0,5 s, niskie napięcie — 10 mrugnięć co 3 s.
### Procedura krok po kroku
1. **Odczytaj oryginalne ID** (jeśli to możliwe) — patrz strategia A w sekcji 6.
2. Włącz zapłon, uruchom procedurę nauki TPMS w aucie
(Astra J: menu kierowcy → ustawienia → ciśnienie w oponach → nauka /
„Tyre learning"; w wersjach bez menu — procedura z pedałem gazu
lub przez OP-COM/TECH2 — sprawdź instrukcję obsługi swojej wersji).
3. **Wejdź w tryb LEARN** (długie naciśnięcie) — urządzenie nadaje
**tylko koło FL** (ID z `SENSOR_FL_ID`), LED mruga 1×.
4. Urządzenie nadaje burst co 2 s. Jeśli procedura w aucie wymaga
**aktywacji czujnika przy kole** (puls LF 125 kHz / programator TPMS):
* podejdź do koła FL i użyj programatora LF — jeśli masz moduł LF
(`PIN_LF_TRIGGER`), urządzenie **natychmiast** wyśle właściwe ID,
* bez modułu LF: **krótkie naciśnięcie przycisku = „aktywuj koło"**
(w LEARN służy też do przejścia dalej — użyj komendy `send`
w konsoli, jeśli potrzebna jest aktywacja bez zmiany koła).
5. **Krótkie naciśnięcie = następne koło** (LED: 2×, 3×, 4×) i powtórz
aktywację przy kolejnych kołach w kolejności **FL → FR → RR → RL**.
6. **Okno czasowe**: na każde koło jest `LEARN_WINDOW_MS` (60 s).
Po jego upływie urządzenie **wraca do trybu normalnego**
(`LEARN_WINDOW_EXPIRE_TO_NORMAL 1`); ustaw `0`, jeśli wolisz
automatyczne przejście do kolejnego koła. Cała sesja learn kończy się
też po `LEARN_TOTAL_TIMEOUT_MS` (15 min).
7. Zakończ procedurę w aucie (zwykle: zapłon OFF, jazda testowa).
8. Po zakończeniu nauki urządzenie samo wraca do NORMAL i nadaje
wszystkie 4 koła co 30 s — także przy postoju (transmisja jest ciągła,
niezależna od ruchu; auto-learn może wymagać jazdy, ale ramki lecą zawsze).
### Jeśli auto „nie zapamiętuje" czujników
* **Użyj oryginalnych ID** (strategia A) — wtedy nie trzeba w ogóle
programować; ECU zna już te ID i zaakceptuje je natychmiast.
* Sprawdź, czy procedura nauki w aucie była uruchomiona **przed**
transmisjami (ECU w trybie nauki nasłuchuje nowych ID).
* W trybie LEARN nadawane jest **tylko jedno ID naraz** — jeśli nadawałeś
wszystkie 4 jednocześnie, ECU mógł się „pomylić" (stąd tryb learn).
* Upewnij się, że ciśnienie jest w zakresie akceptowanym przez ECU
(260 kPa = 2,6 bar jest bezpieczne dla Astry J).
* Spróbuj wariantu modulacji: `MODE_OOK` ↔ `MODE_FSK` (patrz sekcja 7) —
wersje EU/US różnią się; referencyjne nagrania EG53MA4 to **ASK/OOK**.
* Procedura nauki niektórych wersji Astry J wymaga **jazdy > 20 km/h**
przez kilka minut — urządzenie nadaje przez cały czas, więc wystarczy
wykonać jazdę próbną po starcie procedury.
* Sprawdź DTC przed i po (OP-COM/TECH2): kody czujników (np. C0750–C0759)
powinny zniknąć po udanej nauce.
* Zmierz napięcie zasilania (`batt`) — przy `POWER_12V` urządzenie raportuje
stan akumulatora i flagę niskiego napięcia w ramce (`LOWBATT`).
### Tryb SINGLE
Wymuszone nadawanie jednego ID (testy, procedury uczące jedno koło
wielokrotnymi próbami):
* bardzo długie naciśnięcie (≥4 s) — SINGLE na bieżącym kole,
* konsola: `mode single 2` (koło FR), `next` — zmiana koła,
* wyjście: bardzo długie naciśnięcie lub `mode normal`,
limit czasu `SINGLE_TIMEOUT_MS` (domyślnie 5 min).
---
## 9. (e) Pomiar poboru prądu
### Co zmierzyć
| Stan | Co się dzieje | Oczekiwana wartość |
|----------------------|---------------------------------------------------|--------------------|
| **Deep sleep** | między transmisjami (większość czasu) | **< 50 µA** (goły moduł ESP32 + CC1101 + buck o niskim Iq); ~10 µA ESP32 + < 1 µA CC1101 + Iq przetwornicy |
| **Transmisja (burst)** | 4 koła × 3 ramki, ~0,35 s na antenie + 1,2 s aktywności | ~30 mA (CC1101 TX) + ~80 mA (ESP32) przez ok. 1,2 s co interwał |
| **Średnia** | suma | ~4 mA przy interwale 30 s, ~1 mA przy 120 s (patrz sekcja 13) |
### Jak zmierzyć
1. **Sen** — multimetr w zakresie µA **szeregowo z zasilaniem**,
po 30 s od ostatniej transmisji (gdy ESP32 jest w deep sleep).
Mierz na pinach modułu, nie przez port USB!
2. **Burst** — rezystor bocznikowy 1 Ω + oscilloskop albo INA219/INA226
(szyna I²C), odczyt średniego prądu przez ≥ 60 s.
3. **Średnia doby** — mierz przez 1–2 minuty w zakresie mA i przelicz
(albo użyj miernika z integracją, np. µCurrent + logger).
4. Porównaj z budżetem z sekcji 13; odchylenie 2× w dół/w górę jest normalne.
### Typowe pułapki
* **DevKit z USB-UART**: mostek CP2102/CH340 + LDO AMS1117 = 0,5–2 mA
w sleep → cel < 50 µA **niedotrzymany z winy płytki**, nie firmware'u.
Rozwiązanie: goły moduł ESP32-WROOM + regulator z sekcji 5
(MCP1703/ LM5164-Q1 dla 12 V, MCP1700 dla LiPo).
* **Dzielniki pomiarowe**: 2 × 1 MΩ/270 kΩ ≈ 19 µA stale — to już połowa
budżetu < 50 µA; w wariancie bateryjnym możesz je całkowicie odpiąć
(`PIN_VBAT_ADC -1` nie jest obsługiwany — po prostu nie montuj dzielnika
i zignoruj odczyt) albo zwiększyć rezystancje kosztem dokładności ADC.
* Rezystor podciągający przycisku (10 kΩ) pobiera 330 µA przy stanie
aktywnym niskim — w sleep przycisk jest w stanie spoczynkowym (HIGH),
więc prąd nie płynie; gdybyś użył aktywnego HIGH, zwiększ rezystor do 100 kΩ.
* LED — w sleep zgaszony (firmware go gasi przed snem).
---
## 10. (f) Weryfikacja, że błąd zniknął
1. **Przed testem**: skasuj stare DTC (OP-COM/TECH2 lub odłącz akumulator
na kilka minut — utrata ustawień radia/godziny jest możliwa).
2. Uruchom procedurę learn w aucie (sekcja 8) albo użyj oryginalnych ID.
3. Włącz zapłon, odczekaj 1–3 minuty (ECU zbiera ramki) lub wykonaj jazdę
próbną 5–10 min powyżej 20 km/h.
4. Sprawdź:
* **kontrolka TPMS** (żółta ikona opony) — powinna zgasnąć,
* **wyświetlacz kierowcy** (DIC): menu ciśnienia w oponach powinno
pokazywać 4 wartości (2,6 bar),
* **OP-COM/TECH2**: brak aktywnych kodów czujników TPMS,
* **rtl_433**: `rtl_433 -f 433.92M` dekoduje 4 ID co ok. 30 s
(to potwierdza, że transmisja jest ciągła).
5. Test długotrwały: pozostaw auto na noc z włączonym zapłonem raz na
kilka godzin — po ponownym uruchomieniu błąd nie powinien wracać.
6. Jeśli kontrolka zapala się ponownie po dłuższym postoju — sprawdź
interwał parkingowy (`TX_INTERVAL_PARKING_S`) i flagę baterii
(`TPMS_FLAGS_LOWBAT_MASK`).
---
## 11. Tryby pracy i sterowanie
| Tryb | Zachowanie | Wejście |
|----------|----------------------------------------------------------------------------|--------------------------------|
| NORMAL | rotacja 4 kół: burst 3 ramek × 4 koła co `TX_INTERVAL_S` (30 s), potem deep sleep | stan domyślny, `mode normal` |
| LEARN | **tylko jedno koło**, burst co 2 s, okno 60 s na koło, przycisk = następne koło | długie naciśnięcie, `mode learn` |
| SINGLE | wymuszone jedno ID, burst co 2 s | bardzo długie naciśnięcie, `mode single n` |
### Deep sleep i budzenie
* budzik RTC co `TX_INTERVAL_S` / `TX_INTERVAL_IGNITION_S` /
`TX_INTERVAL_PARKING_S`,
* **EXT0**: przycisk (`PIN_BUTTON`) — natychmiastowe wybudzenie,
* **EXT1**: wejście LF (`PIN_LF_TRIGGER`) — aktywacja czujnika przy kole
= natychmiastowa transmisja odpowiedniego ID,
* między transmisjami: CC1101 w SLEEP (`SPWD`), linie SPI trzymane przez
`gpio_hold` (CS wysoki — utrzymuje CC1101 w sleep, SCK/MOSI niskie),
* WiFi **nie jest w ogóle inicjalizowany**, BT wyłączany (`btStop()`),
brak dynamicznej alokacji pamięci (same bufory statyczne),
brak opóźnień blokujących — jedyny „blocking" to oczekiwanie na
zakończenie nadania ramki (~29 ms) i odstępy między ramkami w burście
(transmisja musi fizycznie trwać tyle, ile trwa).
### Tryb ignition-aware (ACC)
* `PIN_ACC` wysoki (zapłon) → interwał `TX_INTERVAL_IGNITION_S` (15 s),
* po zaniku ACC + `ACC_GRACE_MS` (5 min) → interwał `TX_INTERVAL_PARKING_S`
(120 s) albo całkowite uśpienie (`PARKING_SHUTDOWN 1`) — budzi wtedy
tylko przycisk/LF,
* bez podłączonego ACC (`PIN_ACC -1`) urządzenie pracuje stale
z interwałem `TX_INTERVAL_S`.
---
## 12. Konsola szeregowa
115200 8N1, po starcie okno `BOOT_STAY_AWAKE_MS` (3 s) — wciśnij `stay 60`,
żeby zostać dłużej. Komendy:
| Komenda | Działanie |
|------------------------------|------------------------------------------------|
| `help` | lista komend |
| `info` / `config` | wersja, konfiguracja, ID, stan, napięcie |
| `hex [n\|all]` | hexdump ramki koła n (1–4) lub wszystkich |
| `send [n\|all]` | wyślij burst teraz |
| `batt` | pomiar napięcia zasilania [mV] |
| `mode normal\|learn\|single [n]` | zmiana trybu |
| `next` | następne koło (learn/single) |
| `interval <s>` | ręczny interwał (0 = automatycznie wg ACC) |
| `flags <hex>` | słowo `flags` wysyłane w ramce |
| `sleep` | deep sleep teraz |
| `stay [s]` | czuwaj jeszcze s sekund |
Przykładowy `hex 1` (koło FL):
```
FL frame: AA AA AA AA AA AA AA AA AA AA CB 4B 2C AA AA AA D4 AA B3 55 4B 2A D4 AC D3 2A CB 2C D2 CC
FL payload: 4C 90 00 70 2F C8 71 68 49 65 crc=65 id=2FC871 press=260.0 kPa temp=73 F
```
---
## 13. Budżet prądu
Założenia: burst = 4 koła × 3 ramki, ramka na antenie 240 chipów × 120 µs
= **28,8 ms**, przerwa 50 ms między ramkami; wybudzenie + konfiguracja CC1101
+ ADC ≈ 1,2 s aktywności na cykl; ESP32 aktywny ~80 mA, CC1101 TX ~30 mA
(+10 dBm), CC1101 idle ~15 mA, deep sleep ≈ 15 µA (ESP32 ~10 µA + CC1101
< 1 µA + Iq regulatora) **+ ~19 µA na dzielnikach pomiarowych**
(2 × 1 MΩ/270 kΩ). Przeliczenia poniżej robione są jednym wzorem:
pobór z 12 V = pobór na szynie 3,3 V × (3,3/12) / sprawność regulatora (0,9).
**Cykl co 30 s** (2880 cykli/dobę):
| Składnik | Ilość na cykl | Ładunek na cykl |
|---------------------------------------|--------------------|-----------------|
| ESP32 aktywny (80 mA × 1,2 s) | 1,2 s | 96 mAs ≈ 27 µAh |
| CC1101 TX (30 mA × 0,35 s) | 0,35 s | 10 mAs ≈ 3 µAh |
| CC1101 idle/reszta (15 mA × 0,85 s) | 0,85 s | 13 mAs ≈ 4 µAh |
| deep sleep + dzielniki (~34 µA × 30 s)| 30 s | ≈ 0,3 µAh |
| **Razem** | | **≈ 34 µAh/cykl** |
* **Dobowy pobór na szynie 3,3 V: 34 µAh × 2880 ≈ 98 mAh/dobę**
(średnio ≈ 4 mA).
* Przy zasilaniu 12 V (sprawność 90%): **≈ 30 mAh/dobę z akumulatora**
(98 × 3,3/12/0,9 = 30; średnio ≈ 1,25 mA przy 12 V).
**Akumulator 60 Ah (Pb), bez innych odbiorników:**
* prąd potrzebny do rozruchu wymaga napięcia > ~11,8 V, czyli ~50% pojemności
= 30 Ah użyteczne,
* 30 000 mAh / 30 mAh ≈ **1000 dni ≈ 2,7 roku** — teoretycznie;
* **w praktyce granicą jest samorozładowanie akumulatora kwasowego
(3–5%/mies.)** — akumulator bez odbiorników rozładowuje się w 6–12 mies.,
więc symulator **nie jest czynnikiem limitującym**.
**Warianty oszczędne** (pobór z 12 V z uwzględnieniem sprawności 0,9):
| Interwał | Średni prąd (3,3 V) | Dobowy pobór (12 V) | 60 Ah (30 Ah użyteczne) |
|----------|--------------------|--------------------|--------------------------|
| 30 s | ~4 mA | ~30 mAh/dobę | ~2,7 roku* |
| 120 s (parking) | ~1 mA | ~8 mAh/dobę | ~10 lat* |
| 300 s | ~0,4 mA | ~3,5 mAh/dobę | ogranicza samorozładowanie |
\* przed samorozładowaniem akumulatora.
**Wariant bateryjny** (Li-SOCl2 3,6 V 2400 mAh, bez strat przetwornicy):
~98 mAh/dobę przy 30 s to ok. **24 dni**; przy 300 s ~10 mAh/dobę to ok.
**240 dni (~8 mies.)**. Do zasilania bateryjnego stosuj dłuższe interwały,
mniejszą liczbę ramek w burście (`TX_BURST_FRAMES 2`) albo
`PARKING_SHUTDOWN 1`.
Wskazówki: zmniejsz `TX_BURST_FRAMES`, wydłuż interwał, użyj mocy TX
`TPMS_TX_POWER_DBM 0` (wystarczy w aucie), ustaw `PARKING_SHUTDOWN 1`
(przy postoju sen do przycisku).
---
## 14. Protokół — szczegóły techniczne
Dekoder referencyjny: `rtl_433/src/devices/schraeder.c` →
`schrader_EG53MA4` („Schrader TPMS EG53MA4, Saab, Opel, Vauxhall,
Chevrolet"), zasilany sygnałem **OOK Manchester** (`OOK_PULSE_MANCHESTER_ZEROBIT`,
`s=123 µs`, `r=300 µs`). Wymagana długość dekodowanego wiersza: **120 bitów**.
Ramka (bity po dekodowaniu Manchester):
```
0 40 56 80 88 96 104
+--------+--------+---------+---------+---------+--------+
| sync | flags (4 B) | id (3 B) |press|T |crc|
| 40 bit | 4c 90 00 70| 2F C8 71 | 68 |49| 65|
+--------+--------+---------+---------+---------+--------+
```
* `flags` — 4 bajty (status/bateria, wg dekodera nie w pełni rozpoznane),
* `id` — 24-bitowy identyfikator czujnika,
* `press` — ciśnienie: **25 mbar/bit = 2,5 kPa/bit** (260 kPa → `0x68`),
* `T` — temperatura w **°F** (23 °C → `73`),
* `crc` — **suma 9 poprzednich bajtów mod 256** (`add_bytes` w rtl_433).
Kodowanie na warstwie RF (G.E.T. Manchester, zgodnie z analizą nagrań
`rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01/`):
* chip = **120 µs** (8,33 kBaud),
* bit `0` → chipy `01`, bit `1` → chipy `10`,
* nadajnik wysyła **1 chip rozbiegowy + 119 komórek** (ramkę bez pierwszego
bitu — pierwszy bit dopisuje dekoder MC_ZEROBIT), dopełnienie zerowe do
bajtu jest ciszą w eterze (OOK),
* modulacja: **ASK/OOK 433.92 MHz** (jak w referencyjnych nagraniach;
FCC MRXEG53MA4: „Type of Modulation: ASK + FSK", „Frames are Manchester
encoded ASK data"), opcjonalnie **2-FSK 433.92 MHz, dewiacja 47,6 kHz**
(`TPMS_MODULATION MODE_FSK`).
Weryfikacja implementacji (bez sprzętu):
* `tools/tpms_frame.py` — referencyjna implementacja ramki + **kopia
dekodera `pulse_slicer_manchester_zerobit()` z rtl_433** (self-test 500
losowych ramek + wektor z prawdziwego nagrania `gfile001.cu8`),
* `tools/gen_cu8.py` + `tools/verify_rtl433.sh` — synteza nagrań IQ
i dekodowanie **prawdziwym rtl_433** (wynik w sekcji 4),
* `pio test -e native` — testy kodu C firmware'u (te same wektory).
---
## 15. Rozwiązywanie problemów
| Objaw | Przyczyna / rozwiązanie |
|---|---|
| `BLAD: brak modulu CC1101` | Sprawdź SPI (SCK=18, MISO=19, MOSI=23, CS=5), zasilanie 3,3 V, masę |
| rtl_433 nic nie dekoduje | Sprawdź antenę, odległość (< 1 m na test), `rtl_433 -f 433.92M`; spróbuj `MODE_FSK` + decoder flex; sprawdź `send` w konsoli i `hex` |
| rtl_433 dekoduje inne ID niż w config | Skompiluj i wgraj ponownie po zmianie `config.h`; sprawdź `info` |
| Auto nie zapamiętuje ID | Strategia A (oryginalne ID) lub procedura learn w trybie LEARN (jedno koło naraz), jazda testowa > 20 km/h |
| Kontrolka TPMS świeci mimo OK | Zmień `TPMS_FLAGS` / `TPMS_FLAGS_LOWBAT_MASK`, skasuj DTC, powtórz naukę |
| Pobór w sleep > 50 µA | DevKit z mostkiem USB — użyj gołego modułu; sprawdź rezystory podciągające i dzielnik pomiarowy (R1+R2 = 133 kΩ → 27 µA przy 3,6 V — rozważ 470 kΩ/150 kΩ) |
| Reset przy transmisji | Za słabe zasilanie — dodaj kondensator 100 µF przy CC1101, użyj bucka o wystarczającym prądzie |
| `pio test -e native` nie przechodzi | Upewnij się, że nie zmieniłeś `tpms_frame.cpp` bez aktualizacji wektorów w teście (generuj przez `tools/tpms_frame.py`) |
---
## Wersje
* `CONFIG_VERSION` w `src/config.h` — podnieś przy zmianie formatu danych
w pamięci RTC (magic RTC zawiera tę wersję, więc stan zostanie wyzerowany).
* Firmware testowany z: PlatformIO `espressif32@8.0.0`, Arduino core ESP32,
`SmartRC-CC1101-Driver-Lib` commit `de6757e` (3.0.2, wymagane ≥ 2.5.7),
rtl_433 (master).
**Pamiętaj: symulator generuje sztuczne dane ciśnienia i nie zastępuje
prawdziwych czujników TPMS.**
An ID must have six hex digits, be non-zero, differ from `FFFFFF`, and be
unique. The device returns to NORMAL and transmits the known IDs. **Learning
may be unnecessary, but that is not guaranteed.** Confirm reception
diagnostically; do not start with a road drive.
### 4B. Alternative: New IDs + LEARN
1. Type `ids new`, then `info`, and write down the generated IDs.
2. Start the TPMS learning procedure appropriate for your car model/version
according to its service instructions. Do not guess menu/pedal sequences.
3. Type `mode learn`. It transmits FL only, every 2 s. The LED shows 1 blink.
4. `send` forces the current wheel without changing it. After confirming the
step in the car, type `next`: FR → RR → RL. A short button press does the
same; after RL it returns to NORMAL.
5. If 60 s passes on a wheel, LEARN interrupts to NORMAL. The whole session
has a 15 min limit. When finished, verify the IDs and diagnostic codes.
EL-50448/OEC-T5 is a 125 kHz LF activator, **not an ESP32 programmer**. This
procedure does not require it. Details: [SETUP](docs/SETUP.md).
## Controls — one table
The LED works only while awake; in deep sleep it is off. After a wheel change,
a series of 1–4 blinks indicates FL/FR/RR/RL.
| Mode | LED pattern | Short button | Long ≥1.5 s | Very long ≥4 s |
|---|---|---|---|---|
| NORMAL | 1 blink / 2 s | burst of all 4 | enter LEARN | enter SINGLE |
| LEARN | 3 blinks / 0.5 s; changes with wheel number | next wheel + TX; after RL done | exit to NORMAL | enter SINGLE |
| SINGLE | 2 blinks / 0.5 s; changes with wheel number | next wheel + TX | enter LEARN | exit to NORMAL |
In the console, `send` in NORMAL transmits all wheels, and in LEARN/SINGLE
only the current one. `send 1`…`send 4` select a wheel explicitly; `send all`
transmits four. SINGLE shuts off after 5 min.
## Most common problems
- **`ERROR: no CC1101`**: check 3.3 V, common ground, and SCK/MISO/MOSI/CS
on GPIO4/5/6/7 and GDO0 on GPIO10; do not use 5 V on the CC1101.
- **Console disappears before you enter commands**: right after restart type
`stay 300`; a plain RTC wake deliberately does not open the console window.
- **NVS reports an error**: the device uses safe defaults; type `info`.
`factory YES` erases your IDs and restores the factory configuration.
- **The car does not receive**: first verify the car profile and RTL-SDR
reception; do not randomly change modulation, flags, or intervals. See
[TROUBLESHOOTING](docs/TROUBLESHOOTING.md).
## Validation, power, and release
- Protocol and unknowns: [PROTOCOL](docs/PROTOCOL.md)
- Detailed results and the HIL checklist: [VALIDATION](docs/VALIDATION.md)
- Consumption (estimates so far): [POWER](docs/POWER.md)
- LM317T and power from the cigarette-lighter socket:
[HARDWARE](docs/HARDWARE.md#cigarette-lighter-socket-variant--requirements-unvalidated-design)
- Changes: [CHANGELOG](CHANGELOG.md)
Release images are produced by `bash tools/package_release.sh`. The files and
addresses are described in
[VALIDATION](docs/VALIDATION.md#artifacts-and-flashing). The release candidate
does not include a CC1101 test result or a car test.
+66
View File
@@ -0,0 +1,66 @@
# TPMS EG53MA4 Simulator 2.0.0-rc.1
**Release candidate — 2026-10-27. This is not a "validated" release.**
A diagnostic simulator of four Schrader EG53MA4 sensors for the ESP32-S2-MINI
(ESP32-S2FN4R2) + CC1101 433 MHz with an SMA antenna. The target profile
includes tests with an Opel Astra J Sedan 2016, but compatibility of the
specific car must be confirmed. Synthetic data can hide a tyre fault; do not
use while driving.
## Features
- four persistent, independent 24-bit IDs; 260 kPa by default for every wheel;
- OOK/Manchester 433.92 MHz, low configurable power from −10 dBm;
- Clone IDs and New IDs + LEARN FL→FR→RR→RL, SINGLE/diagnostics;
- NVS configuration over UART without recompilation, version/CRC/
validation/factory reset;
- button, LED, timeouts, deep sleep with RTC and optional hardware ACC;
- automated native/RF/build tests, Docker, and SHA-256 artifacts.
## Required hardware
ESP32-S2-MINI (ESP32-S2FN4R2), a CC1101 **433 MHz** 3.3 V module with an SMA
connector (e.g. ARD-CC1101-ANT), an antenna, a button, and decoupling. The LED
is built in. Target power from the cigarette-lighter socket: a car USB charger
or an LM317T with a 240/390 Ω divider and proper capacitors; the 12 V variant
requires input protection and tests. Full BOM/pinout: HARDWARE. Neither the
S2 Mini nor the LM317T is a validated automotive solution on its own.
## Installation and update
New installation: `bash tools/check_all`, then
`pio run -e esp32s2mini -t upload`.
Release images: `bash tools/package_release.sh`; addresses and flashing are
described in VALIDATION. Before a full flash, write down your IDs — the NVS
partition may be erased. Verify the configuration after a restart with `info`.
There is no migration from version 1.0 without NVS; enter the IDs in the
console once.
## Test results without hardware (2026-10-28)
- native: 24/24 PASS (after the hardware–firmware integration audit);
- full ESP32 build with `-Werror`: PASS;
- cppcheck: PASS, 0 defects;
- rtl_433: 64/64 reference records, 3/3 synthetic, 3/3 negative: PASS.
Exact commands and pinned commits: VALIDATION/PROTOCOL.
## Known limitations
- The real CC1101 emission, tail, power, and frequency were not measured.
- RTL-SDR with an antenna, consumption measurement, brownout, and the ACC
test were not performed.
- Clone IDs/LEARN with a car were not performed; OE 13506028 was not confirmed
for a specific VIN.
- The meaning of all flags remains unknown; there is no guessed low-battery
bit.
- The schedule is experimental, not confirmed as OE.
- The LM317T and power from the cigarette-lighter socket are not a validated
automotive design; with power only from an ignition-switched socket there
is no transmission after the ignition goes off — the car ECU does not
listen then anyway.
- Gitea Actions requires a working runner; local results do not mean CI PASS.
Until the HIL items in VALIDATION are checked off, the result remains a
release candidate.
+25
View File
@@ -0,0 +1,25 @@
# Licenses and sources
The project is distributed under GPL-2.0-or-later (`LICENSE`). The choice is
consistent with prior use of the slicer algorithm from rtl_433 in the model's
history. We do not claim rights to external authors' code.
- **rtl_433** — GPL-2.0-or-later; the `schraeder.c` decoder, Copyright
Benjamin Larsson, Christian W. Zuckschwerdt and subsequent authors. Used as
an independent decoding program for testing. Source and full history:
<https://github.com/merbanan/rtl_433>. Test reference: commit
`406f9a33550a2b6b3d0d8a8a486417ce5b3f13ab`.
- **rtl_433_tests** — the recordings and metadata belong to their authors;
they are not copied into the firmware artifact or the release. The script
fetches the pinned commit `1aa8c29d6b9383739d1aeed495dbc5069b704392`.
- **SmartRC-CC1101-Driver-Lib** — an external library fetched by PlatformIO;
its original headers and license are preserved. Commit used:
`de6757ef633b3e626dae5c7835cdb66ab53f9a1d`.
- **Arduino ESP32 / ESP-IDF / PlatformIO / Unity** — build/test dependencies
under their own licenses; they are not covered by the attribution of this
project.
- rtl_433 issue #2978 served only as a CC1101 integration pattern. The
Renault protocol code is not EG53MA4 code and was not used as the protocol.
The full license texts of the dependencies are in their sources, fetched
during the build. This file does not narrow their rights or licenses.
+34
View File
@@ -0,0 +1,34 @@
# Release-v2 audit register
| Priority | Original problem | Repair criteria | Status / evidence |
|---|---|---|---|
| P0 | Guessed low-battery bit dependent on the emulator supply | no mask and no coupling; flags test | fixed; code grep and 20/20 native |
| P0 | MCP1703 + 24 V TVS described as automotive protection | remove the recommendation; requirements and a datasheet example | fixed in HARDWARE |
| P0 | Lack of physical compatibility evidence with the car presented too confidently | RC, explicit HIL, VIN/marking verification | documentation fixed; HIL still open |
| P1 | IDs/pressures/RF only via recompilation | NVS with a console, validation, version/CRC | fixed; test_settings and build |
| P1 | Monolith prevented testing timeouts/ACC | portable state machine, fake clock/radio | fixed; test_app_state |
| P1 | FSK in the base flow without evidence | OOK only in firmware/generator | fixed |
| P1 | PARKING_SHUTDOWN without a guaranteed ACC wake | remove it or guarantee waking | removed; every sleep has RTC |
| P1 | TX ended on time and TXBYTES, tail risk | MARCSTATE/underflow/limit | improved; requires HIL confirmation |
| P1 | Vectors mostly self-authored | four real recordings + independent rtl_433 | 64/64 PASS |
| P2 | Default LF without a validated front end | disabled by default, LEARN without LF | fixed |
| P2 | Intervals presented as OE | explicitly experimental | PROTOCOL/SETUP/POWER |
| P2 | No full single check/build artifacts | check_all, CI, Docker, package_release | added; results in VALIDATION |
| P2 | A console window after every RTC wake raises consumption | sleep right after the RTC cycle | improved; HIL measurement open |
| P2 | README inconsistent with behaviour | new Quick Start, one UI table | rewritten |
| P1 | Digital pull-up of button/LF does not work in deep sleep (EXT1, RTC_PERIPH off) | RTC pulls + HOLD before sleep | fixed in power.cpp; HIL wake still open |
| P1 | `nan` passed console validation (pressure/RF) and reached NVS | rejecting NaN/inf + native tests | fixed; `parse` + test_parse |
| P2 | ADC divider saturating above ~11.8 V — no 12–14.4 V reading | range up to ~16 V | fixed in config.h (R2 180 kΩ); requires measurement |
| P2 | Full release image with `40m` vs build header `80m` | flash parameter consistency | fixed in package_release.sh; header verification |
| P2 | Python model without temperature saturation (discrepancy with C++) | clamp 0–255 + self-test | fixed in tpms_frame.py |
| P3 | Negative checksum test exercised Manchester instead of the sum | invert the whole cell | fixed in test_tpms_frame |
| P3 | Wrong bit offsets in the PROTOCOL.md diagram | correct 72/96/104/112/120 | fixed |
| P1 | Scale of the pressure field `P` (2.5 kPa/bit) unverified — all captures have `P=0`, the car shows 284 kPa for 260 kPa | calibrate against the car display, fix the conversion and tests | fixed; scaling correction 2.73 kPa/bit (`P=95` for 260 kPa), HIL: 260 kPa → 260 kPa on the display; a second measurement point (e.g. 300 kPa) would confirm linearity in range |
## Open, requiring hardware
These cannot be closed by declaration: CC1101/tail/power/frequency
measurement, an RTL-SDR test with an antenna, consumption and brownout,
protected ACC, a Clone IDs/LEARN test with the specific Astra, and the design
and testing of automotive power. They are the checklist in `VALIDATION.md`
and they block the "validated" status.
+184
View File
@@ -0,0 +1,184 @@
# Hardware and assembly
## Scope
The base release describes a **laboratory prototype on the ESP32-S2-MINI**
(ESP32-S2FN4R2). Prototype wires and the LM317T are not a ready kit for
permanent installation in a car. The cigarette-lighter socket variant below
is a list of connections and design requirements, not a validated automotive
schematic.
## Laboratory prototype BOM
| Item | Requirement | Notes |
|---|---|---|
| ESP32-S2-MINI | ESP32-S2FN4R2 (4 MB flash, 2 MB PSRAM), native USB for flash/console; a Lolin/Wemos S2 Mini type board, e.g. ARD-ESP32-S2-MINI | sold with MicroPython — we flash our own firmware; verify a clone before powering it |
| CC1101 | **433 MHz** module, SPI, 3.3 V, with an SMA connector and antenna, e.g. ARD-CC1101-ANT | do not buy the 868/915 MHz version |
| 433 MHz antenna | supplied with the SMA module; for a bench, a λ/4 monopole ≈ 17 cm | ground plane/counterweight per the module's design |
| NO button (optional) | momentary | GPIO3 to GND; without an extra button the board's BOOT button (GPIO0) is used |
| LED | built-in on GPIO15 | active high; an external LED is not needed |
| Car USB charger | cigarette-lighter socket → USB 5 V | power variant A; tested, with a USB-C cable that carries data |
| LM317T | TO-220 (metal), adjustable 1.25–37 V, 1.5 A | only for variant B; not needed when powering from USB |
| LM317T resistors | R1 = 240 Ω (VOUT–ADJ), R2 = 390 Ω (ADJ–GND) | give about 3.28 V; 1% metal-film, close to the device |
| LM317T capacitors | 100 nF on the input and at least 1 µF on the output | practically 10 µF; close to the device |
| Heatsink | for the LM317T when fed from 12–14.4 V | see the thermal calculations below |
| Module decoupling | 100 nF at each module + 47–100 µF at the CC1101 | as close to the supply pins as possible |
| Wires | short, common ground | SPI best under 10 cm |
| Laboratory supply | USB 5 V or the LM317T from a safe VIN | do not feed competing 3.3 V sources at the same time |
RTL-SDR is useful for RF diagnosis but is not part of the emulator. The
standard S2 Mini has a blue LED on GPIO15 and a BOOT button on GPIO0; before
assembly verify the specific clone, because trade names are sometimes used
for different boards.
## Pinout and connections
| ESP32-S2-MINI | CC1101 / item | Rule |
|---|---|---|
| 3V3 | CC1101 VCC; LM317T output when externally powered | **3.3 V only**, never the 5 V pin nor an LM317T set higher |
| GND | CC1101 GND, button, LM317T divider | common ground |
| GPIO4 | SCK/SCLK | SPI |
| GPIO5 | MISO/SO | SPI |
| GPIO6 | MOSI/SI | SPI |
| GPIO7 | CS/CSn/SS | SPI |
| GPIO10 | GDO0 | library diagnostics; GDO2 unconnected |
| GPIO3 | alternative NO button to GND (`-DPIN_BUTTON=3`) | RTC pull-up enabled by the firmware before deep sleep (a digital pull-up does not work in deep sleep); RTC GPIO wakeup, an external 10 kΩ recommended |
| GPIO15 | built-in LED | active HIGH; the firmware drives the correct polarity |
| GPIO1 | optional supply ADC through a divider | `PIN_VBAT_ADC`, ADC1_CH0; 1 MΩ/180 kΩ divider (`config.h`), range up to about 16 V; never 12 V directly |
| GPIO2 | optional ACC after changing `PIN_ACC` and protecting it | never 12 V directly |
| GPIO14 | optional LF detector after changing `PIN_LF_TRIGGER` | active LOW; RTC GPIO wakeup, disabled by default |
| GPIO0 | the board's BOOT button = the control button and RTC wake (default `PIN_BUTTON`) | strapping pin: held at power-up/reset it starts the bootloader instead of the firmware (wake behaviour confirmed on hardware); do not use for the CC1101 |
GPIO0, GPIO45 and GPIO46 are strapping pins. Do not add external resistors or
state-forcing circuits to them during reset. GPIO19/20 carry native USB, and
GPIO26–32 in the ESP32-S2FN4R2 serve the in-package flash and PSRAM — do not
use them. GPIO33–40 remain free; the console uses native USB, so an external
USB-UART bridge is not needed.
With a laboratory 3.3 V supply from the LM317T: start with VIN = 5–9 V, set a
limit of e.g. 0.5 A, check the polarity and output voltage without the S2
Mini connected. Join the grounds, and disconnect USB while externally powered.
Peak current depends on the board and the configured PA.
## LM317T — pinout, divider, and capacitors
For the **LM317T in TO-220**, looking at the markings from the front with the
legs pointing down:
| Leg | Function | Connection |
|---:|---|---|
| 1 | ADJ | divider: R1 to VOUT, R2 to GND |
| 2 | VOUT | 3V3 of the S2 Mini + CC1101 VCC |
| 3 | VIN | protected input voltage |
The metal TAB is connected to **VOUT** — not to GND as in the LF33CV or
7805. The heatsink and TAB enclosure must not touch ground or any other
potential. **Do not use the 7805 leg scheme** — the order here is
ADJ–VOUT–IN.
The output voltage is set by the divider: `VOUT = 1.25 V × (1 + R2/R1)`.
R1 = 240 Ω between VOUT and ADJ, and R2 = 390 Ω between ADJ and GND give
about **3.28 V**, while drawing about 5 mA, close to the LM317's minimum load
current — with larger resistor values measure VOUT unloaded. Place 100 nF
between VIN and GND. Place at least 1 µF between VOUT and GND; a practical
starting point is 10 µF. The LM317 does not require special ESR like an LDO,
but the capacitors should sit close to the device. An extra 100 nF at the
modules and 47–100 µF at the CC1101 remain necessary.
Do not connect the LM317T VOUT to the S2 Mini's **5V** pin. The 5V pin feeds
the board's built-in regulator, whereas external, regulated 3.3 V must be
brought to **3V3**. Do not power from USB and the LM317T at the same time
without verified source separation, because clone designs differ in their
power connections.
## Antenna and position test
We do not guess the TPMS receiver location in the Astra J. Perform the range
test while parked, at low power, comparing RTL-SDR readings/diagnostics for a
few positions: centre console, near the glovebox, possibly the boot. A result
for a single unit is not proof of the receiver location.
Mount the device mechanically, away from airbags and their harnesses, the
pedal area, moving parts, moisture, heat sources, and metal shielding. Do not
wrap the antenna in a harness, do not route it near an LPG bulb/regulator or
ignition wiring. The prototype enclosure should be non-conductive; the hole
for the SMA connector and any need for shielding must be assessed by
measurement.
## Cigarette lighter socket variant — requirements, unvalidated design
The target power comes from the car cigarette-lighter socket, in two ways:
```text
Variant A (simpler):
cigarette-lighter socket → car USB charger (5 V) → USB-C cable → S2 Mini USB
Variant B (regulator):
cigarette-lighter socket 12 V → fuse at the source → reverse-polarity
protection → energy limitation + properly rated TVS
→ LM317T VIN → VOUT 3.3 V → S2 Mini 3V3 + CC1101 VCC
```
In most cars the cigarette-lighter socket is powered only after the ignition
is switched on — **verify this in your vehicle**, because some cars have a
socket powered permanently. With an ignition-switched socket the emulator
draws no current while the car is off. The car computer usually does not read
TPMS state then anyway, so the lack of parking transmission does not matter.
The socket output itself still has transients and noise of the vehicle
installation. **Do not connect it directly to the LM317T VIN as a finished
car installation.** The LM317T tolerates a VIN−VOUT difference up to 37–40 V,
so it is more tolerant of transients than the LF33CV (16 V), but protection
still has to limit the voltage with margin. A TVS with a threshold above the
maximum VIN provides no protection for the LM317T.
Requirements before installation (variant B):
- a fuse matched to the wiring and consumption, close to the source; it does
not replace a TVS;
- reverse-polarity and negative-transient protection;
- TVS and energy limitation matched to the real transient profile, without
conducting at a normal 14.4–14.8 V and without exceeding the LM317T VIN;
- capacitors per the LM317 datasheet, short current loops;
- a measurement of the current peaks of the S2 Mini + CC1101 and a check of
3.3 V stability;
- thermal calculations for the highest temperature and tests of
brownout/crank/load dump, EMC, and ESD on the target board.
The LM317T is a linear regulator: `P = (VIN − 3.3 V) × I`. Already at 14.4 V
and 300 mA you must dissipate about **3.3 W**. Without a calculation and a
TO-220 heatsink it can overheat; the "up to 1.5 A" from the datasheet alone
does not guarantee ESP32-S2 peak supply in all conditions. Measure current
and temperature while transmitting.
**Consequence of powering only from the cigarette-lighter socket:** when the
ignition goes off, the whole emulator loses power. It then performs no deep
sleep or parking transmission, the RTC does not count the interval, and the
`interval parking` setting has no effect. The `PIN_ACC` input is not needed.
After the ignition is switched on, the device simply starts and transmits. If
the device is to transmit while parked too, a permanently powered, protected
input and a separate, protected ACC signal on GPIO2 are required. Then the
consumption of the whole assembly also has to be measured: the LM317T divider
draws a constant ~5 mA, plus the S2 Mini, the CC1101, and the dividers — it
may matter on a long park.
LM317T parameters and required capacitors: the ST datasheet
[LM317](https://www.st.com/resource/en/datasheet/lm317.pdf), the typical
application schematic and the TO-220 pinout drawing. Accessed 2026-10-28.
## Battery power
An 18650 cell in the cabin is **not recommended**: the temperature in a car
can exceed the cell's safe conditions, and an installed cell requires
protection, proper charging, and an enclosure. An ESP32 with a radio and
periodic duty cycling usually gives short runtime; claims of multi-year
operation would be unfounded. A multi-year battery variant requires a
different low-power architecture and is not part of this release.
## Optional LF
The RC works without the EL-50448. It contains no validated LF receiver. A
future module requires a separate 125 kHz resonance/detection schematic, a
comparator threshold, filtering, an interference-immunity test, and proven
waking. The front-end output on GPIO14 is to be active-low and high at rest.
The activator itself does not enter IDs into the emulator.
+88
View File
@@ -0,0 +1,88 @@
# Energy and parking behaviour
## Measurement status
**No current measurements of the physical prototype have been performed.**
The numbers below are budget estimates, not validated results. The S2 Mini
is not suitable for declaring µA consumption without measurement: the built-in
regulator, LED, and auxiliary circuits add consumption. The LM317T itself
loads the supply with a divider current of about 5 mA (R1 = 240 Ω) plus its
own quiescent current, so a permanent supply needs a separate energy budget.
The target supply from an ignition-switched cigarette-lighter socket removes
this problem: with the ignition off the emulator draws no current at all.
## Firmware schedule
- NORMAL after the RTC wake: initialisation, a burst of four wheels, exit of
TX, and deep sleep. There is no 10-second console window after a plain wake.
- Micro-naps: sleep is split into pieces so that the LED blinks about every
2 s, also between transmissions (`NAP_PERIOD_MS` in `config.h`). After a
timer wake the device shows one visible blink and sleeps the rest of the
period after boot time + window (`NAP_AWAKE_MS`). The button wakes
immediately (EXT1) regardless of the micro-naps.
- TX of frames remains on the interval (default 30 s): the sleep counter in
RTC memory counts the slept pieces since the last TX cycle; `interval`
takes effect on the next cycle. After a longer awake period (e.g. `stay`),
the first piece is a full one.
- **Micro-naps raise consumption** (a boot about every 2 s instead of one
sleep per interval) — the numbers below describe the old model and require
HIL measurement.
- After power-on, a button, or LF: a 10 s console window; `stay N` extends it.
- LEARN: TX of one wheel every 2 s, without deep sleep, max 60 s per wheel/
15 min per session.
- SINGLE: TX of one wheel every 2 s, without deep sleep, max 5 min.
- The CC1101 enters SPWD before sleep; CS is high, SCK/MOSI low, LED off.
- Every sleep has an RTC alarm. `PARKING_SHUTDOWN` was removed — the device
cannot remain asleep until a purely manual wake.
- ACC (optional in hardware) selects the ignition/parking interval. It is not
needed as the only wake source, because the RTC always runs. If the whole
assembly is powered only from an ignition-switched lighter socket or from
ACC, then with ACC off there is no power, no RTC, and no transmission —
and that is the target scenario.
## Charge estimate for the default settings
One frame is 240 × 120 µs = 28.8 ms on air. For 4 wheels × 3 frames:
345.6 ms of transmission plus 8 × 50 ms gaps inside the bursts. On top of
that come boot, configuration, SPI, and logging. For energy calculations you
must measure the whole cycle, not just the OOK time.
An example model (to be replaced by measurement): if ESP32 activity is 1.0 s
at 80 mA every 30 s, the ESP32 alone averages about 2.7 mA at 3.3 V. The
CC1101, boot, and sleep current add further terms. With a 120 s interval the
activity share falls about fourfold, but the constant Iq of the regulator and
the dividers remains. These are not measured 2.7 mA nor a promise of
consumption from a 12 V battery.
## Measurement method required before "validated"
1. **The whole S2 Mini in sleep:** a µA meter in series at the input, not
through USB. Wait until TX ends and record the minimum/steady state and
the board model.
2. **S2 Mini + LM317T:** repeat the measurement on the protected VIN input
and on the 3.3 V rail. Include the regulator divider current, TVS, the
other dividers, and pull-ups.
3. **NORMAL cycle:** a shunt + oscilloscope or a logger with sufficient
bandwidth. Record boot, 12 frames, gaps, and entering sleep over at least
10 cycles.
4. **Average:** integrate the charge for at least 15 min at 30 s and 120 s.
State the conditions: voltage, temperature, PA, board and firmware
version.
5. **LEARN/SINGLE:** measure the continuous-awake current separately.
6. **ACC/brownout/crank:** check restart, the return to transmission, and NVS
integrity. Do not test on GPIO without confirmed input protection.
## Conclusions allowed before measurement
- The interval, awake time, PA, and the whole board's Iq have the largest
impact.
- A power-saving version requires measuring the whole S2 Mini and LM317T;
with power only from an ignition-switched lighter socket the assembly draws
no current after the ignition goes off, but then it also transmits no
parking mode — which matches the assumption, because the car ECU does not
listen then.
- We do not recommend an 18650 in the cabin, nor multi-year battery operation
with an ESP32.
- The emulator's constant consumption must be accounted for during a long
park; we do not give a "safe for the battery" time without measuring the
whole car.
+109
View File
@@ -0,0 +1,109 @@
# Schrader EG53MA4 protocol — facts and unknowns
## Pinned sources
| Source | Version used for validation | Scope |
|---|---|---|
| `rtl_433/src/devices/schraeder.c` | commit `406f9a33550a2b6b3d0d8a8a486417ce5b3f13ab` | decoder and slicer parameters |
| `rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01` | commit `1aa8c29d6b9383739d1aeed495dbc5069b704392` | four CU8 recordings + JSON |
| PlatformIO | 6.1.18 | build/test |
| `espressif32` | 8.0.0 | toolchain/ESP32 platform |
| SmartRC-CC1101-Driver-Lib | `de6757ef633b3e626dae5c7835cdb66ab53f9a1d` (3.0.2) | CC1101 configuration |
| Practical receiver analysis | <https://milek7.pl/tpmsreceiver/> | context; not a source of frame fields |
| ESP32+CC1101 integration pattern | <https://github.com/merbanan/rtl_433/issues/2978> | integration, not the EG53MA4 protocol |
We do not use the unlabelled `master` as a reproducible reference. The
commercial emulator <https://spooftpms.com/us-eu-gm-1-2-family-tpms-simulator/>
only confirms that such a class of device exists, not this project's
compatibility.
## Confirmed format after Manchester decoding
The decoder requires exactly 120 bits: 40 bits of synchronisation and 80 data
bits.
```text
0 40 72 96 104 112 120
| 40 × sync (0) | flags 4 B | ID 3 B | P 1 B | T 1 B | sum 1 B |
4C 90 00 70 2F C8 71 68 49 65
```
- `flags`: 32 bits; the field meanings are not fully known.
- `ID`: 24 bits; the firmware rejects 0, `FFFFFF`, and duplicates between
wheels.
- `P`: 2.5 kPa/bit **according to the rtl_433 decoder, but the scale is not
confirmed** — all four captures have `P = 0`, so no real pressure verified
the conversion (in the decoder source it is "probable"). A car measurement:
`P = 104` (260 kPa on the rtl_433 scale) shows up as **284 kPa**, so the
firmware corrects the scale with the constant
`TPMS_PRESSURE_KPA100_PER_RAW` (`tpms_frame.h`, default 273 = 2.73 kPa/bit;
`P = 95` for 260 kPa). Quantisation: `(kPa×100 + 136) / 273`. Calibration
confirmed on hardware: 260 kPa → 260 kPa on the car display (`AUDIT.md`).
- `T`: byte in °F per the decoder, not °C. 23 °C → 73 °F.
- `sum`: the sum of the nine preceding bytes modulo 256; it is not CRC-8.
- The value `4c900070` occurs in all 64 records of the four captures. That
does not prove that every sensor/car mode always uses this value.
## Polarity, preamble, and tail
The recordings and the `OOK_PULSE_MANCHESTER_ZEROBIT` slicer confirm G.E.T.
Manchester: `0 → 01`, `1 → 10`. The slicer prepends the first zero bit. The
CC1101 buffer contains:
```text
1 starting chip + 39 sync cells + 80 data cells + 1 OFF padding chip
= 240 chips = 30 bytes, MSB first.
```
The last padding chip is an OOK zero (silence). The test checks exactly this
length and polarity and rejects a truncated/corrupted buffer.
## Timing and repetitions
- The decoder has `short_width=123 µs`, `reset_limit=300 µs`.
- Analysis of `gfile001` shows a typical pulse+gap period of about 236 µs,
i.e. a chip of about **118 µs**; pulse widths differ from gap widths. The
firmware uses **120 µs** experimentally, which decodes on an independent
`rtl_433`. The exact clock of a physical CC1101 requires an HIL measurement.
- Each of the four recordings contains **16 valid repetitions**. In
`gfile001` the gaps between decode starts vary roughly 115–172 ms; they are
not constant.
- The defaults of **3 frames, a 50 ms gap, a 30 s cycle** are experimental
emulator settings, not a confirmed OE schedule. The ACC/parking intervals
also have no OE-compatibility status.
## Carrier and modulation
The base profile: **433.92 MHz, ASK/OOK**. The recordings are decoded at this
frequency. The kit's README also contains 315 MHz product data and a mention
of ASK+FSK; that is no evidence of FSK in the analysed files nor of
compatibility with the specific Astra. FSK is not available in the base
firmware/generator.
## CC1101 packet engine
The firmware sets fixed-length 30 B, a normal FIFO, MSB first, and disables
the hardware preamble/sync (`SYNC_MODE=0`), Manchester, whitening, FEC, CRC,
address check, and append status. The whole preamble and the protocol's sum
are inside our 30 bytes. End of TX is expected via `MARCSTATE=IDLE` with a
limit; `TXFIFO_UNDERFLOW` and leftover bytes are errors. This prevents the
tail from being truncated by `TXBYTES=0` alone.
The configuration has been audited, but the synthetic CU8 bypasses the
CC1101. The absence of extra bytes and the exact tail still have to be
confirmed on a logic analyser/RTL-SDR in HIL.
## Unknowns — they must not be "tuned" randomly
1. The meaning of individual `flags` bits, including any sensor low-battery
bit. **`TPMS_FLAGS_LOWBAT_MASK` does not exist in the firmware.**
2. The dependence of flags on learning, motion, LF, and the original sensor's
battery state.
3. The interval and minimal number of repetitions required by a specific ECU.
4. The compatibility of OE 13506028/a related part number with a specific
unit without a VIN, markings, a readout, or a test.
5. The physical accuracy of frequency, power, and the tail of the generated
CC1101 transmission before HIL.
Low emulator supply is only a console warning and does not change any field
of the simulated sensor.
+47
View File
@@ -0,0 +1,47 @@
# Safety and limitations
## Synthetic data can hide a fault
This device generates data it does not measure in the tyres. The default
260 kPa is a test value, not confirmation of pressure. The simulator may cause
the warning light not to alert about a real puncture, pressure loss or tyre
damage.
- A diagnostic and workshop project only, on a parked car and under the
control of the person running the test.
- It is not a homologated sensor nor a replacement for a working TPMS.
- Do not use while driving and do not present it as safe for that purpose.
- Before and after the test, check all tyres with an independent gauge and
inspect their condition.
- After the diagnosis, restore working, correctly matched sensors and perform
the vehicle's required procedure.
## Radio and vehicle compatibility
The EG53MA4/OOK 433.92 MHz profile is a working hypothesis for the vehicle
indicated, to be confirmed. OE 13506028, a related part number, or a
replacement offer is not enough. Use the VIN, factory sensor markings,
diagnostics, or a controlled test. Do not transmit at maximum power "to be
sure". Start at −10 dBm, limit transmission time, and follow local 433 MHz
regulations and rules about interfering with vehicle electronics. The device
may be received by other receivers nearby.
## Installation
- Only the laboratory prototype is described as ready to assemble. The 12 V
version requires a separate design and automotive tests.
- Do not apply 12 V to GPIO/ADC or 5 V to the CC1101.
- Do not place the device near airbags, pedals, moving parts, moisture, high
temperature, or the LPG installation.
- Secure the enclosure and cables against loosening. Avoid shielding the
antenna.
- Do not use an 18650 cell as the recommended power source in the cabin.
## Diagnostics without false confidence
Correct decoding by rtl_433 does not prove reception by the car. Green CI does
not replace a CC1101 measurement, an HIL test, or a tyre check. The warning
light going out also does not prove the tyres are sound. Record measurements
and do not change several parameters at once. There is no confirmed low
battery bit of the sensor; low emulator supply is not encoded as a fault of
the simulated sensor.
+111
View File
@@ -0,0 +1,111 @@
# Configuration and startup
## Before you start
1. Verify compatibility of the specific car (VIN, sensor markings,
diagnostics, or reception). Do not rely solely on a number from a listing.
2. Assemble the prototype per `HARDWARE.md`, flash the firmware, and open a
115200 UART.
3. Type `stay 300`. `info` shows the active configuration, not just the saved
one.
4. Work on a parked car. The synthetic 260 kPa does not describe the real
tyres.
Wheels: `1=FL` front left, `2=FR` front right, `3=RR` rear right, `4=RL` rear
left. Configuration commands save to NVS automatically and verify the read
back. An NVS error must be resolved before further testing, not ignored.
## Path A — Clone IDs (preferred)
Use it when the original IDs were read earlier and the car still knows them.
1. Write down four IDs as six-digit hex.
2. Enter in turn (replace the example values with your own):
```text
id 1 2FC871
id 2 2EAAF9
id 3 3495AC
id 4 2FC780
pressure all 260
info
```
3. Check in `info` that all IDs and wheel assignments are correct. A
duplicate, `000000`, `FFFFFF`, or a value beyond 24 bits will be rejected.
4. Optionally, `send` forces a cycle of all wheels. In NORMAL the device does
it automatically as well; after a restart the configuration remains.
5. Confirm reception externally. Known IDs **may** eliminate learning, but we
do not promise that for every ECU state.
Do not use the example IDs in a vehicle if they may coincide with another
device nearby.
## Path B — New IDs + LEARN
### Preparation
1. `ids new` generates four unique IDs. You can use four `id` commands
instead.
2. `info` — write the IDs down on paper.
3. Read the learning procedure for the specific model/equipment version. This
document does not guess menus, pedal sequences, or the receiver location.
4. Start the learning procedure in the car according to its service
instructions.
### Learning from the console
1. `mode learn` — starts at FL; only FL transmits every 2 s.
2. `send` — immediate FL burst, without changing the wheel.
3. After completing the step for FL: `next` — FR; the LED shows 2 blinks.
4. Repeat `send`, then `next` — RR, then `next` — RL.
5. After the last `next` the device returns to NORMAL. The order is always
**FL → FR → RR → RL**.
6. Finish the car procedure according to its instructions and check the
diagnostic readout.
### Learning with one button
- enter: hold ≥1.5 s;
- short press: next wheel and an immediate burst;
- force without changing the wheel: console `send`;
- exit before the end: hold ≥1.5 s again or `mode normal`.
A 60 s timeout per wheel aborts LEARN to NORMAL; the whole session limit is
15 min. This is not an automatic learning success — you have to start again
from the right wheel.
## SINGLE / diagnostics
`mode single 2` transmits only FR every 2 s. `send` forces FR, `next` moves
on. `mode normal` ends it; the automatic limit is 5 min. The mode does not
save the wheel selection in NVS and starts safely in NORMAL after a power
loss.
## Other settings
| Command | Range / effect |
|---|---|
| `pressure all 260` | 0–637.5 kPa, P byte step ≈ 2.73 kPa (calibrated per the car, `PROTOCOL.md`) |
| `temp all 23` | −40…85 °C; °F in the frame |
| `interval normal 30` | interval without ACC, 5–86400 s |
| `interval ignition 30` | with hardware ACC active |
| `interval parking 120` | without active ACC |
| `rf freq 433.92` | 433.05–434.79 MHz; changes require justification |
| `rf power -10` | −30, −20, −15, −10, −6, 0, 5 dBm |
| `rf burst 3` | 1–8 frames per wheel |
| `rf gap 50` | 20–500 ms between frames |
| `flags 4C900070` | experiment; bit meanings are unknown |
| `factory YES` | erases your configuration and restores defaults |
Schedule parameters are experimental. Power starts at −10 dBm; increase it
only after a measurement and with the regulations in mind. Low emulator
supply sets no sensor flag.
## After a restart or brownout
The firmware reads NVS again. A correct version/CRC and ranges are required.
A damaged or incompatible entry produces a message and a return to defaults,
rather than transmitting a partly corrupted configuration. Every deep sleep
has an alarm; there is no `PARKING_SHUTDOWN` mode that could leave the car
without transmission until a manual wake.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
# Troubleshooting
Work one change at a time and record the measurement. Do not switch OOK/FSK,
flags, IDs, or intervals randomly. The base firmware has no FSK mode.
| Symptom | Possible cause | Measurement / check | Repair |
|---|---|---|---|
| `ERROR: no CC1101` | poor supply, CS/SPI, module is not 433 MHz | 3.3 V across VCC-GND; continuity SCK/MISO/MOSI/CS = 4/5/6/7; module marking | fix wiring, shorten SPI, use the correct module |
| Reset during TX | 3.3 V droop, weak wires | voltage at the ESP32/CC1101 during `send`, brownout log | fix the supply and 47–100 µF at the module; do not raise the PA |
| `TX-ERR` | underflow, unfinished TX, wrong CC1101 configuration | log for each wheel; MARCSTATE/registers in HIL | check SPI and supply; save the log for analysis, do not mask the error |
| USB/UART does not respond | console window too short, wrong baud/port, charge-only cable | 115200 8N1, reset, correct `/dev/ttyACM*` or `/dev/ttyUSB*` | type `stay 300` right after startup; use a data cable |
| ID change disappears | NVS write error, full flash | `OK: saved` message, restart and `info` | do not continue on an NVS error; check flash/supply |
| ID rejected | duplicate, 0, FFFFFF, wrong length | six hex digits and `info` | transmit four unique IDs from 000001–FFFFFE |
| rtl_433 decodes nothing | antenna, frequency, wrong RF path, too little power | `send 1`; 433.92 MHz receiver close by; ANT/GDO0 measurement | fix antenna/supply; step through low powers gradually; do not switch to FSK |
| rtl_433 sees wrong data | stale configuration, neighbouring sensor | `info`, `hex 1`, ID filtering in the receiver | compare IDs and force `send 1` in an isolated spot |
| Car does not see known IDs | unconfirmed profile, ECU requires learning, range | VIN/markings/DTC; RTL-SDR reception at the car | confirm the profile; perform LEARN; change position after measuring |
| LEARN stuck on one wheel | used `send` instead of `next` | `info` shows the active wheel | `next` after confirming the step; `send` only forces TX |
| LEARN returned to NORMAL | 60 s per wheel / 15 min session | elapsed time, message and LED | run `mode learn 1` and consciously repeat from FL |
| After RL there is no next wheel | the sequence completed | NORMAL in `info` | finish the car procedure and check DTC |
| Warning light stays on although RTL-SDR is OK | ECU does not know the IDs, other profile/flags/procedure | read IDs and DTC from diagnostics, not only SDR | Clone IDs or LEARN; confirm the car profile; do not guess flags |
| High sleep consumption | S2 Mini, LM317T, LED, dividers | measure the whole board and regulator per `POWER.md` | fix the supply; do not change the protocol |
| No TX after parking | supply only from the lighter socket/ACC, brownout, NVS/CC1101 error | does 3.3 V remain after the ignition goes off; log after restart, `batt`, `info` | with an ignition-switched socket supply the lack of TX is expected; otherwise fix the supply |
| ACC does not change the interval | feature disabled by default or wrong threshold | `PIN_ACC`, voltage on GPIO OFF/ON | build a protected input; never 12 V on GPIO |
## When the car does not receive
Diagnostic sequence:
1. **Prove local TX:** `send 1` + RTL-SDR/analyser.
2. **Prove the correct profile:** VIN, sensor markings, car readout.
3. **Check IDs and order:** `info`, Clone IDs, or one active wheel in LEARN.
4. **Check range:** low power first, console/behind the glovebox, possibly the
boot; without disassembling airbags or guessing the ECU location.
5. **Only then analyse flags:** compare with a recording of the original
sensor in the same mode. There is no confirmed low-battery bit — do not
set it.
6. If there is no measurement or data, stop the test. Random changes add new
variables and are not a diagnosis.
+130
View File
@@ -0,0 +1,130 @@
# Validation
## One command without hardware
```bash
bash tools/check_all
```
The script runs the Python self-test, native tests, the full ESP32 build,
cppcheck, fetching the pinned sources (on first run), and CU8 decoding by the
real `rtl_433`. Logs: `artifacts/validation/`. Every stage has `pipefail`,
and an error ends the script with a non-zero code.
A reproducible alternative:
```bash
docker build -t tpms-rc .
docker run --rm -v "$PWD/artifacts:/work/artifacts" tpms-rc
```
## Results from 2026-10-28
Environment: Linux, Python 3.14.4 on the host test; PlatformIO 6.1.18;
espressif32 8.0.0; Arduino ESP32 3.3.12; SmartRC CC1101 commit
`de6757ef633b3e626dae5c7835cdb66ab53f9a1d`; rtl_433 commit `406f9a3…`;
rtl_433_tests commit `1aa8c29…`. Full SHAs are in `PROTOCOL.md`.
| Command | Result |
|---|---|
| `pio test -e native` | **24/24 PASS** — frame, four independent vectors, negative tests, NVS, console parsing (NaN/ranges), fake clock/radio, Clone IDs, LEARN, SINGLE, ACC, restart |
| `pio run -e esp32s2mini` | **PASS**, own warnings treated as errors (`-Werror`) |
| `pio check -e native ... --fail-on-defect=low` | **PASS**, 0 defects after the struct initialisation fix |
| `python3 tools/tpms_frame.py --self-test` | **PASS**, capture + 500 frames |
| `tools/verify_rtl433.sh` | **PASS**, 64/64 reference records; 3/3 synthetic; 3/3 negative rejected |
| `git diff --check` | **PASS** |
| `bash tools/package_release.sh` | **PASS**, ESP32-S2 image with the bootloader at `0x1000` and a SHA-256 manifest |
Reference data: each of `gfile001`…`gfile004` produced exactly 16 matching
records, with the expected ID/flags/pressure/temperature. The synthetic frames
2FC871/260 kPa/73 F, 3495AC/220 kPa/23 F and ABCDEE/262.5 kPa/75 F were
decoded by an independent `rtl_433`. Damaged Manchester, a wrong sum, and
truncation produced no EG53MA4 record.
## Coverage matrix
| Layer | Automated | Physical RTL-SDR | Physical CC1101 | Car |
|---|---|---|---|---|
| fields, checksum, quantisation | done | not needed for the field | not needed | confirmation of ECU interpretation |
| Manchester/preamble/length | done | **not done** | **not done** | not done |
| real recordings → rtl_433 | done, 64/64 | n/a | n/a | n/a |
| synthetic CU8 → rtl_433 | done | n/a | bypasses hardware | n/a |
| CC1101 registers/tail/power/frequency | code audit | required | **required** | required |
| NVS, IDs, intervals, modes | done; NVS emulated with a blob | a restart test is required | required | required |
| LEARN FL→FR→RR→RL | state machine PASS | auxiliary | required | **not done** |
| consumption/brownout/ACC | ACC in the state machine; no measurements | n/a | required | required |
**There is no basis for a "validated" label.** Gitea Actions has a workflow,
but the runner state and the remote CI result must be checked; a local PASS
is not pretend CI.
## HIL checklist — requires a user and hardware
### CC1101 + analyser/RTL-SDR
- [ ] Read the registers after initialisation: OOK, 433.92 MHz, fixed 30 B,
`SYNC_MODE=0`, no CRC/Manchester/whitening/FEC/append.
- [ ] On GDO0/ANT confirm exactly 30 B, a ~120 µs chip, a full last chip, and
no hardware preamble/sync/CRC/extra bytes.
- [ ] Record TX-ERR/underflow; there should be none on a correct RF path.
- [ ] Measure the frequency and relative power at −10 dBm; do not assume the
calibration of a cheap module. Do not raise the PA unnecessarily.
- [ ] `send 1`…`send 4`: RTL-SDR decodes the correct IDs, 260 kPa and flags.
- [ ] Repeat after a reset and 10 deep sleep cycles.
### NVS and inputs
- [ ] Set your own IDs/pressures/RF, disconnect power for >1 min, and re-check
`info` and transmission.
- [ ] Verify rejection of a duplicate ID, a bad power, and a bad interval.
- [ ] `factory YES` restores 260 kPa and the default RF.
- [ ] Brownout/crank on a protected supply: no hang or configuration damage;
write settings only after the supply stabilises.
- [ ] If ACC is installed: measure the GPIO voltage for OFF/ON/transients,
check the intervals and automatic resumption after ACC ON. Skip without
ACC.
### The specific Opel Astra J
- [ ] Confirm the profile via VIN/markings/diagnostics before transmitting.
- [ ] Clone IDs: reception of the four known IDs without assuming learning
will vanish.
- [ ] New IDs: full learning FL→FR→RR→RL with one active wheel.
- [ ] DTC and TPMS data read before/after; record the ECU version and
procedure.
- [ ] Position test: centre console/behind the glovebox, possibly the boot;
while parked, without guessing the receiver location.
- [ ] A tyre gauge check of all wheels before and after. Do not perform the
test as a road drive with the simulator in place of a working TPMS.
## Artifacts and flashing
```bash
bash tools/package_release.sh
```
The `artifacts/release/` directory:
| File | Address |
|---|---:|
| `bootloader.bin` | `0x1000` — the address for ESP32-S2, not `0x0` as in ESP32-C3 |
| `partitions.bin` | `0x8000` |
| `boot_app0.bin` | `0xE000` |
| `firmware.bin` | `0x10000` |
| `firmware-full.bin` | `0x0` — the full 4 MB image |
| `firmware.elf` | debug/symbols, do not flash it |
| `SHA256SUMS`, `BUILD-INFO.txt` | integrity and version check |
The full image erases the previous flash while writing the whole area; NVS in
that partition may be lost — write down your IDs before updating with the
full image. Updating only the application `firmware.bin` at `0x10000`
usually preserves NVS, but before a release the user should test it on their
own module.
```bash
PORT=/dev/ttyACM0 bash tools/flash_release.sh
(cd artifacts/release && sha256sum -c SHA256SUMS)
```
Do not flash an image from another toolchain blindly. The RC contains no
physical update test or car test.
+24 -17
View File
@@ -1,35 +1,42 @@
; PlatformIO - symulator czujnikow TPMS Schrader EG53MA4 (ESP32 + CC1101)
; PlatformIO - Schrader EG53MA4 TPMS sensor simulator (ESP32 + CC1101)
;
; Kompilacja: pio run -e esp32dev
; Testy: pio test -e native
; Upload: pio run -e esp32dev -t upload
; Monitor: pio device monitor
; Build: pio run -e esp32s2mini
; Tests: pio test -e native
; Upload: pio run -e esp32s2mini -t upload
; Monitor: pio device monitor
;
; Zastrzezenie: projekt diagnostyczny/testowy - symulator generuje
; sztuczne dane cisnienia, nie zastepuje prawdziwych czujnikow TPMS.
; Disclaimer: diagnostic/test project - the simulator generates
; synthetic pressure data and does not replace real TPMS sensors.
[platformio]
default_envs = esp32dev
default_envs = esp32s2mini
[env:esp32dev]
; Wersje przypiete do zweryfikowanego buildu (espressif32 8.0.0,
[env:esp32s2mini]
; Versions pinned to the verified build (espressif32 8.0.0,
; SmartRC-CC1101-Driver-Lib 3.0.2 = commit de6757e)
platform = espressif32@8.0.0
board = esp32dev
; ESP32-S2-MINI (ESP32-S2FN4R2, e.g. ARD-ESP32-S2-MINI): a Lolin/Wemos
; S2 Mini type board; sold with MicroPython, we flash our own firmware.
board = lolin_s2_mini
framework = arduino
monitor_speed = 115200
; Biblioteka CC1101 (ELECHOUSE_CC1101_SRC_DRV / SmartRC):
; wymagana wersja >= 2.5.7 (wspolne API setSpiPin/setGDO0 dla 2.5.x i 3.x).
; CC1101 library (ELECHOUSE_CC1101_SRC_DRV / SmartRC):
; version >= 2.5.7 required (shared setSpiPin/setGDO0 API for 2.5.x and 3.x).
lib_deps =
https://github.com/LSatan/SmartRC-CC1101-Driver-Lib.git#de6757e
https://github.com/LSatan/SmartRC-CC1101-Driver-Lib.git#de6757ef633b3e626dae5c7835cdb66ab53f9a1d
build_flags =
-Wall
-Wextra
-Werror
; Native ESP32-S2 USB: Serial console and flashing without a UART bridge.
; ARDUINO_USB_MODE remains the default for lolin_s2_mini (=0).
-DARDUINO_USB_CDC_ON_BOOT=1
[env:native]
; Testy jednostkowe generatora ramek (bez sprzetu)
; Portable logic: frame, NVS, console parsing and the state machine
; (PIN_ACC enabled in tests).
platform = native
build_flags = -std=gnu++17 -Wall
build_src_filter = -<*> +<tpms_frame.cpp>
build_flags = -std=gnu++17 -Wall -Wextra -Werror -DPIN_ACC=2
build_src_filter = -<*> +<tpms_frame.cpp> +<settings.cpp> +<app_state.cpp> +<parse.cpp>
test_build_src = true
test_framework = unity
+5 -30
View File
@@ -1,40 +1,15 @@
/*
* app.h - API aplikacji (tryby pracy) uzywane przez konsole i maszyne stanow
*/
#ifndef TPMS_APP_H
#define TPMS_APP_H
#include <stdint.h>
#include "app_state.h"
#ifdef __cplusplus
extern "C" {
#endif
enum {
APP_MODE_NORMAL = 0, // rotacja wszystkich 4 kol + deep sleep
APP_MODE_LEARN = 1, // nauka czujnikow w aucie, jedno kolo naraz
APP_MODE_SINGLE = 2, // wymuszone nadawanie wskazanego ID
};
uint8_t app_mode(void);
uint8_t app_wheel(void); // aktywne kolo (w LEARN/SINGLE)
void app_set_mode(uint8_t mode, uint8_t wheel);
void app_next_wheel(void);
void app_send_burst_wheel(uint8_t wheel);
void app_send_burst_all(void);
extern AppState *g_app;
void app_print_info(void);
void app_print_frame(uint8_t wheel);
bool app_save_and_apply(void);
void app_request_sleep(void);
void app_stay_awake(uint32_t ms);
uint32_t app_supply_mv(void);
void app_set_interval(uint32_t seconds); // 0 = automatyczny (wg ACC)
void app_set_flags(uint32_t flags);
void app_request_sleep(void); // zaspij teraz (tryb NORMAL)
void app_stay_awake(uint32_t ms); // przedluz okno konsoli
#ifdef __cplusplus
}
#endif
#endif /* TPMS_APP_H */
+147
View File
@@ -0,0 +1,147 @@
#include "app_state.h"
#include "config.h"
AppState::AppState(const settings_t *settings, RadioSink *radio)
: settings_(settings), radio_(radio)
{
}
void AppState::begin(uint32_t now_ms, bool transmit)
{
set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, transmit);
}
uint32_t AppState::interval_s(bool ignition) const
{
#if PIN_ACC >= 0
return ignition ? settings_->ignition_interval_s : settings_->parking_interval_s;
#else
(void)ignition;
return settings_->normal_interval_s;
#endif
}
bool AppState::transmit(uint8_t wheel)
{
bool ok = radio_ != NULL && radio_->send(wheel);
if (!ok) {
++error_count_;
}
return ok;
}
bool AppState::send_current()
{
return transmit(active_wheel_);
}
bool AppState::send_wheel(uint8_t wheel)
{
return wheel < WHEEL_COUNT && transmit(wheel);
}
bool AppState::send_all()
{
bool ok = true;
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
ok = transmit(i) && ok;
}
return ok;
}
void AppState::schedule(uint32_t now_ms, bool immediate)
{
next_tx_ms_ = immediate ? now_ms : now_ms + LEARN_PERIOD_MS;
}
bool AppState::set_mode(AppMode mode, uint8_t wheel, uint32_t now_ms,
bool transmit_now)
{
if (wheel >= WHEEL_COUNT) {
return false;
}
mode_ = mode;
active_wheel_ = wheel;
mode_start_ms_ = now_ms;
wheel_start_ms_ = now_ms;
schedule(now_ms, transmit_now);
if (mode == AppMode::NORMAL) {
next_tx_ms_ = transmit_now ? now_ms : UINT32_MAX;
}
if (transmit_now && mode != AppMode::NORMAL) {
send_current();
schedule(now_ms, false);
} else if (transmit_now) {
send_all();
next_tx_ms_ = now_ms + settings_->normal_interval_s * 1000u;
}
return true;
}
bool AppState::next_wheel(uint32_t now_ms)
{
if (mode_ == AppMode::NORMAL) {
return false;
}
if (mode_ == AppMode::LEARN && active_wheel_ == WHEEL_RL) {
return set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, false);
}
active_wheel_ = (uint8_t)((active_wheel_ + 1u) % WHEEL_COUNT);
wheel_start_ms_ = now_ms;
send_current();
schedule(now_ms, false);
return true;
}
void AppState::short_press(uint32_t now_ms)
{
if (mode_ == AppMode::NORMAL) {
send_all();
next_tx_ms_ = now_ms + settings_->normal_interval_s * 1000u;
} else {
next_wheel(now_ms);
}
}
void AppState::long_press(uint32_t now_ms)
{
if (mode_ == AppMode::LEARN) {
set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, false);
} else {
set_mode(AppMode::LEARN, active_wheel_, now_ms);
}
}
void AppState::very_long_press(uint32_t now_ms)
{
if (mode_ == AppMode::SINGLE) {
set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, false);
} else {
set_mode(AppMode::SINGLE, active_wheel_, now_ms);
}
}
void AppState::tick(uint32_t now_ms, bool ignition)
{
if (mode_ == AppMode::LEARN) {
if ((uint32_t)(now_ms - mode_start_ms_) >= LEARN_TOTAL_MS
|| (uint32_t)(now_ms - wheel_start_ms_) >= LEARN_WINDOW_MS) {
set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, false);
return;
}
} else if (mode_ == AppMode::SINGLE
&& (uint32_t)(now_ms - mode_start_ms_) >= SINGLE_TIMEOUT_MS) {
set_mode(AppMode::NORMAL, WHEEL_FL, now_ms, false);
return;
}
if (next_tx_ms_ != UINT32_MAX && (int32_t)(now_ms - next_tx_ms_) >= 0) {
if (mode_ == AppMode::NORMAL) {
send_all();
next_tx_ms_ = now_ms + interval_s(ignition) * 1000u;
} else {
send_current();
schedule(now_ms, false);
}
}
}
+61
View File
@@ -0,0 +1,61 @@
/* Portable NORMAL/LEARN/SINGLE state machine (fake clock/radio in tests). */
#ifndef TPMS_APP_STATE_H
#define TPMS_APP_STATE_H
#include <stdint.h>
#include "settings.h"
enum class AppMode : uint8_t {
NORMAL = 0,
LEARN = 1,
SINGLE = 2,
};
class RadioSink {
public:
virtual ~RadioSink() = default;
virtual bool send(uint8_t wheel) = 0;
};
class AppState {
public:
AppState(const settings_t *settings, RadioSink *radio);
void begin(uint32_t now_ms, bool transmit = true);
void tick(uint32_t now_ms, bool ignition);
void short_press(uint32_t now_ms);
void long_press(uint32_t now_ms);
void very_long_press(uint32_t now_ms);
bool set_mode(AppMode mode, uint8_t wheel, uint32_t now_ms,
bool transmit = true);
bool next_wheel(uint32_t now_ms);
bool send_current();
bool send_wheel(uint8_t wheel);
bool send_all();
AppMode mode() const { return mode_; }
uint8_t active_wheel() const { return active_wheel_; }
uint32_t interval_s(bool ignition) const;
uint32_t last_error_count() const { return error_count_; }
private:
static const uint32_t LEARN_PERIOD_MS = 2000u;
static const uint32_t LEARN_WINDOW_MS = 60000u;
static const uint32_t LEARN_TOTAL_MS = 900000u;
static const uint32_t SINGLE_TIMEOUT_MS = 300000u;
const settings_t *settings_;
RadioSink *radio_;
AppMode mode_ = AppMode::NORMAL;
uint8_t active_wheel_ = WHEEL_FL;
uint32_t next_tx_ms_ = 0;
uint32_t mode_start_ms_ = 0;
uint32_t wheel_start_ms_ = 0;
uint32_t error_count_ = 0;
bool transmit(uint8_t wheel);
void schedule(uint32_t now_ms, bool immediate);
};
#endif
+61 -179
View File
@@ -1,190 +1,72 @@
/*
* config.h - konfiguracja symulatora czujnikow TPMS Schrader EG53MA4
* dla Opla Astry J Sedan 2016 (EU, TPMS bezposredni, czujniki Schrader).
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ZASTRZEZENIE / DISCLAIMER:
* Projekt wylacznie do celow diagnostycznych i testowych.
* Symulator dostarcza SZTUCZNE dane cisnienia i temperatury i NIE
* zastepuje prawdziwych czujnikow TPMS. Nie uzywaj tego urzadzenia do
* jazdy po drogach publicznych - prawdziwy TPMS jest elementem
* bezpieczenstwa czynnego pojazdu.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* Protokol wg rtl_433 src/devices/schraeder.c (schrader_EG53MA4):
* "Schrader TPMS EG53MA4, Saab, Opel, Vauxhall, Chevrolet"
* (Opel OEM 13348393), weryfikacja: tools/tpms_frame.py, tools/gen_cu8.py.
*/
/* Hardware configuration. Sensor and RF data live in NVS, no recompile needed. */
#ifndef TPMS_CONFIG_H
#define TPMS_CONFIG_H
#define FW_VERSION "1.0.0"
#define CONFIG_VERSION 4 // podnos przy zmianie formatu danych w RTC
#define FW_VERSION "2.0.0-rc.1"
/* ======================================================================
* 1. ZASILANIE
* POWER_12V - stale zasilanie z akumulatora 12 V.
* UWAGA: potrzebny jest uklad zasilajacy na PELENY zakres
* samochodowy (12 V nominalnie, 14,4 V przy ladowaniu, przepiecia
* load-dump nawet > 40 V):
* - LDO o wejsciu >= 16 V i niskim Iq, np. MCP1703 (Vin 2.7-16 V,
* Iq ~2 uA) - zabezpiecz wejscie bezpiecznikiem + TVS (np. 24 V)
* + rezystor szeregowy/dioda; ogranicz moc strat (patrz README),
* - albo przetwornica buck o szerokim wejsciu, np. LM5164-Q1
* (Vin 6-100 V, Iq ~10 uA, 1 A).
* TPS62740 ma wejscie 2.2-5.5 V - NIE wolno podlaczac go do 12 V!
* POWER_BATTERY - ogniwo 3.6 V (Li-SOCl2) bezposrednio, albo LiPo 3.7 V
* PRZEZ LDO 3.3 V (np. MCP1700, Vin max 6 V). Bezposrednie
* zasilanie LiPo 4.2 V przekracza max ESP32 (3.6 V) i CC1101 (3.9 V)!
* ====================================================================== */
#define POWER_SUPPLY_MODE POWER_12V
#define POWER_12V 1
#define POWER_BATTERY 2
/* ESP32-S2-MINI (ESP32-S2FN4R2) + CC1101 433 MHz (3.3 V).
* GPIO19/20 are native USB, GPIO26-32 serve in-package flash/PSRAM,
* GPIO45/46 are strapping pins - do not use them for the CC1101. */
#define PIN_CC1101_SCK 4
#define PIN_CC1101_MISO 5
#define PIN_CC1101_MOSI 6
#define PIN_CC1101_CS 7
#define PIN_CC1101_GDO0 10
/* ======================================================================
* 2. PINY (ESP32 DevKit + CC1101 po SPI)
* Piny CC1101 zgodne z wymaganiami projektu:
* SCK=18 MISO=19 MOSI=23 CS=5 GDO0=2
* ====================================================================== */
#define PIN_CC1101_SCK 18
#define PIN_CC1101_MISO 19
#define PIN_CC1101_MOSI 23
#define PIN_CC1101_CS 5
#define PIN_CC1101_GDO0 2
/* Control button and wake from deep sleep: the board's BOOT button
* (GPIO0 to GND), confirmed by a bench test. GPIO0 is a strapping pin:
* held during power-up/reset it starts the bootloader instead of the firmware.
* An external momentary button can be wired to GPIO3 instead, selecting
* -DPIN_BUTTON=3 in build_flags. */
#ifndef PIN_BUTTON
#define PIN_BUTTON 0
#endif
#define BTN_ACTIVE_LEVEL 0
/* The S2 Mini's built-in blue LED on GPIO15 is active-high. */
#define PIN_LED 15
#define LED_ACTIVE_LEVEL 1
/* Przycisk sterowania trybami (wejscie budzace EXT0).
* Dolaczenie do GND + rezystor podciagajacy 10k do 3V3 (aktywny niski). */
#define PIN_BUTTON 26
#define BTN_ACTIVE_LEVEL 0 // 0 = aktywny niski (przycisk -> GND)
/* Options disabled until the hardware is assembled and tested. */
#ifndef PIN_LF_TRIGGER
#define PIN_LF_TRIGGER -1
#endif
/* LF shares the button's GPIO wakeup LOW; on ESP32-S2 wakeup requires an
* RTC pin (GPIO0-21). GPIO14 is suggested because GPIO1 holds the supply ADC. */
#define LF_ACTIVE_LEVEL 0
#ifndef PIN_ACC
#define PIN_ACC -1
#endif
#ifndef PIN_VBAT_ADC
#define PIN_VBAT_ADC 1
#endif
/* Divider measures the 12 V supply (LOWBATT threshold 11.5 V). R2 = 180 kOhm
* gives the ADC a full-scale range of about 16.4 V at 2.5 V full scale (11 dB):
* a 14.8 V charge voltage yields 2.25 V at the pin, so the reading saturates
* no earlier. The previous 270 kOhm divider saturated the ADC at ~11.8 V. */
#define VBAT_DIVIDER_R1 1000000.0f
#define VBAT_DIVIDER_R2 180000.0f
#define VBAT_CAL 1.000f
#define VBAT_SAMPLES 16
#define LOWBATT_THRESHOLD_MV 11500
/* LED statusowy (rezystor szeregowy 330R, aktywny wysoki). */
#define PIN_LED 27
/* The only production profile: OOK, Manchester 0->01, 1->10. */
#define TPMS_CHIP_US 120u
/* Opcjonalne wejscie aktywacji LF 125 kHz (cewka + prostownik + tranzystor).
* Impuls wysoki = "programator przy kole" -> natychmiastowa transmisja.
* -1 wylacza funkcje (role pelni przycisk "aktywuj kolo"). */
#define PIN_LF_TRIGGER 25
/* Schedule and initial power: settings_defaults() in settings.cpp.
* These are experimental parameters, not a confirmed OE schedule. */
#define BOOT_STAY_AWAKE_MS 10000u
/* Opcjonalny sygnal zaplonu / ACC (dzielnik 12 V -> ok. 3 V, jak VBAT).
* Bez podciagania wewnetrznego (INPUT) - dolna galaz dzielnika wymusza
* stan niski. Bez sygnalu: PIN_ACC = -1 (wtedy stale TX_INTERVAL_S).
* DOMYSLNIE -1 (wylaczone) - ustaw np. 32 po podlaczeniu dzielnika. */
#define PIN_ACC -1
/* Micro-naps: instead of one long sleep the LED blinks every NAP_PERIOD_MS,
* also between transmissions. Sleep is the remainder of the period after
* boot time + window, and TPMS frame TX remains on the interval (counter
* in RTC memory). */
#define NAP_PERIOD_MS 2000u
#define NAP_AWAKE_MS 400u /* visible LED blink after the timer wake */
#define NAP_MIN_SLEEP_MS 200u
#define SERIAL_BAUD 115200
/* Pomiar napiecia zasilania: dzielnik R1(gora)/R2(dol) na pin ADC1
* + kondensator 100 nF miedzy pinem a masa (ustalanie ADC).
* Dobor: 14,4 V (ladowanie) musi dac <= 3.0 V na wejsciu ADC,
* a prad dzielnika ma byc mikroamperowy (nie psuc budzetu snu):
* R1 = 1 M, R2 = 270 k -> 12 V: 2.55 V (~9 uA), 14.4 V: 3.05 V
* Zabezpieczenie wejscia: rezystor szeregowy + dioda klamujaca do 3V3. */
#define PIN_VBAT_ADC 34
#define VBAT_DIVIDER_R1 1000000.0f // ohm, gora (do zasilania)
#define VBAT_DIVIDER_R2 270000.0f // ohm, dol (do masy)
#define VBAT_CAL 1.000f // mnoznik kalibracji (por. z multimetrem)
#define VBAT_SAMPLES 16
#define BTN_DEBOUNCE_MS 30u
#define BTN_LONG_MS 1500u
#define BTN_VERYLONG_MS 4000u
/* ======================================================================
* 3. CZUJNIKI - 4 identyfikatory (hex, po jednym na kolo)
* Kolejnosc nauki w Astrze: przod lewy -> przod prawy -> tyl prawy -> tyl lewy
* ID sa przykladowe (24-bit). Najlepiej przepisz ID ze starych czujnikow
* (odczytaj je rtl_433: rtl_433 -f 433.92M) - auto wtedy "widzi" znajome ID.
* ====================================================================== */
#define WHEEL_FL 0
#define WHEEL_FR 1
#define WHEEL_RR 2
#define WHEEL_RL 3
#define WHEEL_COUNT 4
/* Kolejnosc nauki (kolejnosc pozycji w tablicy SENSOR[] ponizej = kolejnosc
* learn; domyslnie FL -> FR -> RR -> RL). Kolejnosc mozesz zmienic po prostu
* przestawiajac wpisy w tablicy SENSOR[] w main.cpp (lub zmieniajac ponizsze
* makra kolejnosci w trybie learn). */
#define LEARN_ORDER_0 WHEEL_FL
#define LEARN_ORDER_1 WHEEL_FR
#define LEARN_ORDER_2 WHEEL_RR
#define LEARN_ORDER_3 WHEEL_RL
/* ID poszczegolnych kol (24 bity) */
#define SENSOR_FL_ID 0x2FC871u
#define SENSOR_FR_ID 0x2EAAF9u
#define SENSOR_RR_ID 0x3495ACu
#define SENSOR_RL_ID 0x2FC780u
/* Cisnienie startowe: DOMYSLNIE 2,6 bar = 260 kPa dla wszystkich kol.
* Rozdzielczosc protokolu: 2,5 kPa/bit (0-637,5 kPa). */
#define SENSOR_FL_PRESS_KPA 260.0f
#define SENSOR_FR_PRESS_KPA 260.0f
#define SENSOR_RR_PRESS_KPA 260.0f
#define SENSOR_RL_PRESS_KPA 260.0f
/* Temperatura otoczenia (st. C) - konwertowana na st. F wg protokolu. */
#define SENSOR_TEMP_C 23
/* ======================================================================
* 4. PARAMETRY RF (Schrader EG53MA4)
* - dane: Manchester G.E.T. MC, chip = 120 us (8.33 kBaud)
* - nośna 433.92 MHz
* - modulacja: ASK/OOK (domyślna - tak pracuje referencyjny EG53MA4 z
* nagran rtl_433_tests i tak dekoderuje wbudowany Schrader-EG53MA4)
* albo 2-FSK z dewiacja 47.6 kHz (wariant konfigurowalny - jesli Twoj
* nadajnik/odbiornik auta pracuje FSK, przełacz MODE_FSK).
* ====================================================================== */
#define MODE_OOK 0
#define MODE_FSK 1
#define TPMS_FREQUENCY_MHZ 433.92f
#define TPMS_MODULATION MODE_OOK
#define TPMS_DEVIATION_KHZ 47.6f // dla MODE_FSK
#define TPMS_TX_POWER_DBM 10 // -30,-20,-15,-10,-6,0,5,7,10,11,12
#define TPMS_CHIP_US 120 // czas trwania jednego chipa Manchester
// (8.33 kBaud - zmierzone na nagraniach)
/* Ramka (dane z dekodera rtl_433 schrader_EG53MA4):
* 40 bit sync + 4 bajty flags + 3 bajty ID + cisnienie + temperatura + CRC.
* Suma kontrolna: suma 9 bajtow modulo 256 (add_bytes). */
#define TPMS_FLAGS 0x4C900070u // flags ze zrzutow prawdziwych czujnikow
#define TPMS_FLAGS_LOWBAT_MASK 0x00000008u // bit "rozladowana bateria"
// (pozycja niepewna - dostosuj
// jesli Twoj sterownik oczekuje
// innego bitu)
/* ======================================================================
* 5. HARMONOGRAM NADAWANIA / SEN
* ====================================================================== */
#define TX_BURST_FRAMES 3 // 3-6 ramek w burście (jak prawdziwy czujnik)
#define TX_FRAME_GAP_MS 50 // odstep miedzy ramkami w burscie
#define TX_INTERVAL_S 30 // interwal: kazde kolo co 30 s
#define TX_INTERVAL_IGNITION_S 15 // krotki interwal przy zaplonie (ACC)
#define TX_INTERVAL_PARKING_S 120 // interwal postojowy po zaniku ACC
#define ACC_GRACE_MS (5UL*60UL*1000UL) // 5 min po zaniku ACC
#define PARKING_SHUTDOWN 0 // 1 = po ACC_GRACE calkowite uspienie
// (sen bez budzika, obudza przycisk/LF)
#define BOOT_STAY_AWAKE_MS 3000 // okno na konsoli szeregowej po starcie
/* ======================================================================
* 6. TRYB LEARN / SINGLE
* ====================================================================== */
#define LEARN_TX_PERIOD_MS 2000 // co ile ms wysylac bursta w learn
#define LEARN_WINDOW_MS 60000 // okno czasowe na 1 czujnik (60 s)
#define LEARN_WINDOW_EXPIRE_TO_NORMAL 1 // 1 = po uplywie okna powrot do
// trybu normalnego (wg specyfikacji),
// 0 = automatycznie kolejne kolo,
// po ostatnim -> NORMAL
#define LEARN_TOTAL_TIMEOUT_MS 900000 // bezpiecznik: 15 min i koniec learn
#define SINGLE_TIMEOUT_MS 300000 // 0 = bez limitu
/* ======================================================================
* 7. PROGI / DIAGNOSTYKA
* ====================================================================== */
#define LOWBATT_THRESHOLD_MV 11500 // dla POWER_12V (prog alarmu TPMS)
// dla POWER_BATTERY ustaw np. 3200
#define SERIAL_BAUD 115200
/* ======================================================================
* 8. GESTY PRZYCISKU
* ====================================================================== */
#define BTN_DEBOUNCE_MS 30
#define BTN_LONG_MS 1500 // >= 1.5 s = wejscie/wyjscie LEARN
#define BTN_VERYLONG_MS 4000 // >= 4 s = wejscie/wyjscie SINGLE
#endif /* TPMS_CONFIG_H */
#endif
+221 -177
View File
@@ -1,202 +1,250 @@
/*
* console.cpp - debugowa konsola szeregowa (bez String i bez malloc)
*
* Komendy:
* help - lista komend
* info - wersja, konfiguracja, stan, napiecie
* hex [n|all] - hexdump ramki TPMS dla kola n (1-4) lub wszystkich
* send [n|all] - wyslij burst ramki teraz
* batt - odczyt stanu baterii (napiecie zasilania)
* mode normal|learn|single [n] - zmiana trybu
* next - kolejne kolo (learn/single)
* interval <s> - reczy ustalony interwal (0 = auto wg ACC)
* flags <hex> - slowo flags wyslane w ramce
* sleep - deep sleep teraz
* stay [s] - zostan w stanie czuwania jeszcze s sekund
*
* Parser jest scisly: zly argument = komunikat bledu, bez dzialania
* ubocznego (np. "send bla" NIE nadaje wszystkich kol).
*/
/* Serial console: configuration stored in NVS, no recompilation needed. */
#include <Arduino.h>
#include <esp_system.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "config.h"
#include "app.h"
#include "console.h"
#include "parse.h"
#include "power.h"
#include "settings_store.h"
static char line[64];
static uint8_t line_len = 0;
static bool line_overflow = false;
static char line[96];
static uint8_t line_len;
static bool line_overflow;
static void cmd_help(void)
static bool parse_wheel(const char *text, uint8_t *wheel, bool allow_all = false)
{
Serial.println(F("Komendy:"));
Serial.println(F(" help - ta pomoc"));
Serial.println(F(" info - wersja/config/stan/napiecie"));
Serial.println(F(" hex [n|all] - hexdump ramki kola n (1-4)"));
Serial.println(F(" send [n|all] - nadaj burst teraz"));
Serial.println(F(" batt - napiecie zasilania [mV]"));
Serial.println(F(" mode normal|learn|single [n] - tryb pracy"));
Serial.println(F(" next - kolejne kolo (learn/single)"));
Serial.println(F(" interval <s> - interwal nadawania (0=auto)"));
Serial.println(F(" flags <hex> - slowo flags w ramce"));
Serial.println(F(" sleep - deep sleep teraz"));
Serial.println(F(" stay [s] - czuwaj jeszcze s sekund"));
}
/* Scisly parser liczby calkowitej bez znaku z zakresem. */
static bool parse_u32(const char *s, uint32_t lo, uint32_t hi, uint32_t *out,
int base)
{
if (s == NULL || *s == '\0') {
if (allow_all && text != NULL && strcmp(text, "all") == 0) {
*wheel = 0xFFu;
return true;
}
uint32_t value;
if (!parse_u32(text, 1u, WHEEL_COUNT, &value)) {
return false;
}
errno = 0;
char *end = NULL;
unsigned long v = strtoul(s, &end, base);
if (errno != 0 || end == s || *end != '\0') {
return false;
}
if (v < (unsigned long)lo || v > (unsigned long)hi) {
return false;
}
*out = (uint32_t)v;
*wheel = (uint8_t)(value - 1u);
return true;
}
/* Numer kola 1-4 -> indeks 0-3; "all" -> 0xFF; blad -> -1. */
static int parse_wheel(const char *arg, uint8_t *wheel)
static void cmd_help(void)
{
if (arg == NULL) {
return -1;
}
if (strcmp(arg, "all") == 0) {
*wheel = 0xFF;
return 0;
}
uint32_t n = 0;
if (!parse_u32(arg, 1, WHEEL_COUNT, &n, 10)) {
return -1;
}
*wheel = (uint8_t)(n - 1);
return 0;
Serial.println(F("HELP (configuration changes are saved automatically):"));
Serial.println(F(" info | hex [1-4|all] | send [1-4|all] | batt"));
Serial.println(F(" mode normal | mode learn [1-4] | mode single 1-4 | next"));
Serial.println(F(" id 1-4 XXXXXX - set 24-bit ID (hex)"));
Serial.println(F(" ids new - generate 4 unique IDs"));
Serial.println(F(" pressure 1-4|all KPA - e.g. pressure all 260"));
Serial.println(F(" temp 1-4|all C - temperature -40..85 C"));
Serial.println(F(" interval normal|ignition|parking 5-86400"));
Serial.println(F(" rf freq 433.05-434.79 | rf power -30..5 | rf burst 1-8"));
Serial.println(F(" rf gap 20-500 - gap between frames [ms]"));
Serial.println(F(" flags HEX - 32-bit flags (meaning not fully known)"));
Serial.println(F(" factory YES - restore factory | save | stay [s] | sleep"));
}
static void handle_line(char *s)
static void cmd_send(const char *arg)
{
char *cmd = strtok(s, " \t");
uint8_t wheel;
bool ok;
if (arg == NULL) {
ok = g_app->mode() == AppMode::NORMAL ? g_app->send_all() : g_app->send_current();
} else if (parse_wheel(arg, &wheel, true)) {
ok = wheel == 0xFFu ? g_app->send_all() : g_app->send_wheel(wheel);
} else {
Serial.println(F("ERROR: send [1-4|all]"));
return;
}
Serial.println(ok ? F("OK") : F("TX ERROR"));
}
static void cmd_mode(const char *arg1, const char *arg2)
{
if (arg1 == NULL) {
Serial.println(F("ERROR: mode normal|learn|single [1-4]"));
return;
}
uint8_t wheel = WHEEL_FL;
if (arg2 != NULL && !parse_wheel(arg2, &wheel)) {
Serial.println(F("ERROR: wheel 1-4"));
return;
}
if (strcmp(arg1, "normal") == 0) {
g_app->set_mode(AppMode::NORMAL, WHEEL_FL, millis(), false);
} else if (strcmp(arg1, "learn") == 0) {
g_app->set_mode(AppMode::LEARN, wheel, millis());
} else if (strcmp(arg1, "single") == 0 && arg2 != NULL) {
g_app->set_mode(AppMode::SINGLE, wheel, millis());
} else {
Serial.println(F("ERROR: mode normal|learn [1-4]|single 1-4"));
return;
}
Serial.println(F("OK"));
}
static void cmd_id(const char *wheel_text, const char *id_text)
{
uint8_t wheel;
uint32_t id;
if (!parse_wheel(wheel_text, &wheel) || !parse_u32(id_text, 1u, 0xFFFFFEu, &id, 16)
|| !settings_set_id(&g_settings, wheel, id)) {
Serial.println(F("ERROR: id 1-4 000001..FFFFFE; IDs must be unique"));
return;
}
app_save_and_apply();
}
static void cmd_pressure_temp(const char *which, const char *wheel_text,
const char *value_text)
{
uint8_t wheel;
if (!parse_wheel(wheel_text, &wheel, true)) {
Serial.println(F("ERROR: wheel 1-4 or all"));
return;
}
uint8_t first = wheel == 0xFFu ? 0u : wheel;
uint8_t last = wheel == 0xFFu ? WHEEL_COUNT : (uint8_t)(wheel + 1u);
if (strcmp(which, "pressure") == 0) {
float kpa;
if (!parse_float(value_text, 0.0f, 637.5f, &kpa)) {
Serial.println(F("ERROR: pressure 0..637.5 kPa"));
return;
}
uint16_t value = (uint16_t)(kpa * 10.0f + 0.5f);
for (uint8_t i = first; i < last; ++i) {
g_settings.wheels[i].pressure_kpa10 = value;
}
} else {
int32_t value;
if (!parse_i32(value_text, -40, 85, &value)) {
Serial.println(F("ERROR: temperature -40..85 C"));
return;
}
for (uint8_t i = first; i < last; ++i) {
g_settings.wheels[i].temp_c = (int16_t)value;
}
}
app_save_and_apply();
}
static void cmd_interval(const char *which, const char *value_text)
{
uint32_t value;
if (which == NULL || !parse_u32(value_text, SETTINGS_INTERVAL_MIN_S,
SETTINGS_INTERVAL_MAX_S, &value)) {
Serial.println(F("ERROR: interval normal|ignition|parking 5-86400"));
return;
}
if (strcmp(which, "normal") == 0) {
g_settings.normal_interval_s = value;
} else if (strcmp(which, "ignition") == 0) {
g_settings.ignition_interval_s = value;
} else if (strcmp(which, "parking") == 0) {
g_settings.parking_interval_s = value;
} else {
Serial.println(F("ERROR: interval kind"));
return;
}
app_save_and_apply();
}
static void cmd_rf(const char *which, const char *value_text)
{
uint32_t value;
int32_t signed_value;
float frequency;
if (which == NULL) {
Serial.println(F("ERROR: rf freq|power|burst|gap"));
return;
}
if (strcmp(which, "freq") == 0 && parse_float(value_text, 433.05f, 434.79f, &frequency)) {
g_settings.frequency_mhz = frequency;
} else if (strcmp(which, "power") == 0
&& parse_i32(value_text, -30, 5, &signed_value)
&& settings_valid_tx_power((int)signed_value)) {
g_settings.tx_power_dbm = (int8_t)signed_value;
} else if (strcmp(which, "burst") == 0 && parse_u32(value_text, 1u, 8u, &value)) {
g_settings.burst_frames = (uint8_t)value;
} else if (strcmp(which, "gap") == 0 && parse_u32(value_text, 20u, 500u, &value)) {
g_settings.frame_gap_ms = (uint16_t)value;
} else {
Serial.println(F("ERROR: RF parameter out of the allowed range"));
return;
}
app_save_and_apply();
}
static void handle_line(char *text)
{
char *cmd = strtok(text, " \t");
if (cmd == NULL) {
return;
}
char *arg1 = strtok(NULL, " \t");
char *arg2 = strtok(NULL, " \t");
uint32_t u = 0;
uint32_t value;
if (strcmp(cmd, "help") == 0) {
cmd_help();
}
else if (strcmp(cmd, "info") == 0 || strcmp(cmd, "config") == 0) {
} else if (strcmp(cmd, "info") == 0 || strcmp(cmd, "config") == 0) {
app_print_info();
}
else if (strcmp(cmd, "hex") == 0) {
uint8_t w;
if (arg1 == NULL || strcmp(arg1, "all") == 0) {
for (uint8_t i = 0; i < WHEEL_COUNT; i++) {
app_print_frame(i);
}
}
else if (parse_wheel(arg1, &w) == 0) {
app_print_frame(w);
}
else {
Serial.println(F("BLAD: hex [1-4|all]"));
}
}
else if (strcmp(cmd, "send") == 0) {
uint8_t w;
if (arg1 == NULL || strcmp(arg1, "all") == 0) {
app_send_burst_all();
Serial.println(F("OK"));
}
else if (parse_wheel(arg1, &w) == 0) {
app_send_burst_wheel(w);
Serial.println(F("OK"));
}
else {
Serial.println(F("BLAD: send [1-4|all]"));
}
}
else if (strcmp(cmd, "batt") == 0) {
Serial.printf("Vcc = %u mV\n", (unsigned)app_supply_mv());
}
else if (strcmp(cmd, "next") == 0) {
app_next_wheel();
}
else if (strcmp(cmd, "mode") == 0) {
uint8_t w = 0;
} else if (strcmp(cmd, "hex") == 0) {
uint8_t wheel;
if (arg1 == NULL) {
Serial.println(F("BLAD: mode normal|learn|single [n]"));
return;
}
if (strcmp(arg1, "normal") == 0) {
app_set_mode(APP_MODE_NORMAL, 0);
}
else if (strcmp(arg1, "learn") == 0) {
if (arg2 != NULL && parse_wheel(arg2, &w) != 0) {
Serial.println(F("BLAD: numer kola 1-4"));
return;
app_print_frame(g_app->active_wheel());
} else if (parse_wheel(arg1, &wheel, true)) {
if (wheel == 0xFFu) {
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) app_print_frame(i);
} else {
app_print_frame(wheel);
}
app_set_mode(APP_MODE_LEARN, w);
} else {
Serial.println(F("ERROR: hex [1-4|all]"));
}
else if (strcmp(arg1, "single") == 0) {
if (arg2 == NULL || parse_wheel(arg2, &w) != 0 || w == 0xFF) {
Serial.println(F("BLAD: single wymaga numeru kola 1-4"));
return;
}
app_set_mode(APP_MODE_SINGLE, w);
}
else {
Serial.println(F("BLAD: mode normal|learn|single [n]"));
} else if (strcmp(cmd, "send") == 0) {
cmd_send(arg1);
} else if (strcmp(cmd, "batt") == 0) {
Serial.printf("Vcc=%u mV\n", (unsigned)power_read_mv());
} else if (strcmp(cmd, "mode") == 0) {
cmd_mode(arg1, arg2);
} else if (strcmp(cmd, "next") == 0) {
Serial.println(g_app->next_wheel(millis()) ? F("OK") : F("ERROR: LEARN/SINGLE only"));
} else if (strcmp(cmd, "id") == 0) {
cmd_id(arg1, arg2);
} else if (strcmp(cmd, "ids") == 0 && arg1 != NULL && strcmp(arg1, "new") == 0) {
settings_generate_ids(&g_settings, esp_random());
app_save_and_apply();
} else if (strcmp(cmd, "pressure") == 0 || strcmp(cmd, "temp") == 0) {
cmd_pressure_temp(cmd, arg1, arg2);
} else if (strcmp(cmd, "interval") == 0) {
cmd_interval(arg1, arg2);
} else if (strcmp(cmd, "rf") == 0) {
cmd_rf(arg1, arg2);
} else if (strcmp(cmd, "flags") == 0) {
if (!parse_u32(arg1, 0u, 0xFFFFFFFFu, &value, 16)) {
Serial.println(F("ERROR: flags HEX"));
return;
}
Serial.println(F("OK"));
}
else if (strcmp(cmd, "interval") == 0) {
if (!parse_u32(arg1, 0, 86400, &u, 10)) {
Serial.println(F("BLAD: interval <0-86400>"));
return;
}
app_set_interval(u);
Serial.println(F("OK"));
}
else if (strcmp(cmd, "flags") == 0) {
if (!parse_u32(arg1, 0, 0xFFFFFFFFu, &u, 16)) {
Serial.println(F("BLAD: flags <hex>"));
return;
}
app_set_flags(u);
Serial.println(F("OK"));
}
else if (strcmp(cmd, "sleep") == 0) {
g_settings.flags = value;
app_save_and_apply();
} else if (strcmp(cmd, "factory") == 0 && arg1 != NULL && strcmp(arg1, "YES") == 0) {
settings_defaults(&g_settings);
g_app->set_mode(AppMode::NORMAL, WHEEL_FL, millis(), false);
app_save_and_apply();
} else if (strcmp(cmd, "save") == 0) {
app_save_and_apply();
} else if (strcmp(cmd, "sleep") == 0) {
app_request_sleep();
}
else if (strcmp(cmd, "stay") == 0) {
if (arg1 == NULL) {
app_stay_awake(60000u);
}
else if (parse_u32(arg1, 0, 3600, &u, 10)) {
app_stay_awake(u * 1000u);
}
else {
Serial.println(F("BLAD: stay <0-3600>"));
} else if (strcmp(cmd, "stay") == 0) {
value = 60u;
if (arg1 != NULL && !parse_u32(arg1, 1u, 3600u, &value)) {
Serial.println(F("ERROR: stay 1-3600"));
return;
}
app_stay_awake(value * 1000u);
Serial.println(F("OK"));
}
else {
Serial.println(F("Nieznana komenda - 'help'"));
} else {
Serial.println(F("Unknown command; help"));
}
}
@@ -212,24 +260,20 @@ void console_poll(void)
char c = (char)Serial.read();
if (c == '\r' || c == '\n') {
if (line_overflow) {
Serial.println(F("BLAD: linia za dluga"));
}
else if (line_len > 0) {
Serial.println(F("ERROR: line too long"));
} else if (line_len > 0u) {
line[line_len] = '\0';
handle_line(line);
}
line_len = 0;
line_overflow = false;
}
else if (line_overflow) {
/* po przeplenieniu porzucamy cala linie lacznie z ogonem */
}
else if (line_len < sizeof(line) - 1u) {
line[line_len++] = c;
}
else {
line_overflow = true;
line_len = 0;
} else if (!line_overflow) {
if (line_len < sizeof(line) - 1u) {
line[line_len++] = c;
} else {
line_overflow = true;
line_len = 0;
}
}
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
/*
* console.h - debugowa konsola szeregowa (bez String, stalobuforowa)
* console.h - debug serial console (no String, fixed buffer)
*/
#ifndef TPMS_CONSOLE_H
#define TPMS_CONSOLE_H
@@ -9,7 +9,7 @@ extern "C" {
#endif
void console_init(void);
void console_poll(void); // nieblokujaca obsluga linii - wywolywac w petli
void console_poll(void); // non-blocking line handling - call in the loop
#ifdef __cplusplus
}
+215 -459
View File
@@ -1,203 +1,67 @@
/*
* main.cpp - symulator 4 czujnikow TPMS Schrader EG53MA4 (ESP32 + CC1101)
* dla Opla Astry J Sedan 2016 (EU, 433 MHz, TPMS bezposredni).
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ZASTRZEZENIE: projekt wylacznie diagnostyczny/testowy.
* Symulator dostarcza SZTUCZNE dane cisnienia i temperatury i NIE
* zastepuje prawdziwych czujnikow TPMS. Nie uzywac podczas jazdy.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* Tryby pracy:
* NORMAL - rotacja 4 kol, burst 3-5 ramek co TX_INTERVAL_S, deep sleep
* miedzy transmisjami (budzik RTC + budzenie przyciskiem/LF)
* LEARN - nauka czujnikow w aucie: jedno kolo naraz, kolejnosc
* FL -> FR -> RR -> RL, przycisk = kolejne kolo, okno czasowe
* SINGLE - wymuszone nadawanie jednego ID (testy/procedury serwisowe)
*
* Protokol: rtl_433 src/devices/schraeder.c (schrader_EG53MA4),
* Manchester G.E.T. MC, chip 120 us, ASK/OOK 433.92 MHz (opcjonalnie 2-FSK).
*/
/* TPMS diagnostic simulator. Synthetic pressure can mask a tyre fault. */
#include <Arduino.h>
#include <esp_attr.h>
#include <esp_sleep.h>
#include <driver/gpio.h>
#include <soc/soc_caps.h>
#include "config.h"
#include "tpms_frame.h"
#include "radio.h"
#include "power.h"
#include "ui.h"
#include "console.h"
#include "app.h"
#include "config.h"
#include "console.h"
#include "power.h"
#include "radio.h"
#include "settings_store.h"
#include "tpms_frame.h"
#include "ui.h"
/* ------------------------------------------------------------------ */
/* Dane czujnikow (mapowanie ID -> kolo) */
/* ------------------------------------------------------------------ */
#define KPA10(x) ((uint16_t)((x) * 10.0f + 0.5f))
AppState *g_app = nullptr;
static const tpms_sensor_t SENSOR[WHEEL_COUNT] = {
{ SENSOR_FL_ID, KPA10(SENSOR_FL_PRESS_KPA), SENSOR_TEMP_C, "FL" },
{ SENSOR_FR_ID, KPA10(SENSOR_FR_PRESS_KPA), SENSOR_TEMP_C, "FR" },
{ SENSOR_RR_ID, KPA10(SENSOR_RR_PRESS_KPA), SENSOR_TEMP_C, "RR" },
{ SENSOR_RL_ID, KPA10(SENSOR_RL_PRESS_KPA), SENSOR_TEMP_C, "RL" },
};
/* Kolejnosc nauki (kolejnosc w tablicy SENSOR = FL, FR, RR, RL). */
static const uint8_t LEARN_SEQ[WHEEL_COUNT] = {
LEARN_ORDER_0, LEARN_ORDER_1, LEARN_ORDER_2, LEARN_ORDER_3,
};
/* ------------------------------------------------------------------ */
/* Stan w RTC (przetrwuje deep sleep) */
/* ------------------------------------------------------------------ */
/* Magic zwiazany z wersja konfiguracji: zmiana CONFIG_VERSION (np. po
* zmianie formatu stanu w RTC) zeruje caly stan po wybudzeniu. */
#define RTC_MAGIC (0x54504D53u ^ (uint32_t)CONFIG_VERSION) // 'TPMS' ^ version
RTC_DATA_ATTR static uint32_t rtc_magic;
RTC_DATA_ATTR static uint8_t rtc_mode = APP_MODE_NORMAL;
RTC_DATA_ATTR static uint8_t rtc_seq_idx = 0; // pozycja w LEARN_SEQ (LEARN)
RTC_DATA_ATTR static uint8_t rtc_single_wheel = 0; // kolo w SINGLE (indeks SENSOR)
RTC_DATA_ATTR static uint8_t rtc_rot_idx = 0; // rotacja w NORMAL
RTC_DATA_ATTR static uint32_t rtc_wake_count = 0;
RTC_DATA_ATTR static uint32_t rtc_interval_s = 0; // 0 = auto wg ACC
RTC_DATA_ATTR static uint32_t rtc_flags = TPMS_FLAGS;
RTC_DATA_ATTR static uint64_t rtc_last_acc_ms = 0;
/* Stan sesji (wazny tylko w biezaczym wybudzeniu) */
static uint32_t stay_awake_until = 0;
static uint32_t next_tx_ms = 0;
static uint32_t learn_window_start = 0;
static uint32_t learn_session_start = 0;
static uint32_t single_start = 0;
static bool request_sleep = false;
static bool low_batt = false;
static uint32_t supply_mv = 0;
static const char *const WHEEL_NAMES[WHEEL_COUNT] = {"FL", "FR", "RR", "RL"};
static uint32_t stay_awake_until;
static bool request_sleep;
static uint32_t supply_mv;
/* Micro-naps: time slept since the last TX cycle and the length of the last
* sleep slice survive deep sleep in RTC memory (cleared by power-on). */
RTC_DATA_ATTR static uint32_t slept_ms;
RTC_DATA_ATTR static uint32_t last_slice_ms;
#if PIN_LF_TRIGGER >= 0
static bool lf_prev = false; // poprzedni stan wejscia LF (zbocze)
static bool lf_previous;
#endif
/* ------------------------------------------------------------------ */
/* Pomocnicze */
/* ------------------------------------------------------------------ */
static uint32_t compute_interval(void);
/* Aktywne kolo: SINGLE trzyma bezposredni indeks SENSOR, LEARN - pozycje
* w sekwencji nauki LEARN_SEQ (moga sie roznic po zmianie LEARN_ORDER_*). */
static uint8_t active_wheel(void)
static bool ignition_on(void)
{
return (rtc_mode == APP_MODE_SINGLE)
? (uint8_t)(rtc_single_wheel % WHEEL_COUNT)
: LEARN_SEQ[rtc_seq_idx % WHEEL_COUNT];
#if PIN_ACC >= 0
return digitalRead(PIN_ACC) == HIGH;
#else
return false;
#endif
}
/* Pozycja kola w sekwencji nauki (do trybu LEARN). */
static uint8_t seq_pos_of(uint8_t wheel)
{
for (uint8_t i = 0; i < WHEEL_COUNT; i++) {
if (LEARN_SEQ[i] == wheel) {
return i;
class HardwareRadio final : public RadioSink {
public:
bool send(uint8_t wheel) override
{
if (wheel >= WHEEL_COUNT) {
return false;
}
const sensor_settings_t &sensor = g_settings.wheels[wheel];
uint8_t frame[TPMS_TX_BYTES];
if (!tpms_build_frame(frame, sensor.id, sensor.pressure_kpa10,
(int8_t)sensor.temp_c, g_settings.flags)) {
return false;
}
bool ok = radio_send_burst(frame, TPMS_TX_BYTES, g_settings.burst_frames,
g_settings.frame_gap_ms);
Serial.printf("TX %s id=%06X %u.%u kPa %d C flags=%08X%s\n",
WHEEL_NAMES[wheel], (unsigned)sensor.id,
sensor.pressure_kpa10 / 10u, sensor.pressure_kpa10 % 10u,
(int)sensor.temp_c, (unsigned)g_settings.flags,
ok ? "" : " TX-ERR");
return ok;
}
return 0;
}
};
static void refresh_power(void)
{
supply_mv = power_read_mv();
low_batt = power_low_battery(supply_mv);
}
static void build_frame_for(uint8_t wheel, uint8_t out[TPMS_TX_BYTES])
{
const tpms_sensor_t *s = &SENSOR[wheel % WHEEL_COUNT];
tpms_build_frame(out, s->id, s->press_kpa10, s->temp_c, rtc_flags, low_batt);
}
void app_send_burst_wheel(uint8_t wheel)
{
uint8_t frame[TPMS_TX_BYTES];
build_frame_for(wheel, frame);
bool ok = radio_send_burst(frame, TPMS_TX_BYTES, TX_BURST_FRAMES);
Serial.printf("TX %s id=%06X %.1f kPa %d C flags=%08X%s%s\n",
SENSOR[wheel % WHEEL_COUNT].name,
(unsigned)SENSOR[wheel % WHEEL_COUNT].id,
SENSOR[wheel % WHEEL_COUNT].press_kpa10 / 10.0f,
(int)SENSOR[wheel % WHEEL_COUNT].temp_c,
(unsigned)rtc_flags, low_batt ? " LOWBATT" : "",
ok ? "" : " TX-ERR");
}
void app_send_burst_all(void)
{
for (uint8_t i = 0; i < WHEEL_COUNT; i++) {
app_send_burst_wheel((uint8_t)((rtc_rot_idx + i) % WHEEL_COUNT));
}
rtc_rot_idx = (uint8_t)((rtc_rot_idx + 1) % WHEEL_COUNT);
}
void app_print_frame(uint8_t wheel)
{
uint8_t frame[TPMS_TX_BYTES];
uint8_t payload[TPMS_PAYLOAD_LEN];
const tpms_sensor_t *s = &SENSOR[wheel % WHEEL_COUNT];
build_frame_for(wheel, frame);
tpms_build_payload(payload, s->id, s->press_kpa10, s->temp_c, rtc_flags, low_batt);
Serial.printf("%s frame:", s->name);
for (uint8_t i = 0; i < TPMS_TX_BYTES; i++) {
Serial.printf(" %02X", frame[i]);
}
Serial.printf("\n%s payload:", s->name);
for (uint8_t i = 0; i < TPMS_PAYLOAD_LEN; i++) {
Serial.printf(" %02X", payload[i]);
}
Serial.printf(" crc=%02X id=%06X press=%.1f kPa temp=%d F\n",
payload[9], (unsigned)s->id,
payload[7] * 2.5f, (int)payload[8]);
}
void app_print_info(void)
{
Serial.printf("FW %s config v%d mode=%s wheel=%s\n",
FW_VERSION, CONFIG_VERSION,
rtc_mode == APP_MODE_NORMAL ? "NORMAL" :
rtc_mode == APP_MODE_LEARN ? "LEARN" : "SINGLE",
SENSOR[active_wheel()].name);
for (uint8_t i = 0; i < WHEEL_COUNT; i++) {
Serial.printf(" %s id=%06X press=%.1f kPa temp=%d C\n",
SENSOR[i].name, (unsigned)SENSOR[i].id,
SENSOR[i].press_kpa10 / 10.0f, (int)SENSOR[i].temp_c);
}
Serial.printf("flags=%08X mod=%s chip=%dus burst=%d interval=%us wake=%lu\n",
(unsigned)rtc_flags,
TPMS_MODULATION == MODE_FSK ? "FSK" : "OOK",
TPMS_CHIP_US, TX_BURST_FRAMES,
(unsigned)compute_interval(),
(unsigned long)rtc_wake_count);
Serial.printf("Vcc=%u mV%s\n", (unsigned)supply_mv, low_batt ? " LOWBATT" : "");
}
uint32_t app_supply_mv(void)
{
refresh_power();
return supply_mv;
}
void app_set_interval(uint32_t seconds)
{
rtc_interval_s = seconds;
}
void app_set_flags(uint32_t flags)
{
rtc_flags = flags;
}
void app_request_sleep(void)
{
request_sleep = true;
}
static HardwareRadio hardware_radio;
static AppState app_state(&g_settings, &hardware_radio);
void app_stay_awake(uint32_t ms)
{
@@ -207,345 +71,237 @@ void app_stay_awake(uint32_t ms)
}
}
uint8_t app_mode(void)
void app_request_sleep(void)
{
return rtc_mode;
request_sleep = true;
}
uint8_t app_wheel(void)
bool app_save_and_apply(void)
{
return active_wheel();
}
void app_next_wheel(void)
{
if (rtc_mode == APP_MODE_SINGLE) {
rtc_single_wheel = (uint8_t)((rtc_single_wheel + 1) % WHEEL_COUNT);
if (!settings_store_save()) {
Serial.println(F("ERROR: NVS not saved (validation or write)"));
return false;
}
else {
rtc_seq_idx = (uint8_t)((rtc_seq_idx + 1) % WHEEL_COUNT);
if (!radio_init(&g_settings)) {
Serial.println(F("WARNING: saved, but the CC1101 does not respond"));
}
ui_blink_count((uint8_t)(active_wheel() + 1));
Serial.printf("Kolo: %s\n", SENSOR[active_wheel()].name);
learn_window_start = millis();
Serial.println(F("OK: saved in NVS"));
return true;
}
void app_set_mode(uint8_t mode, uint8_t wheel)
void app_print_frame(uint8_t wheel)
{
rtc_mode = mode;
switch (mode) {
case APP_MODE_LEARN:
rtc_seq_idx = seq_pos_of((uint8_t)(wheel % WHEEL_COUNT));
learn_window_start = millis();
learn_session_start = millis();
next_tx_ms = 0;
ui_set_pattern(UI_PAT_LEARN);
ui_blink_count((uint8_t)(active_wheel() + 1));
Serial.printf("LEARN start, kolo %s\n", SENSOR[active_wheel()].name);
app_stay_awake(LEARN_TOTAL_TIMEOUT_MS);
break;
case APP_MODE_SINGLE:
rtc_single_wheel = (uint8_t)(wheel % WHEEL_COUNT);
single_start = millis();
next_tx_ms = 0;
ui_set_pattern(UI_PAT_SINGLE);
ui_blink_count((uint8_t)(active_wheel() + 1));
Serial.printf("SINGLE start, kolo %s\n", SENSOR[active_wheel()].name);
app_stay_awake(SINGLE_TIMEOUT_MS ? SINGLE_TIMEOUT_MS : 3600000u);
break;
default:
rtc_mode = APP_MODE_NORMAL;
ui_set_pattern(UI_PAT_NORMAL);
Serial.println(F("NORMAL"));
next_tx_ms = 0;
app_stay_awake(BOOT_STAY_AWAKE_MS);
break;
if (wheel >= WHEEL_COUNT) {
return;
}
const sensor_settings_t &s = g_settings.wheels[wheel];
uint8_t frame[TPMS_TX_BYTES];
uint8_t payload[TPMS_PAYLOAD_LEN];
if (!tpms_build_frame(frame, s.id, s.pressure_kpa10, (int8_t)s.temp_c,
g_settings.flags)
|| !tpms_build_payload(payload, s.id, s.pressure_kpa10,
(int8_t)s.temp_c, g_settings.flags)) {
Serial.println(F("ERROR: invalid frame configuration"));
return;
}
Serial.printf("%s payload:", WHEEL_NAMES[wheel]);
for (uint8_t i = 0; i < TPMS_PAYLOAD_LEN; ++i) {
Serial.printf(" %02X", payload[i]);
}
Serial.printf("\n%s frame:", WHEEL_NAMES[wheel]);
for (uint8_t i = 0; i < TPMS_TX_BYTES; ++i) {
Serial.printf(" %02X", frame[i]);
}
Serial.println();
}
void app_print_info(void)
{
Serial.printf("FW %s NVS v%u mode=%u wheel=%s errors=%lu\n", FW_VERSION,
(unsigned)SETTINGS_VERSION, (unsigned)g_app->mode(),
WHEEL_NAMES[g_app->active_wheel()],
(unsigned long)g_app->last_error_count());
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
const sensor_settings_t &s = g_settings.wheels[i];
Serial.printf(" %s id=%06X pressure=%u.%u kPa temp=%d C\n",
WHEEL_NAMES[i], (unsigned)s.id, s.pressure_kpa10 / 10u,
s.pressure_kpa10 % 10u, (int)s.temp_c);
}
Serial.printf("flags=%08X OOK chip=%u us burst=%u gap=%u ms\n",
(unsigned)g_settings.flags, TPMS_CHIP_US, g_settings.burst_frames,
g_settings.frame_gap_ms);
Serial.printf("RF=%.2f MHz power=%d dBm intervals=%lu/%lu/%lu s\n",
g_settings.frequency_mhz, g_settings.tx_power_dbm,
(unsigned long)g_settings.normal_interval_s,
(unsigned long)g_settings.ignition_interval_s,
(unsigned long)g_settings.parking_interval_s);
Serial.printf("Vcc=%u mV (does not change TPMS flags)\n", (unsigned)supply_mv);
}
static void sync_ui(void)
{
static AppMode previous_mode = AppMode::NORMAL;
static uint8_t previous_wheel = UINT8_MAX;
AppMode mode = g_app->mode();
uint8_t wheel = g_app->active_wheel();
if (mode != previous_mode || wheel != previous_wheel) {
ui_set_pattern(mode == AppMode::LEARN ? UI_PAT_LEARN
: mode == AppMode::SINGLE ? UI_PAT_SINGLE : UI_PAT_NORMAL);
if (mode != AppMode::NORMAL) {
ui_blink_count((uint8_t)(wheel + 1u));
}
previous_mode = mode;
previous_wheel = wheel;
}
}
/* ------------------------------------------------------------------ */
/* Cykl nadawczy w trybie NORMAL */
/* ------------------------------------------------------------------ */
static uint32_t compute_interval(void)
{
if (rtc_interval_s != 0) {
return rtc_interval_s;
}
#if PIN_ACC < 0
/* Bez wejscia ACC stale pracujemy z interwalem podstawowym - logika
* "5 min po zaniku ACC" nie ma wtedy zastosowania. */
return (uint32_t)TX_INTERVAL_S;
#else
uint64_t now_ms = power_elapsed_ms();
if (digitalRead(PIN_ACC) == HIGH) {
rtc_last_acc_ms = now_ms;
return (uint32_t)TX_INTERVAL_IGNITION_S;
}
if (now_ms - rtc_last_acc_ms > (uint64_t)ACC_GRACE_MS) {
return PARKING_SHUTDOWN ? 0u : (uint32_t)TX_INTERVAL_PARKING_S;
}
return (uint32_t)TX_INTERVAL_S;
#endif
}
static void tx_cycle(void)
{
refresh_power();
app_send_burst_all();
}
/* Czy ktorekolwiek zrodlo budzenia poziomowego jest aktywne? */
static bool wake_sources_active(void)
{
if (ui_button_down() || digitalRead(PIN_BUTTON) == BTN_ACTIVE_LEVEL) {
return true;
}
#if PIN_LF_TRIGGER >= 0
if (digitalRead(PIN_LF_TRIGGER) == HIGH) {
if (digitalRead(PIN_LF_TRIGGER) == LF_ACTIVE_LEVEL) {
return true;
}
#endif
return false;
}
static void go_sleep(uint32_t seconds)
static void go_sleep(void)
{
/* Nie spij, dopoki przycisk jest wcisniety lub LF aktywne - EXT0/EXT1
* dzialaja poziomowo, wiec sen przy aktywnym zrodle = natychmiastowa
* petla wybudzen. Dajemy krotki margines i wracamy do petli. */
if (wake_sources_active()) {
app_stay_awake(500);
if (g_app->mode() != AppMode::NORMAL) {
return;
}
if (wake_sources_active()) {
app_stay_awake(500u);
return;
}
/* Micro-nap: the rest of the period after boot time + window, so that
* LED blinks land on NAP_PERIOD_MS regardless of awake duration. */
uint32_t awake_ms = millis();
uint32_t slice_ms = NAP_PERIOD_MS;
if (awake_ms + NAP_MIN_SLEEP_MS < NAP_PERIOD_MS) {
slice_ms = NAP_PERIOD_MS - awake_ms;
}
ui_set_pattern(UI_PAT_OFF);
digitalWrite(PIN_LED, LOW);
Serial.printf("sleep %us\n", (unsigned)seconds);
Serial.printf("sleep %lu ms\n", (unsigned long)slice_ms);
Serial.flush();
power_deep_sleep(seconds); // nie wraca
last_slice_ms = slice_ms;
power_deep_sleep(slice_ms);
}
/* ------------------------------------------------------------------ */
void setup(void)
{
Serial.begin(SERIAL_BAUD);
ui_init();
power_init();
settings_store_begin();
console_init();
#if PIN_LF_TRIGGER >= 0
pinMode(PIN_LF_TRIGGER, INPUT_PULLDOWN);
pinMode(PIN_LF_TRIGGER, INPUT_PULLUP);
lf_previous = digitalRead(PIN_LF_TRIGGER) == LF_ACTIVE_LEVEL;
#endif
#if PIN_ACC >= 0
/* INPUT (bez podciagania): dolna galazka dzielnika wymusza stan niski,
* a wewnetrzny pulldown (~45 k) obciazylby dzielnik i zbil prog VIH. */
pinMode(PIN_ACC, INPUT);
#endif
if (rtc_magic != RTC_MAGIC) {
rtc_magic = RTC_MAGIC;
rtc_mode = APP_MODE_NORMAL;
rtc_seq_idx = 0;
rtc_single_wheel = 0;
rtc_rot_idx = 0;
rtc_wake_count = 0;
rtc_interval_s = 0;
rtc_flags = TPMS_FLAGS;
rtc_last_acc_ms = 0;
}
rtc_wake_count++;
bool radio_ok = radio_init();
Serial.println();
Serial.printf("TPMS simulator FW %s (config v%d) - SYMULATOR, dane sztuczne!\n",
FW_VERSION, CONFIG_VERSION);
if (!radio_ok) {
Serial.println(F("BLAD: brak modulu CC1101 (sprawdz SPI)"));
}
refresh_power();
if (low_batt) {
Serial.printf("OSTRZEZENIE: niskie napiecie zasilania %u mV!\n",
(unsigned)supply_mv);
}
g_app = &app_state;
esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
uint32_t iv = compute_interval();
switch (cause) {
case ESP_SLEEP_WAKEUP_TIMER:
/* zwykly cykl - nadaj i spij bez czuwania */
next_tx_ms = 0;
stay_awake_until = 0;
break;
case ESP_SLEEP_WAKEUP_EXT0:
/* przycisk - obsluga gestu w petli, krotkie okno konsoli */
Serial.println(F("wake: button"));
next_tx_ms = UINT32_MAX; // nie nadawaj automatycznie
stay_awake_until = millis() + BOOT_STAY_AWAKE_MS;
break;
case ESP_SLEEP_WAKEUP_EXT1: {
uint64_t st = esp_sleep_get_ext1_wakeup_status();
Serial.printf("wake: ext1 mask=%08X%08X\n",
(unsigned)(st >> 32), (unsigned)(st & 0xFFFFFFFFu));
refresh_power();
app_send_burst_wheel(active_wheel()); // aktywacja LF = natychmiast
next_tx_ms = UINT32_MAX;
stay_awake_until = millis() + BOOT_STAY_AWAKE_MS;
break;
#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
/* Chips with GPIO wakeup in deep sleep (e.g. ESP32-C3). */
bool pin_wake = cause == ESP_SLEEP_WAKEUP_GPIO;
#else
/* ESP32-S2: waking from RTC pins raises EXT1. */
bool pin_wake = cause == ESP_SLEEP_WAKEUP_EXT1;
#endif
bool timer_wake = cause == ESP_SLEEP_WAKEUP_TIMER;
if (timer_wake) {
slept_ms += last_slice_ms;
}
/* TX on the interval: power-on, wake after sleeping the whole cycle, or
* an exhausted sleep counter. A button wake does not transmit (as before). */
uint32_t interval_ms = g_app->interval_s(ignition_on()) * 1000u;
bool transmit = !pin_wake && (!timer_wake || slept_ms >= interval_ms);
bool quick_nap = timer_wake && !transmit;
if (transmit) {
slept_ms = 0;
}
default:
Serial.println(F("wake: power-on"));
next_tx_ms = 0;
stay_awake_until = millis() + BOOT_STAY_AWAKE_MS;
break;
}
if (rtc_mode == APP_MODE_LEARN) {
ui_set_pattern(UI_PAT_LEARN);
learn_window_start = millis();
learn_session_start = millis();
next_tx_ms = 0;
stay_awake_until = millis() + LEARN_TOTAL_TIMEOUT_MS;
}
else if (rtc_mode == APP_MODE_SINGLE) {
ui_set_pattern(UI_PAT_SINGLE);
single_start = millis();
next_tx_ms = 0;
stay_awake_until = millis() +
(SINGLE_TIMEOUT_MS ? SINGLE_TIMEOUT_MS : 3600000u);
}
else {
ui_set_pattern(low_batt ? UI_PAT_LOWBAT : UI_PAT_NORMAL);
}
/* Po wybudzeniu przyciskiem/LF obsluzylismy juz akcje - nie powtarzaj
* cyklu natychmiast, tylko odloz go o pelny okres. */
if (cause == ESP_SLEEP_WAKEUP_EXT0 || cause == ESP_SLEEP_WAKEUP_EXT1) {
if (rtc_mode != APP_MODE_NORMAL) {
next_tx_ms = millis() + LEARN_TX_PERIOD_MS;
bool radio_ready = radio_init(&g_settings);
if (!quick_nap) {
supply_mv = power_read_mv();
Serial.printf("\nTPMS DIAG FW %s - SYNTHETIC DATA, NOT FOR ROAD USE\n", FW_VERSION);
Serial.printf("NVS: %s; access=%s\n",
settings_load_result_text(settings_store_last_load()),
settings_store_available() ? "yes" : "no");
if (!radio_ready) {
Serial.println(F("ERROR: no CC1101; check 3V3/SPI"));
}
if (power_low_battery(supply_mv)) {
Serial.println(F("WARNING: emulator supply low"));
}
}
#if PIN_LF_TRIGGER >= 0
/* LF ciagle aktywne = brak nowego zbocza = brak kolejnego bursta */
lf_prev = (digitalRead(PIN_LF_TRIGGER) == HIGH);
#endif
Serial.printf("Vcc=%u mV tryb=%d interwal=%us\n", (unsigned)supply_mv,
(int)rtc_mode, (unsigned)iv);
app_print_info();
Serial.println(F("gotowy ('help' - komendy)"));
g_app->begin(millis(), transmit);
#if PIN_LF_TRIGGER >= 0
uint64_t wake_mask = 0;
if (pin_wake) {
#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
wake_mask = esp_sleep_get_gpio_wakeup_status();
#else
wake_mask = esp_sleep_get_ext1_wakeup_status();
#endif
}
if ((wake_mask & (1ULL << PIN_LF_TRIGGER)) != 0) {
g_app->send_current();
}
#endif
/* Windows: power-on/button/LF = 10 s console; timer wake = straight to
* sleep after TX, the micro-nap only for a visible LED blink. */
stay_awake_until = millis() + (timer_wake
? (transmit ? 0u : NAP_AWAKE_MS) : BOOT_STAY_AWAKE_MS);
sync_ui();
if (!quick_nap) {
app_print_info();
Serial.println(F("ready; help = commands; stay 60 = 60 s console"));
}
}
void loop(void)
{
uint32_t now = millis();
ui_update();
/* gesty przycisku */
ui_event_t ev = ui_poll();
if (ev == UI_EV_SHORT) {
if (rtc_mode == APP_MODE_NORMAL) {
refresh_power();
app_send_burst_all(); // "aktywuj kolo" - nadaj teraz
}
else {
app_next_wheel(); // learn/single: kolejne kolo
}
switch (ev) {
case UI_EV_SHORT: g_app->short_press(now); break;
case UI_EV_LONG: g_app->long_press(now); break;
case UI_EV_VERYLONG: g_app->very_long_press(now); break;
default: break;
}
else if (ev == UI_EV_LONG) {
if (rtc_mode == APP_MODE_LEARN) {
app_set_mode(APP_MODE_NORMAL, 0);
}
else {
app_set_mode(APP_MODE_LEARN, 0);
}
if (ev != UI_EV_NONE) {
/* Every gesture = a 10 s console window (POWER.md), also when leaving
* LEARN/SINGLE - the device does not fall asleep right after a button. */
app_stay_awake(BOOT_STAY_AWAKE_MS);
}
else if (ev == UI_EV_VERYLONG) {
if (rtc_mode == APP_MODE_SINGLE) {
app_set_mode(APP_MODE_NORMAL, 0);
}
else {
app_set_mode(APP_MODE_SINGLE, active_wheel());
}
}
console_poll();
#if PIN_LF_TRIGGER >= 0
/* aktywacja LF tez dziala "na zywo" (nie tylko przez budzenie) */
{
bool lf = (digitalRead(PIN_LF_TRIGGER) == HIGH);
if (lf && !lf_prev) {
refresh_power();
app_send_burst_wheel(active_wheel());
/* po recznej transmisji odloz cykl - bez tego LF moglby
* wywolac 2-3 bursty zamiast jednego */
if (rtc_mode != APP_MODE_NORMAL) {
next_tx_ms = millis() + LEARN_TX_PERIOD_MS;
}
}
lf_prev = lf;
bool lf = digitalRead(PIN_LF_TRIGGER) == LF_ACTIVE_LEVEL;
if (lf && !lf_previous) {
g_app->send_current();
app_stay_awake(BOOT_STAY_AWAKE_MS);
}
lf_previous = lf;
#endif
g_app->tick(millis(), ignition_on());
sync_ui();
if (request_sleep) {
request_sleep = false;
go_sleep(compute_interval());
}
switch (rtc_mode) {
case APP_MODE_LEARN:
if ((int32_t)(now - next_tx_ms) >= 0) {
refresh_power();
app_send_burst_wheel(active_wheel());
next_tx_ms = now + LEARN_TX_PERIOD_MS;
}
if (now - learn_window_start >= LEARN_WINDOW_MS) {
if (LEARN_WINDOW_EXPIRE_TO_NORMAL) {
Serial.println(F("okno learn minelo - powrot do NORMAL"));
app_set_mode(APP_MODE_NORMAL, 0);
}
else if (rtc_seq_idx + 1u >= WHEEL_COUNT) {
Serial.println(F("learn ukonczony - powrot do NORMAL"));
app_set_mode(APP_MODE_NORMAL, 0);
}
else {
app_next_wheel();
}
}
if (now - learn_session_start >= LEARN_TOTAL_TIMEOUT_MS) {
Serial.println(F("timeout learn - powrot do NORMAL"));
app_set_mode(APP_MODE_NORMAL, 0);
}
break;
case APP_MODE_SINGLE:
if ((int32_t)(now - next_tx_ms) >= 0) {
refresh_power();
app_send_burst_wheel(active_wheel());
next_tx_ms = now + LEARN_TX_PERIOD_MS;
}
if (SINGLE_TIMEOUT_MS && now - single_start >= SINGLE_TIMEOUT_MS) {
Serial.println(F("timeout single - powrot do NORMAL"));
app_set_mode(APP_MODE_NORMAL, 0);
}
break;
default: /* NORMAL */
if (next_tx_ms != UINT32_MAX && (int32_t)(now - next_tx_ms) >= 0) {
uint32_t iv = compute_interval();
tx_cycle();
next_tx_ms = now + (iv ? iv : 3600u) * 1000u;
}
if ((int32_t)(now - stay_awake_until) >= 0) {
go_sleep(compute_interval());
}
break;
go_sleep();
} else if (g_app->mode() == AppMode::NORMAL
&& (int32_t)(millis() - stay_awake_until) >= 0) {
go_sleep();
}
}
+53
View File
@@ -0,0 +1,53 @@
#include <errno.h>
#include <stdlib.h>
#include "parse.h"
bool parse_u32(const char *text, uint32_t lo, uint32_t hi, uint32_t *out,
int base)
{
if (text == NULL || *text == '\0' || *text == '-') {
return false;
}
errno = 0;
char *end = NULL;
unsigned long value = strtoul(text, &end, base);
if (errno != 0 || end == text || *end != '\0'
|| value < lo || value > hi) {
return false;
}
*out = (uint32_t)value;
return true;
}
bool parse_i32(const char *text, int32_t lo, int32_t hi, int32_t *out)
{
if (text == NULL || *text == '\0') {
return false;
}
errno = 0;
char *end = NULL;
long value = strtol(text, &end, 10);
if (errno != 0 || end == text || *end != '\0' || value < lo || value > hi) {
return false;
}
*out = value;
return true;
}
bool parse_float(const char *text, float lo, float hi, float *out)
{
if (text == NULL || *text == '\0') {
return false;
}
errno = 0;
char *end = NULL;
float value = strtof(text, &end);
/* Inverted comparison also rejects NaN (both sides false). */
if (errno != 0 || end == text || *end != '\0'
|| !(value >= lo && value <= hi)) {
return false;
}
*out = value;
return true;
}
+22
View File
@@ -0,0 +1,22 @@
/* Console argument parsing; portable module (native tests). */
#ifndef TPMS_PARSE_H
#define TPMS_PARSE_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
bool parse_u32(const char *text, uint32_t lo, uint32_t hi, uint32_t *out,
int base = 10);
bool parse_i32(const char *text, int32_t lo, int32_t hi, int32_t *out);
/* Rejects NaN and infinity; closed range [lo, hi]. */
bool parse_float(const char *text, float lo, float hi, float *out);
#ifdef __cplusplus
}
#endif
#endif
+64 -58
View File
@@ -1,19 +1,12 @@
/*
* power.cpp - zasilanie, pomiar napiecia, deep sleep
*
* Zastrzezenie: urzadzenie diagnostyczne/testowe - symulator TPMS
* dostarcza sztuczne dane cisnienia i nie zastepuje prawdziwych czujnikow.
*
* Budzet pradu (patrz README):
* - ESP32 deep sleep: ~10 uA (WiFi/BT nie sa wcale inicjalizowane)
* - CC1101 w SLEEP (SPWD): < 1 uA
* - gpio_hold trzyma linie CC1101 w stanach niskich/wysokiej CS
*/
/* Power and deep sleep. Supply state does NOT change TPMS protocol fields. */
#include <Arduino.h>
#include <esp_sleep.h>
#include <driver/gpio.h>
#include <driver/rtc_io.h>
#include <soc/soc_caps.h>
#if SOC_BT_SUPPORTED
#include <esp32-hal-bt.h>
#include <sys/time.h>
#endif
#include "config.h"
#include "power.h"
@@ -21,28 +14,33 @@
void power_init(void)
{
/* Zwolnij hold z poprzedniego snu - po deep sleep piny sa zatrzymane. */
gpio_deep_sleep_hold_dis();
gpio_hold_dis((gpio_num_t)PIN_CC1101_CS);
gpio_hold_dis((gpio_num_t)PIN_CC1101_SCK);
gpio_hold_dis((gpio_num_t)PIN_CC1101_MOSI);
/* WiFi nie jest wcale uruchamiany (brak init), BT wylaczamy defensywnie. */
#if SOC_BT_SUPPORTED
/* ESP32-S2 has no Bluetooth radio; btStop only exists on chips with BT. */
btStop();
#endif
#if PIN_VBAT_ADC >= 0
analogSetPinAttenuation(PIN_VBAT_ADC, ADC_11db);
#endif
}
uint32_t power_read_mv(void)
{
#if PIN_VBAT_ADC < 0
return 0u;
#else
uint64_t sum = 0;
for (int i = 0; i < VBAT_SAMPLES; i++) {
for (uint8_t i = 0; i < VBAT_SAMPLES; ++i) {
sum += analogReadMilliVolts(PIN_VBAT_ADC);
}
uint32_t pin_mv = (uint32_t)(sum / VBAT_SAMPLES);
float v = (float)pin_mv * ((VBAT_DIVIDER_R1 + VBAT_DIVIDER_R2) / VBAT_DIVIDER_R2)
* VBAT_CAL;
return (uint32_t)(v + 0.5f);
float value = (float)pin_mv * ((VBAT_DIVIDER_R1 + VBAT_DIVIDER_R2) / VBAT_DIVIDER_R2)
* VBAT_CAL;
return (uint32_t)(value + 0.5f);
#endif
}
bool power_low_battery(uint32_t mv)
@@ -50,57 +48,65 @@ bool power_low_battery(uint32_t mv)
return mv > 500u && mv < (uint32_t)LOWBATT_THRESHOLD_MV;
}
void power_deep_sleep(uint32_t seconds)
void power_deep_sleep(uint32_t ms)
{
/* CC1101 w sleep + bezpieczne stany linii (CS=1 utrzymuje SPWD). */
radio_sleep();
/* Zatrzymaj piny w tych stanach na czas snu. */
gpio_hold_en((gpio_num_t)PIN_CC1101_CS);
gpio_hold_en((gpio_num_t)PIN_CC1101_SCK);
gpio_hold_en((gpio_num_t)PIN_CC1101_MOSI);
gpio_deep_sleep_hold_en();
/* Budzik RTC. */
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL);
if (seconds > 0) {
if (esp_sleep_enable_timer_wakeup((uint64_t)seconds * 1000000ULL) != ESP_OK) {
Serial.println(F("power: blad konfiguracji budzika RTC"));
}
/* PARKING_SHUTDOWN does not exist: every sleep has an RTC alarm and the
* device cannot be stopped until a manual wake. The lower bound also
* guarantees an alarm for micro-naps. */
if (ms < NAP_MIN_SLEEP_MS) {
ms = NAP_MIN_SLEEP_MS;
}
esp_sleep_enable_timer_wakeup((uint64_t)ms * 1000ULL);
/* Przycisk jako zrodlo EXT0 (poziom konfigurowalny). */
#if PIN_BUTTON >= 0 || PIN_LF_TRIGGER >= 0
/* Waking from RTC pins (on ESP32-S2: GPIO0-21). Both inputs are active
* low, so they can share one mode. ESP32-S2 does not support GPIO wakeup
* in deep sleep - it uses EXT1 ANY_LOW. */
uint64_t wake_mask = 0;
#if PIN_BUTTON >= 0
if (esp_sleep_enable_ext0_wakeup((gpio_num_t)PIN_BUTTON, BTN_ACTIVE_LEVEL)
!= ESP_OK) {
Serial.println(F("power: blad konfiguracji EXT0 (pin nie RTC?)"));
}
wake_mask |= 1ULL << PIN_BUTTON;
#endif
/* Opcjonalne wejscie LF 125 kHz (impuls wysoki) jako EXT1.
* Uwaga: poziom musi byc niski w spoczynku, inaczej ESP32 obudzi sie
* natychmiast po wejsciu w sen. */
uint64_t ext1_mask = 0;
#if PIN_LF_TRIGGER >= 0
ext1_mask |= (1ULL << PIN_LF_TRIGGER);
wake_mask |= 1ULL << PIN_LF_TRIGGER;
#endif
#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
/* Digital pull-up/pull-down (pinMode) does not work in deep sleep while
* the RTC_PERIPH domain is off. Without RTC pulls the wake pins float and
* EXT1 can wake randomly; we configure them here and keep them with the
* HOLD mechanism (per ESP-IDF sleep_modes for EXT1). */
#if PIN_BUTTON >= 0
rtc_gpio_init((gpio_num_t)PIN_BUTTON);
#if BTN_ACTIVE_LEVEL == 0
rtc_gpio_pulldown_dis((gpio_num_t)PIN_BUTTON);
rtc_gpio_pullup_en((gpio_num_t)PIN_BUTTON);
#else
rtc_gpio_pullup_dis((gpio_num_t)PIN_BUTTON);
rtc_gpio_pulldown_en((gpio_num_t)PIN_BUTTON);
#endif
#endif
#if PIN_LF_TRIGGER >= 0
rtc_gpio_init((gpio_num_t)PIN_LF_TRIGGER);
#if LF_ACTIVE_LEVEL == 0
rtc_gpio_pulldown_dis((gpio_num_t)PIN_LF_TRIGGER);
rtc_gpio_pullup_en((gpio_num_t)PIN_LF_TRIGGER);
#else
rtc_gpio_pullup_dis((gpio_num_t)PIN_LF_TRIGGER);
rtc_gpio_pulldown_en((gpio_num_t)PIN_LF_TRIGGER);
#endif
#endif
#endif /* SOC_RTCIO_INPUT_OUTPUT_SUPPORTED */
#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
esp_deep_sleep_enable_gpio_wakeup(wake_mask, ESP_GPIO_WAKEUP_GPIO_LOW);
#else
esp_sleep_enable_ext1_wakeup(wake_mask, ESP_EXT1_WAKEUP_ANY_LOW);
#endif
#endif
if (ext1_mask != 0) {
if (esp_sleep_enable_ext1_wakeup(ext1_mask, ESP_EXT1_WAKEUP_ANY_HIGH)
!= ESP_OK) {
Serial.println(F("power: blad konfiguracji EXT1 (pin nie RTC?)"));
}
}
esp_deep_sleep_start();
}
uint64_t power_elapsed_ms(void)
{
/* System time jest utrzymywany przez RTC i przywracany po deep sleep,
* wiec licznik rosnie o rzeczywisty czas (takze ten spedzony w snie),
* a nie o planowany interwal - wczesniejsze wybudzenia (przycisk/LF)
* nie zaklamuja wtedy logiki "5 min po zaniku ACC". */
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)tv.tv_sec * 1000u + (uint64_t)(tv.tv_usec / 1000);
}
+3 -28
View File
@@ -1,37 +1,12 @@
/*
* power.h - zasilanie, pomiar napiecia, deep sleep
*/
#ifndef TPMS_POWER_H
#define TPMS_POWER_H
#include <stdint.h>
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Wywolac raz po starcie (zwalnia gpio_hold z poprzedniego snu). */
void power_init(void);
/* Pomiar napiecia zasilania [mV] (dzielnik ADC + kalibracja). */
uint32_t power_read_mv(void);
bool power_low_battery(uint32_t mv); /* only a warning about the emulator supply */
void power_deep_sleep(uint32_t ms); /* always has an RTC alarm; does not return */
/* Decyzja o fladze "niska bateria" (prog LOWBATT_THRESHOLD_MV). */
bool power_low_battery(uint32_t mV);
/* Przygotuj i wejdz w deep sleep na `seconds` (0 = bez budzika, tylko
* przycisk/LF). Funkcja nie wraca. */
void power_deep_sleep(uint32_t seconds);
/* Czas rzeczywisty [ms] od startu systemu - licznik RTC przetrwuje deep
* sleep (ESP32 przywraca czas z RTC po wybudzeniu), wiec rosnie o rzeczywisty
* czas spedzony w snie, nie o planowany interwal. Uzywane do logiki
* "5 min po zaniku ACC". */
uint64_t power_elapsed_ms(void);
#ifdef __cplusplus
}
#endif
#endif /* TPMS_POWER_H */
+52 -85
View File
@@ -1,14 +1,4 @@
/*
* radio.cpp - konfiguracja CC1101 i nadawanie ramek TPMS
*
* Modul: CC1101 po SPI (SCK=18, MISO=19, MOSI=23, CS=5, GDO0=2).
* Biblioteka: SmartRC-CC1101-Driver-Lib (LSatan), naglowek zgodnosciowy
* ELECHOUSE_CC1101_SRC_DRV.h - obslugiwane sa obie wersje API (2.x i 3.x).
*
* Nadawanie: tryb FIFO (pakiet o stalej dlugosci, bez preambuly/sync/CRC
* CC1101 - wszystkie bity, lacznie z preambula i wlasna suma kontrolna,
* leza w naszym buforze). Kolejnosc bitow MSB first.
*/
/* CC1101: raw 30 Manchester bytes into the fixed-length FIFO, no HW extras. */
#include <Arduino.h>
#include <SPI.h>
#include <ELECHOUSE_CC1101_SRC_DRV.h>
@@ -20,67 +10,54 @@
static bool radio_ok = false;
/* ------------------------------------------------------------------ */
/* Inicjalizacja pinow */
/* Wymagana biblioteka SmartRC-CC1101-Driver-Lib >= 2.5.7 */
/* (wspolne API setSpiPin/setGDO0 dla wersji 2.5.x i 3.x; */
/* starsze 1.x mialy setSCK/setMISO/... - nie sa obslugiwane). */
/* ------------------------------------------------------------------ */
static void radio_set_pins(void)
{
ELECHOUSE_cc1101.setSpiPin(PIN_CC1101_SCK, PIN_CC1101_MISO,
PIN_CC1101_MOSI, PIN_CC1101_CS);
ELECHOUSE_cc1101.setGDO0(PIN_CC1101_GDO0);
}
bool radio_init(void)
bool radio_init(const settings_t *cfg)
{
radio_ok = false;
if (cfg == NULL) {
return false;
}
gpio_deep_sleep_hold_dis();
gpio_hold_dis((gpio_num_t)PIN_CC1101_CS);
gpio_hold_dis((gpio_num_t)PIN_CC1101_SCK);
gpio_hold_dis((gpio_num_t)PIN_CC1101_MOSI);
radio_set_pins();
ELECHOUSE_cc1101.setSpiPin(PIN_CC1101_SCK, PIN_CC1101_MISO,
PIN_CC1101_MOSI, PIN_CC1101_CS);
ELECHOUSE_cc1101.setGDO0(PIN_CC1101_GDO0);
ELECHOUSE_cc1101.Init();
radio_ok = ELECHOUSE_cc1101.getCC1101();
if (!radio_ok) {
if (!ELECHOUSE_cc1101.getCC1101()) {
return false;
}
ELECHOUSE_cc1101.setCCMode(1); // tryb wewnetrzny, dane z FIFO
if (TPMS_MODULATION == MODE_FSK) {
ELECHOUSE_cc1101.setModulation(0); // 2-FSK
ELECHOUSE_cc1101.setDeviation(TPMS_DEVIATION_KHZ);
}
else {
ELECHOUSE_cc1101.setModulation(2); // ASK/OOK
}
ELECHOUSE_cc1101.setMHZ(TPMS_FREQUENCY_MHZ);
ELECHOUSE_cc1101.setDRate(1000.0f / (float)TPMS_CHIP_US); // kBaud (8.33)
ELECHOUSE_cc1101.setPA(TPMS_TX_POWER_DBM);
ELECHOUSE_cc1101.setCCMode(1);
ELECHOUSE_cc1101.setModulation(2); /* ASK/OOK; no FSK profile. */
ELECHOUSE_cc1101.setMHZ(cfg->frequency_mhz);
ELECHOUSE_cc1101.setDRate(1000.0f / (float)TPMS_CHIP_US);
ELECHOUSE_cc1101.setPA(cfg->tx_power_dbm);
ELECHOUSE_cc1101.setChannel(0);
ELECHOUSE_cc1101.setSyncMode(0); // bez preambuly/sync CC1101
/* SYNC_MODE=0: the packet engine adds no preamble or sync word. */
ELECHOUSE_cc1101.setSyncMode(0);
ELECHOUSE_cc1101.setPRE(0);
ELECHOUSE_cc1101.setAdrChk(0);
ELECHOUSE_cc1101.setAddr(0);
ELECHOUSE_cc1101.setWhiteData(0); // bez whiteningu
ELECHOUSE_cc1101.setManchester(0); // Manchester kodujemy sami
ELECHOUSE_cc1101.setWhiteData(0);
ELECHOUSE_cc1101.setManchester(0);
ELECHOUSE_cc1101.setFEC(0);
ELECHOUSE_cc1101.setCrc(0); // wlasna suma kontrolna protokolu
ELECHOUSE_cc1101.setCrc(0);
ELECHOUSE_cc1101.setCRC_AF(0);
ELECHOUSE_cc1101.setAppendStatus(0);
ELECHOUSE_cc1101.setDcFilterOff(0);
ELECHOUSE_cc1101.setPktFormat(0); // normalny tryb FIFO
ELECHOUSE_cc1101.setLengthConfig(0); // stala dlugosc pakietu
ELECHOUSE_cc1101.setPktFormat(0);
ELECHOUSE_cc1101.setLengthConfig(0);
ELECHOUSE_cc1101.setPacketLength(TPMS_TX_BYTES);
radio_ok = true;
return true;
}
bool radio_send_frame(const uint8_t *buf, uint8_t len)
{
if (!radio_ok) {
if (!radio_ok || buf == NULL || len != TPMS_TX_BYTES) {
return false;
}
@@ -89,48 +66,40 @@ bool radio_send_frame(const uint8_t *buf, uint8_t len)
ELECHOUSE_cc1101.SpiWriteBurstReg(CC1101_TXFIFO, (uint8_t *)buf, len);
ELECHOUSE_cc1101.SpiStrobe(CC1101_STX);
/* Pelny czas serializacji bufora na antenie: sprzet wysyla dokladnie
* len*8 chipow z predkoscia DRate. UWAGA: TXBYTES == 0 NIE oznacza
* konca transmisji - po oproznieniu FIFO ostatni bajt jest dopiero
* w rejestrze przesuwnym (8 chipow = 8*TPMS_CHIP_US), wiec wczesniejsze
* SIDLE obcialoby ogon ramki. Czekamy zatem na policzony czas + maly
* margines i dopiero wtedy wychodzimy z TX. */
uint32_t air_us = (uint32_t)len * 8u * (uint32_t)TPMS_CHIP_US + 1000u;
uint32_t t0 = micros();
while ((uint32_t)(micros() - t0) < air_us) {
delayMicroseconds(500);
}
/* Diagnostyka po zakonczeniu: dwa zgodne odczyty (errata CC1101),
* kontrola niedopelnienia FIFO i tego, czy bufor zostal faktycznie
* wyslany. Zwracamy blad zamiast udawac sukces. */
bool ok = true;
uint8_t txb = ELECHOUSE_cc1101.SpiReadStatus(CC1101_TXBYTES);
uint8_t txb2 = ELECHOUSE_cc1101.SpiReadStatus(CC1101_TXBYTES);
if (txb != txb2) {
txb = txb2;
}
if (txb & 0x80u) { // TXFIFO_UNDERFLOW
ok = false;
}
if ((txb & 0x7Fu) != 0) { // cos zostalo w FIFO - transmisja nie wyszla
ok = false;
/* We wait for MARCSTATE, not just TXBYTES=0: the last byte may still be
* in the shift register. The limit covers the start and the full tail. */
const uint32_t timeout_us = (uint32_t)len * 8u * TPMS_CHIP_US + 10000u;
const uint32_t start = micros();
bool finished = false;
bool underflow = false;
while ((uint32_t)(micros() - start) < timeout_us) {
uint8_t state = ELECHOUSE_cc1101.SpiReadStatus(CC1101_MARCSTATE) & 0x1Fu;
if (state == 0x16u) { /* TXFIFO_UNDERFLOW */
underflow = true;
break;
}
if (state == 0x01u) { /* IDLE after the automatic end of the packet */
finished = true;
break;
}
delayMicroseconds(50);
}
uint8_t txbytes = ELECHOUSE_cc1101.SpiReadStatus(CC1101_TXBYTES);
underflow |= (txbytes & 0x80u) != 0u;
ELECHOUSE_cc1101.SpiStrobe(CC1101_SIDLE);
ELECHOUSE_cc1101.SpiStrobe(CC1101_SFTX);
return ok;
return finished && !underflow && (txbytes & 0x7Fu) == 0u;
}
bool radio_send_burst(const uint8_t *buf, uint8_t len, uint8_t frames)
bool radio_send_burst(const uint8_t *buf, uint8_t len, uint8_t frames,
uint16_t gap_ms)
{
bool ok = true;
for (uint8_t i = 0; i < frames; i++) {
if (!radio_send_frame(buf, len)) {
ok = false;
}
if (i + 1u < frames) {
delay(TX_FRAME_GAP_MS);
for (uint8_t i = 0; i < frames; ++i) {
ok = radio_send_frame(buf, len) && ok;
if ((uint8_t)(i + 1u) < frames) {
delay(gap_ms);
}
}
return ok;
@@ -139,11 +108,9 @@ bool radio_send_burst(const uint8_t *buf, uint8_t len, uint8_t frames)
void radio_sleep(void)
{
if (radio_ok) {
ELECHOUSE_cc1101.goSleep(); // SIDLE + SPWD (sen po zboczu CS)
ELECHOUSE_cc1101.goSleep();
radio_ok = false;
}
/* Zwolnij peryferium SPI i ustaw linie w stanach bezpiecznych:
* CS=1 (utrzymuje CC1101 w sleep), SCK/MOSI=0, GDO0 wejscie z podciaganiem
* w dol (CC1101 w sleep trzystanuje wyjscia). */
SPI.end();
pinMode(PIN_CC1101_CS, OUTPUT);
digitalWrite(PIN_CC1101_CS, HIGH);
+6 -18
View File
@@ -1,34 +1,22 @@
/*
* radio.h - sterowanie CC1101 (nadawanie ramek TPMS, tryb uśpienia)
*/
#ifndef TPMS_RADIO_H
#define TPMS_RADIO_H
#include <stdint.h>
#include <stdbool.h>
#include "config.h"
#include <stdint.h>
#include "settings.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Inicjalizacja SPI + konfiguracja CC1101. Zwraca false przy braku modulu. */
bool radio_init(void);
/* Wyslij jeden bufor nadawczy (TPMS_TX_BYTES) - blokujace do zakonczenia
* transmisji na eterze (dokladnie len*8 chipow, ~29 ms). Zwraca false
* przy niedopelnieniu FIFO / niezakonczonej transmisji. */
bool radio_init(const settings_t *cfg);
bool radio_send_frame(const uint8_t *buf, uint8_t len);
/* Burst: n ramek tego samego bufora z odstepem TX_FRAME_GAP_MS.
* Zwraca false, jesli ktorykolwiek z ramek sie nie udal. */
bool radio_send_burst(const uint8_t *buf, uint8_t len, uint8_t frames);
/* CC1101 do trybu SLEEP (<1 uA) + przygotowanie linii pod gpio_hold. */
bool radio_send_burst(const uint8_t *buf, uint8_t len, uint8_t frames,
uint16_t gap_ms);
void radio_sleep(void);
#ifdef __cplusplus
}
#endif
#endif /* TPMS_RADIO_H */
#endif
+172
View File
@@ -0,0 +1,172 @@
#include "settings.h"
void settings_defaults(settings_t *out)
{
static const uint32_t ids[WHEEL_COUNT] = {
0x2FC871u, 0x2EAAF9u, 0x3495ACu, 0x2FC780u,
};
*out = settings_t{};
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
out->wheels[i].id = ids[i];
out->wheels[i].pressure_kpa10 = 2600u;
out->wheels[i].temp_c = 23;
}
out->flags = 0x4C900070u;
out->normal_interval_s = 30u;
out->ignition_interval_s = 30u;
out->parking_interval_s = 120u;
out->frequency_mhz = 433.92f;
out->tx_power_dbm = -10;
out->burst_frames = 3u;
out->frame_gap_ms = 50u;
}
bool settings_valid_id(uint32_t id)
{
return id > 0u && id < 0xFFFFFFu;
}
bool settings_valid_tx_power(int power_dbm)
{
static const int8_t allowed[] = {-30, -20, -15, -10, -6, 0, 5};
for (uint8_t i = 0; i < sizeof(allowed) / sizeof(allowed[0]); ++i) {
if (power_dbm == allowed[i]) {
return true;
}
}
return false;
}
static bool valid_interval(uint32_t value)
{
return value >= SETTINGS_INTERVAL_MIN_S && value <= SETTINGS_INTERVAL_MAX_S;
}
bool settings_validate(const settings_t *cfg)
{
if (cfg == NULL) {
return false;
}
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
if (!settings_valid_id(cfg->wheels[i].id)
|| cfg->wheels[i].pressure_kpa10 > SETTINGS_PRESSURE_MAX_KPA10
|| cfg->wheels[i].temp_c < -40 || cfg->wheels[i].temp_c > 85) {
return false;
}
for (uint8_t j = (uint8_t)(i + 1u); j < WHEEL_COUNT; ++j) {
if (cfg->wheels[i].id == cfg->wheels[j].id) {
return false;
}
}
}
return valid_interval(cfg->normal_interval_s)
&& valid_interval(cfg->ignition_interval_s)
&& valid_interval(cfg->parking_interval_s)
&& cfg->frequency_mhz >= 433.05f && cfg->frequency_mhz <= 434.79f
&& settings_valid_tx_power(cfg->tx_power_dbm)
&& cfg->burst_frames >= 1u && cfg->burst_frames <= 8u
&& cfg->frame_gap_ms >= 20u && cfg->frame_gap_ms <= 500u;
}
bool settings_set_id(settings_t *cfg, uint8_t wheel, uint32_t id)
{
if (cfg == NULL || wheel >= WHEEL_COUNT || !settings_valid_id(id)) {
return false;
}
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
if (i != wheel && cfg->wheels[i].id == id) {
return false;
}
}
cfg->wheels[wheel].id = id;
return true;
}
void settings_generate_ids(settings_t *cfg, uint32_t seed)
{
if (seed == 0u) {
seed = 0x6D2B79F5u;
}
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
uint32_t candidate;
bool duplicate;
do {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
candidate = (seed & 0xFFFFFFu);
if (!settings_valid_id(candidate)) {
candidate = (candidate % 0xFFFFFEu) + 1u;
}
duplicate = false;
for (uint8_t j = 0; j < i; ++j) {
duplicate |= cfg->wheels[j].id == candidate;
}
} while (duplicate);
cfg->wheels[i].id = candidate;
}
}
uint32_t settings_crc32(const void *data, size_t len)
{
const uint8_t *p = (const uint8_t *)data;
uint32_t crc = 0xFFFFFFFFu;
for (size_t i = 0; i < len; ++i) {
crc ^= p[i];
for (uint8_t bit = 0; bit < 8u; ++bit) {
crc = (crc >> 1) ^ ((crc & 1u) ? 0xEDB88320u : 0u);
}
}
return ~crc;
}
void settings_make_blob(const settings_t *cfg, settings_blob_t *blob)
{
*blob = settings_blob_t{};
blob->magic = SETTINGS_MAGIC;
blob->version = SETTINGS_VERSION;
blob->size = sizeof(blob->values);
blob->values = *cfg;
blob->crc32 = settings_crc32(blob, offsetof(settings_blob_t, crc32));
}
settings_load_result_t settings_decode_blob(const settings_blob_t *blob,
settings_t *out)
{
if (blob == NULL || out == NULL) {
return SETTINGS_LOAD_IO_ERROR;
}
if (blob->magic != SETTINGS_MAGIC) {
return SETTINGS_LOAD_BAD_MAGIC;
}
if (blob->version != SETTINGS_VERSION) {
return SETTINGS_LOAD_BAD_VERSION;
}
if (blob->size != sizeof(blob->values)) {
return SETTINGS_LOAD_BAD_SIZE;
}
uint32_t expected = settings_crc32(blob, offsetof(settings_blob_t, crc32));
if (expected != blob->crc32) {
return SETTINGS_LOAD_BAD_CRC;
}
if (!settings_validate(&blob->values)) {
return SETTINGS_LOAD_INVALID;
}
*out = blob->values;
return SETTINGS_LOAD_OK;
}
const char *settings_load_result_text(settings_load_result_t result)
{
switch (result) {
case SETTINGS_LOAD_OK: return "OK";
case SETTINGS_LOAD_EMPTY: return "empty configuration";
case SETTINGS_LOAD_BAD_MAGIC: return "bad magic";
case SETTINGS_LOAD_BAD_VERSION: return "unsupported version";
case SETTINGS_LOAD_BAD_SIZE: return "invalid size";
case SETTINGS_LOAD_BAD_CRC: return "CRC error";
case SETTINGS_LOAD_INVALID: return "invalid values";
case SETTINGS_LOAD_IO_ERROR: return "NVS error";
default: return "unknown error";
}
}
+81
View File
@@ -0,0 +1,81 @@
/* Persistent user configuration; module independent of Arduino. */
#ifndef TPMS_SETTINGS_H
#define TPMS_SETTINGS_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SETTINGS_MAGIC 0x54504D53u
#define SETTINGS_VERSION 1u
#define WHEEL_COUNT 4
#define SETTINGS_PRESSURE_MAX_KPA10 6375u
#define SETTINGS_INTERVAL_MIN_S 5u
#define SETTINGS_INTERVAL_MAX_S 86400u
typedef enum {
WHEEL_FL = 0,
WHEEL_FR = 1,
WHEEL_RR = 2,
WHEEL_RL = 3,
} wheel_t;
typedef struct {
uint32_t id;
uint16_t pressure_kpa10;
int16_t temp_c;
} sensor_settings_t;
typedef struct {
sensor_settings_t wheels[WHEEL_COUNT];
uint32_t flags;
uint32_t normal_interval_s;
uint32_t ignition_interval_s;
uint32_t parking_interval_s;
float frequency_mhz;
int8_t tx_power_dbm;
uint8_t burst_frames;
uint16_t frame_gap_ms;
} settings_t;
typedef struct {
uint32_t magic;
uint32_t version;
uint32_t size;
settings_t values;
uint32_t crc32;
} settings_blob_t;
typedef enum {
SETTINGS_LOAD_OK = 0,
SETTINGS_LOAD_EMPTY,
SETTINGS_LOAD_BAD_MAGIC,
SETTINGS_LOAD_BAD_VERSION,
SETTINGS_LOAD_BAD_SIZE,
SETTINGS_LOAD_BAD_CRC,
SETTINGS_LOAD_INVALID,
SETTINGS_LOAD_IO_ERROR,
} settings_load_result_t;
void settings_defaults(settings_t *out);
bool settings_valid_id(uint32_t id);
bool settings_validate(const settings_t *cfg);
bool settings_set_id(settings_t *cfg, uint8_t wheel, uint32_t id);
void settings_generate_ids(settings_t *cfg, uint32_t seed);
bool settings_valid_tx_power(int power_dbm);
uint32_t settings_crc32(const void *data, size_t len);
void settings_make_blob(const settings_t *cfg, settings_blob_t *blob);
settings_load_result_t settings_decode_blob(const settings_blob_t *blob,
settings_t *out);
const char *settings_load_result_text(settings_load_result_t result);
#ifdef __cplusplus
}
#endif
#endif
+73
View File
@@ -0,0 +1,73 @@
#include <Arduino.h>
#include <Preferences.h>
#include <string.h>
#include "settings_store.h"
static Preferences preferences;
static settings_load_result_t last_load = SETTINGS_LOAD_EMPTY;
static bool store_available = false;
settings_t g_settings;
void settings_store_begin()
{
settings_defaults(&g_settings);
store_available = preferences.begin("tpms", false);
if (!store_available) {
last_load = SETTINGS_LOAD_IO_ERROR;
return;
}
settings_blob_t blob;
size_t length = preferences.getBytesLength("config");
if (length == 0u) {
last_load = SETTINGS_LOAD_EMPTY;
settings_store_save();
return;
}
if (length != sizeof(blob)
|| preferences.getBytes("config", &blob, sizeof(blob)) != sizeof(blob)) {
last_load = SETTINGS_LOAD_BAD_SIZE;
} else {
last_load = settings_decode_blob(&blob, &g_settings);
}
if (last_load != SETTINGS_LOAD_OK) {
settings_defaults(&g_settings);
/* Recovery from corruption: save consistent defaults. */
settings_store_save();
}
}
bool settings_store_save()
{
if (!store_available || !settings_validate(&g_settings)) {
return false;
}
settings_blob_t blob;
settings_make_blob(&g_settings, &blob);
if (preferences.putBytes("config", &blob, sizeof(blob)) != sizeof(blob)) {
return false;
}
settings_blob_t verify;
if (preferences.getBytes("config", &verify, sizeof(verify)) != sizeof(verify)
|| memcmp(&blob, &verify, sizeof(blob)) != 0) {
return false;
}
return true;
}
bool settings_store_factory_reset()
{
settings_defaults(&g_settings);
return settings_store_save();
}
settings_load_result_t settings_store_last_load()
{
return last_load;
}
bool settings_store_available()
{
return store_available;
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef TPMS_SETTINGS_STORE_H
#define TPMS_SETTINGS_STORE_H
#include "settings.h"
extern settings_t g_settings;
void settings_store_begin();
bool settings_store_save();
bool settings_store_factory_reset();
settings_load_result_t settings_store_last_load();
bool settings_store_available();
#endif
+49 -63
View File
@@ -1,97 +1,83 @@
/*
* tpms_frame.cpp - generator ramek TPMS Schrader EG53MA4 (bez zaleznosci
* od Arduino - kompilowalne takze natywnie w testach).
*
* Zastrzezenie: symulator generuje sztuczne dane cisnienia/temperatury
* i nie zastepuje prawdziwych czujnikow TPMS.
*/
/* EG53MA4 frame generator. Synthetic data for diagnostics only. */
#include <string.h>
#include "config.h"
#include "settings.h"
#include "tpms_frame.h"
static void put_bit(uint8_t *buf, unsigned *nbits, unsigned v)
static void put_bit(uint8_t *buf, unsigned *nbits, unsigned value)
{
if (v) {
if (value != 0u) {
buf[*nbits >> 3] |= (uint8_t)(0x80u >> (*nbits & 7u));
}
(*nbits)++;
++(*nbits);
}
/* G.E.T. Manchester: 0 -> "01", 1 -> "10" */
/* Polarity confirmed by captures and rtl_433 OOK_MC_ZEROBIT: 0=01, 1=10. */
static void put_cell(uint8_t *buf, unsigned *nbits, unsigned bit)
{
if (bit) {
put_bit(buf, nbits, 1);
put_bit(buf, nbits, 0);
}
else {
put_bit(buf, nbits, 0);
put_bit(buf, nbits, 1);
}
put_bit(buf, nbits, bit != 0u ? 1u : 0u);
put_bit(buf, nbits, bit != 0u ? 0u : 1u);
}
uint8_t tpms_build_payload(uint8_t out[TPMS_PAYLOAD_LEN], uint32_t id,
uint16_t press_kpa10, int8_t temp_c,
uint32_t flags, bool low_batt)
bool tpms_build_payload(uint8_t out[TPMS_PAYLOAD_LEN], uint32_t id,
uint16_t press_kpa10, int8_t temp_c, uint32_t flags)
{
if (low_batt) {
flags |= TPMS_FLAGS_LOWBAT_MASK;
if (out == NULL || !settings_valid_id(id)) {
return false;
}
/* cisnienie: 25 mbar/bit = 2.5 kPa/bit, zaokraglenie w gore do polowy bitu */
int32_t press = ((int32_t)press_kpa10 + 12) / 25;
if (press < 0) press = 0;
if (press > 255) press = 255;
int32_t pressure = ((int32_t)press_kpa10 * 10 + TPMS_PRESSURE_KPA100_PER_RAW / 2)
/ TPMS_PRESSURE_KPA100_PER_RAW;
if (pressure > 255) {
pressure = 255;
}
/* temperatura: protokol podaje stopnie Fahrenheita */
int32_t num = 9 * (int32_t)temp_c + 160;
int32_t tf = (num >= 0) ? (num + 2) / 5 : -((-num + 2) / 5);
if (tf < 0) tf = 0;
if (tf > 255) tf = 255;
int32_t numerator = 9 * (int32_t)temp_c + 160;
int32_t temperature_f = numerator >= 0
? (numerator + 2) / 5 : -((-numerator + 2) / 5);
if (temperature_f < 0) {
temperature_f = 0;
} else if (temperature_f > 255) {
temperature_f = 255;
}
out[0] = (uint8_t)(flags >> 24);
out[1] = (uint8_t)(flags >> 16);
out[2] = (uint8_t)(flags >> 8);
out[3] = (uint8_t)(flags);
out[3] = (uint8_t)flags;
out[4] = (uint8_t)(id >> 16);
out[5] = (uint8_t)(id >> 8);
out[6] = (uint8_t)(id);
out[7] = (uint8_t)press;
out[8] = (uint8_t)tf;
uint8_t crc = 0;
for (unsigned i = 0; i < 9; i++) {
crc = (uint8_t)(crc + out[i]); // suma mod 256 (add_bytes w rtl_433)
out[6] = (uint8_t)id;
out[7] = (uint8_t)pressure;
out[8] = (uint8_t)temperature_f;
uint8_t checksum = 0;
for (uint8_t i = 0; i < 9u; ++i) {
checksum = (uint8_t)(checksum + out[i]);
}
out[9] = crc;
return crc;
out[9] = checksum;
return true;
}
void tpms_build_frame(uint8_t out[TPMS_TX_BYTES], uint32_t id,
uint16_t press_kpa10, int8_t temp_c,
uint32_t flags, bool low_batt)
bool tpms_build_frame(uint8_t out[TPMS_TX_BYTES], uint32_t id,
uint16_t press_kpa10, int8_t temp_c, uint32_t flags)
{
uint8_t payload[TPMS_PAYLOAD_LEN];
tpms_build_payload(payload, id, press_kpa10, temp_c, flags, low_batt);
if (out == NULL || !tpms_build_payload(payload, id, press_kpa10, temp_c, flags)) {
return false;
}
memset(out, 0, TPMS_TX_BYTES);
unsigned nbits = 0;
put_bit(out, &nbits, 1); // chip rozbiegowy (carrier on)
/* 39 bitow sync - pierwszy (zerowy) bit dopisuje odbiornik (MC_ZEROBIT) */
for (unsigned i = 0; i < TPMS_SYNC_BITS - 1; i++) {
put_cell(out, &nbits, 0);
put_bit(out, &nbits, 1u); /* starting chip */
for (unsigned i = 0; i < TPMS_SYNC_BITS - 1u; ++i) {
put_cell(out, &nbits, 0u);
}
/* 80 bitow payloadu */
for (unsigned b = 0; b < 8u * TPMS_PAYLOAD_LEN; b++) {
unsigned bit = (payload[b >> 3] >> (7 - (b & 7u))) & 1u;
put_cell(out, &nbits, bit);
for (unsigned bit = 0; bit < 8u * TPMS_PAYLOAD_LEN; ++bit) {
unsigned value = (payload[bit >> 3] >> (7u - (bit & 7u))) & 1u;
put_cell(out, &nbits, value);
}
/* padding do granicy bajtu - dla OOK sa to chipy "off" = cisza w eterze */
while (nbits % 8u) {
put_bit(out, &nbits, 0);
while ((nbits & 7u) != 0u) {
put_bit(out, &nbits, 0u);
}
return nbits == TPMS_TX_CHIPS;
}
+24 -52
View File
@@ -1,70 +1,42 @@
/*
* tpms_frame.h - generator ramek TPMS Schrader EG53MA4
*
* Zastrzezenie: dane sa sztuczne (diagnostyka/testy), nie zastepuja
* prawdziwych czujnikow TPMS.
*
* Ramka na zrzuconej warstwie bitowej (120 bitow, po dekodowaniu
* Manchester przez rtl_433 OOK_MC_ZEROBIT):
*
* 40 bit sync (zera) | flags(4B) | id(3B) | pressure(1B) | temp(1B) | crc(1B)
*
* - flags: 32 bity, wg dekodera "moze zawierac preamble/status/battery"
* - pressure: 25 mbar/bit (cisnienie w kPa = bajt * 2.5)
* - temperature: stopnie Fahrenheita
* - crc: suma 9 poprzednich bajtow mod 256 (add_bytes w rtl_433)
*
* Kodowanie na zrzuconej warstwie RF (G.E.T. Manchester):
* bit 0 -> chipy "01", bit 1 -> chipy "10", chip = 120 us
* Odbiornik rtl_433 (MC_ZEROBIT) dopisuje pierwszy bit ramki samodzielnie,
* wiec nadajnik wysyla ramke BEZ pierwszego bitu, poprzedzona jednym
* chipem rozbiegowym '1'. Bufor wyjsciowy jest dopełniany zerami do
* granicy bajtu (dla OOK sa to chipy "wylaczone" = cisza).
*/
/* Schrader EG53MA4: 40 sync bits + 80 data bits, OOK Manchester. */
#ifndef TPMS_FRAME_H
#define TPMS_FRAME_H
#include <stdint.h>
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define TPMS_ROW_BITS 120 // dlugosc dekodowanej ramki (wymagana przez rtl_433)
#define TPMS_SYNC_BITS 40
#define TPMS_PAYLOAD_LEN 10 // flags(4)+id(3)+press+temp+crc
#define TPMS_TX_BYTES 30 // 240 chipow = 1 lead + 238 danych + 1 padding
#define TPMS_TX_CHIPS (TPMS_TX_BYTES * 8)
#define TPMS_ROW_BITS 120
#define TPMS_SYNC_BITS 40
#define TPMS_PAYLOAD_LEN 10
#define TPMS_TX_BYTES 30
#define TPMS_TX_CHIPS (TPMS_TX_BYTES * 8)
/* Calibration of the P field: how many hundredths of a kPa one bit of the
* P byte represents. The rtl_433 scale (250 = 2.5 kPa/bit) is not confirmed
* by the captures (all have P=0), while a car measurement showed
* 260 kPa -> 284 kPa on the display at P=104, so a scaling correction of
* 2.73 kPa/bit gives P=95 for 260 kPa. Confirmed with the car:
* 260 kPa -> 260 kPa on the display (docs/AUDIT.md) -
* also change PRESSURE_KPA100_PER_RAW in tools/tpms_frame.py. */
#define TPMS_PRESSURE_KPA100_PER_RAW 273
#ifdef __cplusplus
/* Zaleznosc bufora nadawczego od dlugosci ramki: 1 chip rozbiegowy +
* 2 chipy na kazdy z (TPMS_ROW_BITS-1) bitow (pierwszy bit dopisuje
* odbiornik) + padding do granicy bajtu (< 8 chipow). */
static_assert(TPMS_TX_CHIPS >= 1 + 2 * (TPMS_ROW_BITS - 1)
&& TPMS_TX_CHIPS < 1 + 2 * (TPMS_ROW_BITS - 1) + 8,
"TPMS_TX_BYTES musi miescic 1 + 2*(TPMS_ROW_BITS-1) chipow");
static_assert(TPMS_TX_CHIPS == 1 + 2 * (TPMS_ROW_BITS - 1) + 1,
"Invalid Manchester buffer length");
#endif
typedef struct {
uint32_t id; // 24-bit identyfikator czujnika
uint16_t press_kpa10; // cisnienie w kPa * 10 (np. 2600 = 260.0 kPa)
int8_t temp_c; // temperatura w st. C
const char *name; // "FL", "FR", "RR", "RL"
} tpms_sensor_t;
/* Zbuduj 10-bajtowy payload (bez sync). Zwraca crc (tez wpisane do out[9]). */
uint8_t tpms_build_payload(uint8_t out[TPMS_PAYLOAD_LEN], uint32_t id,
uint16_t press_kpa10, int8_t temp_c,
uint32_t flags, bool low_batt);
/* Zbuduj kompletny bufor nadawczy (TPMS_TX_BYTES) gotowy do CC1101 FIFO. */
void tpms_build_frame(uint8_t out[TPMS_TX_BYTES], uint32_t id,
uint16_t press_kpa10, int8_t temp_c,
uint32_t flags, bool low_batt);
/* Returns false for ID 0, 0xFFFFFF and values outside 24 bits. */
bool tpms_build_payload(uint8_t out[TPMS_PAYLOAD_LEN], uint32_t id,
uint16_t press_kpa10, int8_t temp_c, uint32_t flags);
bool tpms_build_frame(uint8_t out[TPMS_TX_BYTES], uint32_t id,
uint16_t press_kpa10, int8_t temp_c, uint32_t flags);
#ifdef __cplusplus
}
#endif
#endif /* TPMS_FRAME_H */
#endif
+22 -22
View File
@@ -1,19 +1,19 @@
/*
* ui.cpp - przycisk (gesty) i LED statusowy (nieblokujaco, bez delay())
* ui.cpp - button (gestures) and status LED (non-blocking, no delay())
*/
#include <Arduino.h>
#include "config.h"
#include "ui.h"
/* ---------------------------- przycisk ---------------------------- */
/* Debounce: nowy stan surowy musi sie utrzymac BTN_DEBOUNCE_MS, zanim
* zostanie uznany za stan stabilny (kandydat + czas jego zmiany). */
/* ---------------------------- button ---------------------------- */
/* Debounce: the new raw state must persist for BTN_DEBOUNCE_MS before it is
* accepted as stable (candidate + the time it changed). */
static bool btn_raw_last = false; // ostatni surowy odczyt
static uint32_t btn_raw_change = 0; // czas ostatniej zmiany surowej
static bool btn_stable = false; // stan po debounce
static bool btn_raw_last = false; // last raw reading
static uint32_t btn_raw_change = 0; // time of the last raw change
static bool btn_stable = false; // debounced state
static uint32_t btn_press_start = 0;
static bool btn_long_fired = false; // bardzo dlugie zdarzenie juz wyslane
static bool btn_long_fired = false; // very long event already reported
bool ui_button_down(void)
{
@@ -24,14 +24,14 @@ void ui_init(void)
{
pinMode(PIN_BUTTON, BTN_ACTIVE_LEVEL ? INPUT_PULLDOWN : INPUT_PULLUP);
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, LOW);
digitalWrite(PIN_LED, LED_ACTIVE_LEVEL ? LOW : HIGH);
uint32_t now = millis();
bool raw = (digitalRead(PIN_BUTTON) == BTN_ACTIVE_LEVEL);
btn_raw_last = raw;
btn_raw_change = now;
btn_stable = raw;
btn_press_start = now; // start z wcisnietym przyciskiem = poczatek gestu
btn_press_start = now; // starting pressed = beginning of a gesture
btn_long_fired = false;
}
@@ -42,12 +42,12 @@ ui_event_t ui_poll(void)
uint32_t now = millis();
if (raw != btn_raw_last) {
/* kandydat - czekaj az stan sie utrzyma */
/* candidate - wait until the state persists */
btn_raw_last = raw;
btn_raw_change = now;
}
else if (raw != btn_stable && (now - btn_raw_change) >= BTN_DEBOUNCE_MS) {
btn_stable = raw; // zaakceptowany po debounce
btn_stable = raw; // accepted after debounce
if (btn_stable) {
btn_press_start = now;
btn_long_fired = false;
@@ -60,7 +60,7 @@ ui_event_t ui_poll(void)
}
}
/* bardzo dlugi przycisk sygnalizujemy od razu (nie czekajac na puszczenie) */
/* very long press is signalled immediately (without waiting for release) */
if (btn_stable && !btn_long_fired && (now - btn_press_start) >= BTN_VERYLONG_MS) {
btn_long_fired = true;
ev = UI_EV_VERYLONG;
@@ -73,7 +73,7 @@ ui_event_t ui_poll(void)
static ui_pat_t led_pat = UI_PAT_OFF;
static uint8_t led_blinks_left = 0;
static bool led_on = false;
static bool led_series = false; // seria migniec w trakcie
static bool led_series = false; // blink series in progress
static uint32_t led_next = 0;
void ui_set_pattern(ui_pat_t pat)
@@ -82,7 +82,7 @@ void ui_set_pattern(ui_pat_t pat)
led_blinks_left = 0;
led_on = false;
led_series = false;
digitalWrite(PIN_LED, LOW);
digitalWrite(PIN_LED, LED_ACTIVE_LEVEL ? LOW : HIGH);
led_next = millis();
}
@@ -103,8 +103,8 @@ void ui_update(void)
if (led_series) {
if (led_on) {
/* koniec migniecia */
digitalWrite(PIN_LED, LOW);
/* end of a blink */
digitalWrite(PIN_LED, LED_ACTIVE_LEVEL ? LOW : HIGH);
led_on = false;
if (led_blinks_left > 0) {
led_blinks_left--;
@@ -112,13 +112,13 @@ void ui_update(void)
led_next = now + 90;
}
else if (led_blinks_left > 0) {
/* kolejne migniecie */
digitalWrite(PIN_LED, HIGH);
/* next blink */
digitalWrite(PIN_LED, LED_ACTIVE_LEVEL ? HIGH : LOW);
led_on = true;
led_next = now + 90;
}
else {
/* koniec serii - przerwa zalezna od wzorca */
/* end of the series - gap depends on the pattern */
led_series = false;
uint32_t idle = 2000;
switch (led_pat) {
@@ -133,9 +133,9 @@ void ui_update(void)
return;
}
/* rozpoczynamy serie wg wzorca */
/* start the series for the pattern */
if (led_pat == UI_PAT_OFF) {
digitalWrite(PIN_LED, LOW);
digitalWrite(PIN_LED, LED_ACTIVE_LEVEL ? LOW : HIGH);
led_next = now + 50;
return;
}
+9 -9
View File
@@ -1,5 +1,5 @@
/*
* ui.h - przycisk (gesty) i LED statusowy
* ui.h - button (gestures) and status LED
*/
#ifndef TPMS_UI_H
#define TPMS_UI_H
@@ -14,28 +14,28 @@ extern "C" {
typedef enum {
UI_EV_NONE = 0,
UI_EV_SHORT, // < BTN_LONG_MS
UI_EV_LONG, // >= BTN_LONG_MS (wejscie/wyjscie LEARN)
UI_EV_VERYLONG, // >= BTN_VERYLONG_MS (wejscie/wyjscie SINGLE)
UI_EV_LONG, // >= BTN_LONG_MS (enter/exit LEARN)
UI_EV_VERYLONG, // >= BTN_VERYLONG_MS (enter/exit SINGLE)
} ui_event_t;
typedef enum {
UI_PAT_OFF = 0,
UI_PAT_NORMAL, // 1 migniecie co 2 s
UI_PAT_LEARN, // 3 szybkie migniecia co 0.5 s
UI_PAT_SINGLE, // 2 szybkie migniecia co 0.5 s
UI_PAT_LOWBAT, // 10 szybkich migniec co 3 s
UI_PAT_NORMAL, // 1 blink every 2 s
UI_PAT_LEARN, // 3 quick blinks every 0.5 s
UI_PAT_SINGLE, // 2 quick blinks every 0.5 s
UI_PAT_LOWBAT, // 10 quick blinks every 3 s
} ui_pat_t;
void ui_init(void);
/* Nieblokujaca obsluga przycisku i LED - wywolywac w kazdej petli. */
/* Non-blocking button and LED handling - call in every loop. */
ui_event_t ui_poll(void);
void ui_update(void);
bool ui_button_down(void);
void ui_set_pattern(ui_pat_t pat);
/* Seria n szybkich migniec (np. numer kola: 1-4). */
/* Series of n quick blinks (e.g. wheel number: 1-4). */
void ui_blink_count(uint8_t n);
#ifdef __cplusplus
+201
View File
@@ -0,0 +1,201 @@
#include <unity.h>
#include "app_state.h"
class FakeRadio final : public RadioSink {
public:
uint8_t wheels[128];
uint8_t count = 0;
bool fail = false;
bool send(uint8_t wheel) override
{
if (count < sizeof(wheels)) wheels[count] = wheel;
++count;
return !fail;
}
};
void setUp(void) {}
void tearDown(void) {}
static void test_normal_clone_ids_sends_four_wheels_and_repeats(void)
{
settings_t cfg;
settings_defaults(&cfg);
cfg.wheels[0].id = 0x111111u; /* Clone IDs: configuration without LEARN. */
FakeRadio radio;
AppState app(&cfg, &radio);
app.begin(0u);
TEST_ASSERT_EQUAL_UINT8(4u, radio.count);
static const uint8_t expected[] = {0, 1, 2, 3};
TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, radio.wheels, 4);
app.tick(29999u, false);
TEST_ASSERT_EQUAL_UINT8(4u, radio.count);
app.tick(30000u, false);
TEST_ASSERT_EQUAL_UINT8(8u, radio.count);
}
static void test_new_ids_learn_order_force_and_finish(void)
{
settings_t cfg;
settings_defaults(&cfg);
settings_generate_ids(&cfg, 42u);
TEST_ASSERT_TRUE(settings_validate(&cfg));
FakeRadio radio;
AppState app(&cfg, &radio);
app.begin(0u, false);
app.set_mode(AppMode::LEARN, WHEEL_FL, 0u);
TEST_ASSERT_EQUAL(AppMode::LEARN, app.mode());
TEST_ASSERT_EQUAL_UINT8(1u, radio.count);
TEST_ASSERT_EQUAL_UINT8(WHEEL_FL, radio.wheels[0]);
TEST_ASSERT_TRUE(app.send_current()); /* force TX without changing wheel */
TEST_ASSERT_EQUAL_UINT8(2u, radio.count);
app.short_press(100u);
TEST_ASSERT_EQUAL_UINT8(WHEEL_FR, app.active_wheel());
app.short_press(200u);
TEST_ASSERT_EQUAL_UINT8(WHEEL_RR, app.active_wheel());
app.short_press(300u);
TEST_ASSERT_EQUAL_UINT8(WHEEL_RL, app.active_wheel());
app.short_press(400u);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
static const uint8_t expected[] = {0, 0, 1, 2, 3};
TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, radio.wheels, 5);
}
static void test_learn_period_window_and_total_timeout(void)
{
settings_t cfg;
settings_defaults(&cfg);
FakeRadio radio;
AppState app(&cfg, &radio);
app.set_mode(AppMode::LEARN, WHEEL_FL, 0u);
app.tick(1999u, false);
TEST_ASSERT_EQUAL_UINT8(1u, radio.count);
app.tick(2000u, false);
TEST_ASSERT_EQUAL_UINT8(2u, radio.count);
app.tick(59999u, false);
TEST_ASSERT_EQUAL(AppMode::LEARN, app.mode());
app.tick(60000u, false);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
TEST_ASSERT_EQUAL_UINT8(3u, radio.count); /* timeout sends no new frame */
app.set_mode(AppMode::LEARN, WHEEL_FL, 100000u);
app.tick(1000000u, false);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
}
static void test_single_isolated_wheel_and_timeout(void)
{
settings_t cfg;
settings_defaults(&cfg);
FakeRadio radio;
AppState app(&cfg, &radio);
app.set_mode(AppMode::SINGLE, WHEEL_FR, 0u);
TEST_ASSERT_EQUAL_UINT8(1u, radio.count);
TEST_ASSERT_EQUAL_UINT8(WHEEL_FR, radio.wheels[0]);
app.tick(2000u, false);
TEST_ASSERT_EQUAL_UINT8(2u, radio.count);
TEST_ASSERT_EQUAL_UINT8(WHEEL_FR, radio.wheels[1]);
app.next_wheel(3000u);
TEST_ASSERT_EQUAL_UINT8(WHEEL_RR, app.active_wheel());
app.tick(300000u, false);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
}
static void test_button_gestures(void)
{
settings_t cfg;
settings_defaults(&cfg);
FakeRadio radio;
AppState app(&cfg, &radio);
app.begin(0u, false);
app.long_press(0u);
TEST_ASSERT_EQUAL(AppMode::LEARN, app.mode());
app.long_press(10u);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
app.very_long_press(20u);
TEST_ASSERT_EQUAL(AppMode::SINGLE, app.mode());
app.very_long_press(30u);
TEST_ASSERT_EQUAL(AppMode::NORMAL, app.mode());
app.short_press(40u);
TEST_ASSERT_EQUAL_UINT8(6u, radio.count); /* LEARN + SINGLE + 4 wheels NORMAL */
}
static void test_acc_intervals_without_permanent_shutdown(void)
{
settings_t cfg;
settings_defaults(&cfg);
cfg.ignition_interval_s = 15u;
cfg.parking_interval_s = 120u;
FakeRadio radio;
AppState app(&cfg, &radio);
app.begin(0u);
app.tick(30000u, true);
app.tick(45000u, true);
TEST_ASSERT_EQUAL_UINT8(12u, radio.count);
app.tick(60000u, false);
TEST_ASSERT_EQUAL_UINT8(16u, radio.count);
app.tick(179999u, false);
TEST_ASSERT_EQUAL_UINT8(16u, radio.count);
app.tick(180000u, false);
TEST_ASSERT_EQUAL_UINT8(20u, radio.count);
TEST_ASSERT_EQUAL_UINT32(15u, app.interval_s(true));
TEST_ASSERT_EQUAL_UINT32(120u, app.interval_s(false));
}
static void test_power_restart_and_nvs_reloaded_configuration(void)
{
settings_t persisted;
settings_defaults(&persisted);
persisted.wheels[3].id = 0x654321u;
settings_blob_t blob;
settings_make_blob(&persisted, &blob);
settings_t reloaded;
TEST_ASSERT_EQUAL(SETTINGS_LOAD_OK, settings_decode_blob(&blob, &reloaded));
FakeRadio radio;
AppState after_restart(&reloaded, &radio);
after_restart.begin(1000u);
TEST_ASSERT_EQUAL(AppMode::NORMAL, after_restart.mode());
TEST_ASSERT_EQUAL_UINT8(4u, radio.count);
TEST_ASSERT_EQUAL_HEX32(0x654321u, reloaded.wheels[3].id);
}
static void test_radio_failure_is_counted_and_other_wheels_continue(void)
{
settings_t cfg;
settings_defaults(&cfg);
FakeRadio radio;
radio.fail = true;
AppState app(&cfg, &radio);
app.begin(0u);
TEST_ASSERT_EQUAL_UINT8(4u, radio.count);
TEST_ASSERT_EQUAL_UINT32(4u, app.last_error_count());
}
static void test_millis_wrap_does_not_stall_learn(void)
{
settings_t cfg;
settings_defaults(&cfg);
FakeRadio radio;
AppState app(&cfg, &radio);
app.set_mode(AppMode::LEARN, WHEEL_FL, UINT32_MAX - 1000u);
app.tick(1000u, false); /* 2001 ms elapsed after the wrap */
TEST_ASSERT_EQUAL_UINT8(2u, radio.count);
}
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
UNITY_BEGIN();
RUN_TEST(test_normal_clone_ids_sends_four_wheels_and_repeats);
RUN_TEST(test_new_ids_learn_order_force_and_finish);
RUN_TEST(test_learn_period_window_and_total_timeout);
RUN_TEST(test_single_isolated_wheel_and_timeout);
RUN_TEST(test_button_gestures);
RUN_TEST(test_acc_intervals_without_permanent_shutdown);
RUN_TEST(test_power_restart_and_nvs_reloaded_configuration);
RUN_TEST(test_radio_failure_is_counted_and_other_wheels_continue);
RUN_TEST(test_millis_wrap_does_not_stall_learn);
return UNITY_END();
}
+71
View File
@@ -0,0 +1,71 @@
#include <string.h>
#include <unity.h>
#include "parse.h"
void setUp(void) {}
void tearDown(void) {}
static void test_u32_ranges_and_bases(void)
{
uint32_t value = 0u;
TEST_ASSERT_TRUE(parse_u32("260", 0u, 6375u, &value));
TEST_ASSERT_EQUAL_UINT32(260u, value);
TEST_ASSERT_TRUE(parse_u32("2FC871", 1u, 0xFFFFFEu, &value, 16));
TEST_ASSERT_EQUAL_HEX32(0x2FC871u, value);
TEST_ASSERT_FALSE(parse_u32("0", 1u, 10u, &value));
TEST_ASSERT_FALSE(parse_u32("11", 1u, 10u, &value));
TEST_ASSERT_FALSE(parse_u32("-1", 0u, 10u, &value));
TEST_ASSERT_FALSE(parse_u32("1x", 0u, 10u, &value));
TEST_ASSERT_FALSE(parse_u32("", 0u, 10u, &value));
TEST_ASSERT_FALSE(parse_u32(NULL, 0u, 10u, &value));
}
static void test_i32_ranges(void)
{
int32_t value = 0;
TEST_ASSERT_TRUE(parse_i32("-40", -40, 85, &value));
TEST_ASSERT_EQUAL_INT32(-40, value);
TEST_ASSERT_TRUE(parse_i32("85", -40, 85, &value));
TEST_ASSERT_EQUAL_INT32(85, value);
TEST_ASSERT_FALSE(parse_i32("-41", -40, 85, &value));
TEST_ASSERT_FALSE(parse_i32("86", -40, 85, &value));
TEST_ASSERT_FALSE(parse_i32("2.5", -40, 85, &value));
TEST_ASSERT_FALSE(parse_i32(NULL, -40, 85, &value));
}
static void test_float_ranges(void)
{
float value = 0.0f;
TEST_ASSERT_TRUE(parse_float("260.5", 0.0f, 637.5f, &value));
TEST_ASSERT_FLOAT_WITHIN(0.001f, 260.5f, value);
TEST_ASSERT_TRUE(parse_float("0", 0.0f, 637.5f, &value));
TEST_ASSERT_TRUE(parse_float("637.5", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("637.6", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("-0.1", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("260,5", 0.0f, 637.5f, &value));
}
static void test_float_rejects_nan_and_infinity(void)
{
/* Regression: NaN passed the old range test (both comparisons false),
* ended up in NVS as pressure and blocked later RF frequency saves. */
float value = 0.0f;
TEST_ASSERT_FALSE(parse_float("nan", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("-nan", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("NaN", 0.0f, 637.5f, &value));
TEST_ASSERT_FALSE(parse_float("inf", 433.05f, 434.79f, &value));
TEST_ASSERT_FALSE(parse_float("-inf", 433.05f, 434.79f, &value));
TEST_ASSERT_FALSE(parse_float("nan", -40.0f, 85.0f, &value));
}
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
UNITY_BEGIN();
RUN_TEST(test_u32_ranges_and_bases);
RUN_TEST(test_i32_ranges);
RUN_TEST(test_float_ranges);
RUN_TEST(test_float_rejects_nan_and_infinity);
return UNITY_END();
}
+112
View File
@@ -0,0 +1,112 @@
#include <string.h>
#include <unity.h>
#include "settings.h"
void setUp(void) {}
void tearDown(void) {}
static void test_defaults_are_safe_and_valid(void)
{
settings_t cfg;
settings_defaults(&cfg);
TEST_ASSERT_TRUE(settings_validate(&cfg));
for (uint8_t i = 0; i < WHEEL_COUNT; ++i) {
TEST_ASSERT_EQUAL_UINT16(2600u, cfg.wheels[i].pressure_kpa10);
TEST_ASSERT_TRUE(settings_valid_id(cfg.wheels[i].id));
}
TEST_ASSERT_EQUAL_INT8(-10, cfg.tx_power_dbm);
TEST_ASSERT_FLOAT_WITHIN(0.001f, 433.92f, cfg.frequency_mhz);
}
static void test_ids_must_be_24_bit_nonzero_and_unique(void)
{
settings_t cfg;
settings_defaults(&cfg);
TEST_ASSERT_FALSE(settings_set_id(&cfg, 0u, 0u));
TEST_ASSERT_FALSE(settings_set_id(&cfg, 0u, 0xFFFFFFu));
TEST_ASSERT_FALSE(settings_set_id(&cfg, 0u, 0x1000000u));
TEST_ASSERT_FALSE(settings_set_id(&cfg, 4u, 0x123456u));
TEST_ASSERT_FALSE(settings_set_id(&cfg, 0u, cfg.wheels[1].id));
TEST_ASSERT_TRUE(settings_set_id(&cfg, 0u, 0x123456u));
TEST_ASSERT_EQUAL_HEX32(0x123456u, cfg.wheels[0].id);
}
static void test_generated_ids_are_unique_and_deterministic_for_seed(void)
{
settings_t a, b;
settings_defaults(&a);
settings_defaults(&b);
settings_generate_ids(&a, 1234u);
settings_generate_ids(&b, 1234u);
TEST_ASSERT_TRUE(settings_validate(&a));
TEST_ASSERT_EQUAL_MEMORY(&a, &b, sizeof(a));
settings_generate_ids(&a, 0u);
TEST_ASSERT_TRUE(settings_validate(&a));
}
static void test_blob_round_trip_and_crc(void)
{
settings_t cfg, decoded;
settings_defaults(&cfg);
TEST_ASSERT_TRUE(settings_set_id(&cfg, WHEEL_FR, 0xABCDEFu));
cfg.wheels[2].pressure_kpa10 = 2555u;
settings_blob_t blob;
settings_make_blob(&cfg, &blob);
TEST_ASSERT_EQUAL_UINT32(SETTINGS_VERSION, blob.version);
TEST_ASSERT_EQUAL(SETTINGS_LOAD_OK, settings_decode_blob(&blob, &decoded));
TEST_ASSERT_EQUAL_MEMORY(&cfg, &decoded, sizeof(cfg));
blob.values.wheels[0].id ^= 1u;
TEST_ASSERT_EQUAL(SETTINGS_LOAD_BAD_CRC, settings_decode_blob(&blob, &decoded));
}
static void test_incompatible_version_size_magic_are_rejected(void)
{
settings_t cfg, decoded;
settings_defaults(&cfg);
settings_blob_t blob;
settings_make_blob(&cfg, &blob);
++blob.version;
TEST_ASSERT_EQUAL(SETTINGS_LOAD_BAD_VERSION, settings_decode_blob(&blob, &decoded));
settings_make_blob(&cfg, &blob);
--blob.size;
TEST_ASSERT_EQUAL(SETTINGS_LOAD_BAD_SIZE, settings_decode_blob(&blob, &decoded));
settings_make_blob(&cfg, &blob);
blob.magic = 0u;
TEST_ASSERT_EQUAL(SETTINGS_LOAD_BAD_MAGIC, settings_decode_blob(&blob, &decoded));
}
static void test_invalid_ranges_are_rejected_even_with_valid_crc(void)
{
settings_t cfg, decoded;
settings_defaults(&cfg);
settings_blob_t blob;
cfg.normal_interval_s = 4u;
settings_make_blob(&cfg, &blob);
TEST_ASSERT_EQUAL(SETTINGS_LOAD_INVALID, settings_decode_blob(&blob, &decoded));
settings_defaults(&cfg);
cfg.tx_power_dbm = 10;
settings_make_blob(&cfg, &blob);
TEST_ASSERT_EQUAL(SETTINGS_LOAD_INVALID, settings_decode_blob(&blob, &decoded));
settings_defaults(&cfg);
cfg.wheels[1].id = cfg.wheels[0].id;
settings_make_blob(&cfg, &blob);
TEST_ASSERT_EQUAL(SETTINGS_LOAD_INVALID, settings_decode_blob(&blob, &decoded));
settings_defaults(&cfg);
cfg.frequency_mhz = 434.80f;
settings_make_blob(&cfg, &blob);
TEST_ASSERT_EQUAL(SETTINGS_LOAD_INVALID, settings_decode_blob(&blob, &decoded));
}
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
UNITY_BEGIN();
RUN_TEST(test_defaults_are_safe_and_valid);
RUN_TEST(test_ids_must_be_24_bit_nonzero_and_unique);
RUN_TEST(test_generated_ids_are_unique_and_deterministic_for_seed);
RUN_TEST(test_blob_round_trip_and_crc);
RUN_TEST(test_incompatible_version_size_magic_are_rejected);
RUN_TEST(test_invalid_ranges_are_rejected_even_with_valid_crc);
return UNITY_END();
}
+118 -114
View File
@@ -1,144 +1,148 @@
/*
* test_tpms_frame.cpp - testy generatora ramek TPMS (natywne, bez sprzetu)
*
* Wektory odniesienia wygenerowane narzedziem tools/tpms_frame.py,
* ktore jest zgodne bit-w-bit z dekoderem rtl_433 (schrader_EG53MA4)
* oraz z referencyjnym nagraniem Schrader_EG53MA4_TPMS/01/gfile001.cu8.
*/
#include <string.h>
#include <unity.h>
#include "config.h"
#include "tpms_frame.h"
static uint8_t hexval(char c)
{
if (c >= '0' && c <= '9') return (uint8_t)(c - '0');
if (c >= 'a' && c <= 'f') return (uint8_t)(c - 'a' + 10);
return 0;
}
static void unhex(const char *hex, uint8_t *out)
{
for (unsigned i = 0; hex[2 * i]; i++) {
out[i] = (uint8_t)((hexval(hex[2 * i]) << 4) | hexval(hex[2 * i + 1]));
}
}
struct vec_t {
uint32_t id;
uint16_t kpa10;
int8_t temp_c;
const char *frame_hex; // 30 bajtow bufora nadawczego
};
void setUp(void) {}
void tearDown(void) {}
static void test_frame_vectors(void)
{
static const vec_t v[] = {
{ 0x2FC871u, 2600, 23, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4aab3554b2ad4acd32acb2cd2cc" },
{ 0x2FC871u, 0, 32, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4aab3554b2ad4acaaaacd32ab52" },
{ 0x3495ACu, 2200, -5, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4aab4cb2ccd334acd2aacd4b4aa" },
{ 0x000001u, 6375, 85, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4aaaaaaaaaaaaad5555352caacc" },
{ 0xABCDEEu, 2625, 24, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4ab33354b4d5352d32ccb34d2d2" },
{ 0x2FC780u, 2580, -40, "aaaaaaaaaaaaaaaaaaaacb4b2caaaaaad4aab3554ad52aaad2d4aaaab32c" },
};
struct capture_vector_t {
uint32_t id;
int16_t temp_c;
uint8_t temp_f;
uint8_t checksum;
};
for (unsigned i = 0; i < sizeof(v) / sizeof(v[0]); i++) {
uint8_t got[TPMS_TX_BYTES];
uint8_t want[TPMS_TX_BYTES];
tpms_build_frame(got, v[i].id, v[i].kpa10, v[i].temp_c, 0x4C900070u, false);
unhex(v[i].frame_hex, want);
TEST_ASSERT_EQUAL_HEX8_ARRAY(want, got, TPMS_TX_BYTES);
static void test_four_independent_capture_payloads(void)
{
/* rtl_433_tests commit 1aa8c29, four captures, 16 decodes each.
* All: flags=4c900070, pressure=0. The values do not come from a generator. */
static const capture_vector_t vectors[] = {
{0x2FC871u, 32, 90u, 0x0Eu},
{0x2EAAF9u, 32, 90u, 0x77u},
{0x3495ACu, 32, 90u, 0x1Bu},
{0x2FC780u, 33, 91u, 0x1Du},
};
for (uint8_t i = 0; i < 4u; ++i) {
uint8_t payload[TPMS_PAYLOAD_LEN];
TEST_ASSERT_TRUE(tpms_build_payload(payload, vectors[i].id, 0u,
(int8_t)vectors[i].temp_c, 0x4C900070u));
TEST_ASSERT_EQUAL_HEX32(vectors[i].id,
((uint32_t)payload[4] << 16) | ((uint32_t)payload[5] << 8) | payload[6]);
TEST_ASSERT_EQUAL_HEX8(0x00, payload[7]);
TEST_ASSERT_EQUAL_HEX8(vectors[i].temp_f, payload[8]);
TEST_ASSERT_EQUAL_HEX8(vectors[i].checksum, payload[9]);
}
}
static void test_reference_capture(void)
static void test_known_frame_and_pressure_temperature(void)
{
/* gfile001.cu8: id=2FC871, flags=4c900070, 0 kPa, 90 F, crc=0x0E */
uint8_t p[TPMS_PAYLOAD_LEN];
tpms_build_payload(p, 0x2FC871u, 0, 32, 0x4C900070u, false);
const uint8_t want[TPMS_PAYLOAD_LEN] = {
0x4C, 0x90, 0x00, 0x70, 0x2F, 0xC8, 0x71, 0x00, 0x5A, 0x0E
/* Vector regenerated after calibrating the P field against the car
* (260 kPa -> P=95); parallel to tools/tpms_frame.py. Manchester bit
* coding itself is unchanged. */
static const uint8_t expected[TPMS_TX_BYTES] = {
0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,
0xCB,0x4B,0x2C,0xAA,0xAA,0xAA,0xD4,0xAA,0xB3,0x55,
0x4B,0x2A,0xD4,0xAC,0xCD,0x54,0xCB,0x2C,0xCD,0x4A,
};
TEST_ASSERT_EQUAL_HEX8_ARRAY(want, p, TPMS_PAYLOAD_LEN);
uint8_t frame[TPMS_TX_BYTES];
uint8_t payload[TPMS_PAYLOAD_LEN];
TEST_ASSERT_TRUE(tpms_build_frame(frame, 0x2FC871u, 2600u, 23, 0x4C900070u));
TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, frame, TPMS_TX_BYTES);
TEST_ASSERT_TRUE(tpms_build_payload(payload, 0x123456u, 2600u, 23, 0x4C900070u));
TEST_ASSERT_EQUAL_HEX8(0x5F, payload[7]); /* 260 kPa -> 95 (2.73 kPa/bit) */
TEST_ASSERT_EQUAL_UINT8(73u, payload[8]);
TEST_ASSERT_EQUAL_HEX8(0x90, payload[9]);
}
static void test_pressure_scale(void)
static bool decode_strict(const uint8_t *frame, size_t length,
uint8_t payload[TPMS_PAYLOAD_LEN])
{
uint8_t p[TPMS_PAYLOAD_LEN];
/* 260 kPa = 2600 kPa*10 -> 2600/2.5 = 104 = 0x68 */
tpms_build_payload(p, 0x123456u, 2600, 23, 0x4C900070u, false);
TEST_ASSERT_EQUAL_HEX8(0x68, p[7]);
/* 23 C = 73 F */
TEST_ASSERT_EQUAL_HEX8(73, p[8]);
/* ograniczenie zakresu */
tpms_build_payload(p, 0x123456u, 65535, 127, 0x4C900070u, false);
TEST_ASSERT_EQUAL_HEX8(255, p[7]);
TEST_ASSERT_EQUAL_HEX8(255, p[8]);
tpms_build_payload(p, 0x123456u, 0, -99, 0x4C900070u, false);
TEST_ASSERT_EQUAL_HEX8(0, p[7]);
TEST_ASSERT_EQUAL_HEX8(0, p[8]);
}
static void test_pressure_rounding(void)
{
uint8_t p[TPMS_PAYLOAD_LEN];
/* skala 2.5 kPa/bit = 25 kPa*10/bit, zaokraglenie w gore do pol bitu:
* bajt = (kpa10 + 12) / 25 */
tpms_build_payload(p, 1, 12, 0, 0x4C900070u, false); // 1.2 kPa -> 0
TEST_ASSERT_EQUAL_HEX8(0, p[7]);
tpms_build_payload(p, 1, 13, 0, 0x4C900070u, false); // 1.3 kPa -> 1
TEST_ASSERT_EQUAL_HEX8(1, p[7]);
tpms_build_payload(p, 1, 2588, 0, 0x4C900070u, false); // 258.8 kPa -> 104
TEST_ASSERT_EQUAL_HEX8(104, p[7]);
tpms_build_payload(p, 1, 2587, 0, 0x4C900070u, false); // 258.7 kPa -> 103
TEST_ASSERT_EQUAL_HEX8(103, p[7]);
}
static void test_checksum(void)
{
uint8_t p[TPMS_PAYLOAD_LEN];
tpms_build_payload(p, 0x2FC871u, 2600, 23, 0x4C900070u, false);
unsigned sum = 0;
for (int i = 0; i < 9; i++) {
sum += p[i];
if (frame == NULL || length != TPMS_TX_BYTES || (frame[0] & 0x80u) == 0u) {
return false;
}
TEST_ASSERT_EQUAL_HEX8(sum & 0xFF, p[9]);
uint8_t row[15] = {0};
unsigned chip = 1u;
for (unsigned bit = 1u; bit < TPMS_ROW_BITS; ++bit) {
unsigned first = (frame[chip >> 3] >> (7u - (chip & 7u))) & 1u;
unsigned second = (frame[(chip + 1u) >> 3] >> (7u - ((chip + 1u) & 7u))) & 1u;
if (first == second) {
return false;
}
unsigned value = first != 0u ? 1u : 0u;
row[bit >> 3] |= (uint8_t)(value << (7u - (bit & 7u)));
chip += 2u;
}
if ((frame[29] & 1u) != 0u) {
return false;
}
memcpy(payload, &row[5], TPMS_PAYLOAD_LEN);
uint8_t sum = 0;
for (uint8_t i = 0; i < 9u; ++i) sum = (uint8_t)(sum + payload[i]);
return sum == payload[9];
}
static void test_low_batt_flag(void)
static void test_manchester_polarity_and_negative_frames(void)
{
uint8_t a[TPMS_PAYLOAD_LEN], b[TPMS_PAYLOAD_LEN];
tpms_build_payload(a, 0x2FC871u, 2600, 23, 0x4C900070u, false);
tpms_build_payload(b, 0x2FC871u, 2600, 23, 0x4C900070u, true);
TEST_ASSERT_EQUAL_HEX32(0x4C900070u,
((uint32_t)a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]);
TEST_ASSERT_TRUE((((uint32_t)b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3])
& TPMS_FLAGS_LOWBAT_MASK);
uint8_t frame[TPMS_TX_BYTES];
uint8_t payload[TPMS_PAYLOAD_LEN];
TEST_ASSERT_TRUE(tpms_build_frame(frame, 0x2FC871u, 2600u, 23, 0x4C900070u));
TEST_ASSERT_TRUE(decode_strict(frame, sizeof(frame), payload));
TEST_ASSERT_EQUAL_HEX32(0x2FC871u,
((uint32_t)payload[4] << 16) | ((uint32_t)payload[5] << 8) | payload[6]);
uint8_t damaged[TPMS_TX_BYTES];
memcpy(damaged, frame, sizeof(frame));
damaged[10] &= 0x3Fu; /* two identical chips: invalid Manchester */
TEST_ASSERT_FALSE(decode_strict(damaged, sizeof(damaged), payload));
TEST_ASSERT_FALSE(decode_strict(frame, sizeof(frame) - 1u, payload));
memcpy(damaged, frame, sizeof(frame));
/* Invert the whole Manchester cell (both chips) of the checksum bit:
* the frame remains a valid Manchester bitstream, but the sum stops
* matching, so rejection happens exactly at the checksum stage. */
damaged[28] ^= 0x60u;
TEST_ASSERT_FALSE(decode_strict(damaged, sizeof(damaged), payload));
}
static void test_frame_layout(void)
static void test_rounding_and_saturation(void)
{
uint8_t f[TPMS_TX_BYTES];
tpms_build_frame(f, 0x2FC871u, 2600, 23, 0x4C900070u, false);
/* pierwszy bit = chip rozbiegowy '1' -> najstarszy bit pierwszego bajtu */
TEST_ASSERT_EQUAL_HEX8(0xAA, f[0]);
/* dlugosc stale: 240 chipow = 30 bajtow */
TEST_ASSERT_EQUAL_UINT32(30, TPMS_TX_BYTES);
uint8_t p[TPMS_PAYLOAD_LEN];
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 12u, 0, 0u)); /* 1.2 kPa */
TEST_ASSERT_EQUAL_UINT8(0u, p[7]);
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 13u, 0, 0u)); /* threshold 13.7 */
TEST_ASSERT_EQUAL_UINT8(0u, p[7]);
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 14u, 0, 0u));
TEST_ASSERT_EQUAL_UINT8(1u, p[7]);
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 2608u, -40, 0u)); /* threshold 2607.2 */
TEST_ASSERT_EQUAL_UINT8(96u, p[7]);
TEST_ASSERT_EQUAL_UINT8(0u, p[8]);
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 2607u, 85, 0u));
TEST_ASSERT_EQUAL_UINT8(95u, p[7]);
TEST_ASSERT_EQUAL_UINT8(185u, p[8]);
TEST_ASSERT_TRUE(tpms_build_payload(p, 1u, 65535u, 127, 0u));
TEST_ASSERT_EQUAL_UINT8(255u, p[7]);
TEST_ASSERT_EQUAL_UINT8(255u, p[8]);
}
static void test_invalid_id_and_null_are_rejected(void)
{
uint8_t p[TPMS_PAYLOAD_LEN];
TEST_ASSERT_FALSE(tpms_build_payload(p, 0u, 2600u, 23, 0u));
TEST_ASSERT_FALSE(tpms_build_payload(p, 0xFFFFFFu, 2600u, 23, 0u));
TEST_ASSERT_FALSE(tpms_build_payload(p, 0x1000000u, 2600u, 23, 0u));
TEST_ASSERT_FALSE(tpms_build_payload(NULL, 1u, 2600u, 23, 0u));
TEST_ASSERT_FALSE(tpms_build_frame(NULL, 1u, 2600u, 23, 0u));
}
int main(int argc, char **argv)
{
(void)argc; (void)argv;
(void)argc;
(void)argv;
UNITY_BEGIN();
RUN_TEST(test_frame_vectors);
RUN_TEST(test_reference_capture);
RUN_TEST(test_pressure_scale);
RUN_TEST(test_pressure_rounding);
RUN_TEST(test_checksum);
RUN_TEST(test_low_batt_flag);
RUN_TEST(test_frame_layout);
RUN_TEST(test_four_independent_capture_payloads);
RUN_TEST(test_known_frame_and_pressure_temperature);
RUN_TEST(test_manchester_polarity_and_negative_frames);
RUN_TEST(test_rounding_and_saturation);
RUN_TEST(test_invalid_id_and_null_are_rejected);
return UNITY_END();
}
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# All tests possible without ESP32/CC1101/RTL-SDR/car.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
mkdir -p artifacts/validation
if [ -n "${PIO:-}" ]; then
PIO_BIN="$PIO"
elif [ -x "$ROOT/.venv/bin/pio" ]; then
PIO_BIN="$ROOT/.venv/bin/pio"
elif command -v pio >/dev/null 2>&1; then
PIO_BIN="$(command -v pio)"
else
python3 -m venv "$ROOT/.venv"
"$ROOT/.venv/bin/pip" install --disable-pip-version-check -r tools/requirements.txt
PIO_BIN="$ROOT/.venv/bin/pio"
fi
run() {
local name="$1"
shift
echo "== $name =="
"$@" 2>&1 | tee "artifacts/validation/$name.log"
}
run python-self-test python3 tools/tpms_frame.py --self-test
run native-tests "$PIO_BIN" test -e native
run esp32-build "$PIO_BIN" run -e esp32s2mini
run cppcheck "$PIO_BIN" check -e native \
--flags='--enable=warning,performance,portability --inline-suppr' \
--fail-on-defect=low
if [ ! -x "${RTL433:-$ROOT/.cache/rtl_433/build/src/rtl_433}" ] \
|| [ ! -f "${REFERENCE_DIR:-$ROOT/.cache/rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01}/gfile001.cu8" ]; then
run fetch-references bash ./tools/fetch_references.sh
fi
run rtl433 bash ./tools/verify_rtl433.sh
echo "PASS: all hardware-free tests completed successfully"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Fetches and builds the exactly pinned, independent RF references.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DEPS="${DEPS_DIR:-$ROOT/.cache}"
RTL_COMMIT=406f9a33550a2b6b3d0d8a8a486417ce5b3f13ab
TESTS_COMMIT=1aa8c29d6b9383739d1aeed495dbc5069b704392
mkdir -p "$DEPS"
if [ ! -d "$DEPS/rtl_433/.git" ]; then
git clone --filter=blob:none https://github.com/merbanan/rtl_433.git "$DEPS/rtl_433"
fi
git -C "$DEPS/rtl_433" checkout --detach "$RTL_COMMIT"
if [ ! -x "$DEPS/rtl_433/build/src/rtl_433" ]; then
cmake -S "$DEPS/rtl_433" -B "$DEPS/rtl_433/build" -DCMAKE_BUILD_TYPE=Release
cmake --build "$DEPS/rtl_433/build" -j2
fi
if [ ! -d "$DEPS/rtl_433_tests/.git" ]; then
git clone --filter=blob:none --sparse https://github.com/merbanan/rtl_433_tests.git "$DEPS/rtl_433_tests"
git -C "$DEPS/rtl_433_tests" sparse-checkout set tests/Schrader_EG53MA4_TPMS
fi
git -C "$DEPS/rtl_433_tests" checkout --detach "$TESTS_COMMIT"
printf 'RTL433=%s\nREFERENCE_DIR=%s\n' \
"$DEPS/rtl_433/build/src/rtl_433" \
"$DEPS/rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Flashes the full release image; PORT=e.g. /dev/ttyACM0. Erases the ESP32-S2 flash.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PORT="${PORT:?Set PORT=/dev/ttyACMX or /dev/ttyUSBX}"
ESPTOOL="${ESPTOOL:-${PLATFORMIO_CORE_DIR:-$HOME/.platformio}/packages/tool-esptool/esptool}"
IMAGE="$ROOT/artifacts/release/firmware-full.bin"
[ -f "$IMAGE" ] || { echo "Missing $IMAGE; run tools/package_release.sh"; exit 1; }
"$ESPTOOL" --chip esp32s2 --port "$PORT" --baud 460800 write-flash 0x0 "$IMAGE"
+42 -70
View File
@@ -1,25 +1,5 @@
#!/usr/bin/env python3
"""Synthesise a .cu8 IQ capture of the TPMS simulator's RF output.
The generated file is what an RTL-SDR would record while the ESP32+CC1101
simulator is transmitting. Feed it to rtl_433 to verify the frame format
without any hardware:
python3 tools/gen_cu8.py --id 2FC871 --pressure 260 --temp 23 -o /tmp/sim.cu8
rtl_433 -r /tmp/sim.cu8
expected:
model : Schrader-EG53MA4 id : 2FC871 pressure_kPa: 260.0 temperature_F: 73
Modulations:
ook ASK/OOK, Manchester data (default; matches the rtl_433 reference
capture and the built-in Schrader-EG53MA4 decoder)
fsk 2-FSK, +/-47.6 kHz deviation, same data (verify with
rtl_433 -X 'n=schrader,m=FSK_MC_ZEROBIT,s=120,l=120,r=300')
DISCLAIMER: diagnostic/test tool only, generates artificial pressure data.
"""
"""CU8 synthesis of OOK/Manchester for an independent rtl_433 test (no RF)."""
import argparse
import math
import os
@@ -27,73 +7,65 @@ import random
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from tpms_frame import build_row, build_tx_bits, CHIP_US # noqa: E402
from tpms_frame import build_row, build_tx_bits, CHIP_US
SAMPLE_RATE = 250000
def synth(bits: str, mode: str, deviation_hz: float, amp: float, noise: float,
rng: random.Random):
"""Yield (i, q) int8 pairs for one chip string."""
sps = SAMPLE_RATE * CHIP_US / 1e6 # samples per chip (~30)
total = int(round(len(bits) * sps))
def synth(bits: str, amp: float, noise: float, rng: random.Random):
samples_per_chip = SAMPLE_RATE * CHIP_US / 1e6
phase = 0.0
for n in range(total):
k = int(n / sps) % len(bits)
bit = bits[k]
if mode == "fsk":
freq = deviation_hz if bit == "1" else -deviation_hz
phase += 2 * math.pi * freq / SAMPLE_RATE
a = amp
else:
a = amp if bit == "1" else 0.0
i = a * math.cos(phase) + rng.gauss(0, noise)
q = a * math.sin(phase) + rng.gauss(0, noise)
yield i, q
for n in range(int(round(len(bits) * samples_per_chip))):
chip = bits[int(n / samples_per_chip) % len(bits)]
amplitude = amp if chip == "1" else 0.0
phase += 0.1 # any carrier inside the IQ band; the demodulator uses amplitude
yield (amplitude * math.cos(phase) + rng.gauss(0, noise),
amplitude * math.sin(phase) + rng.gauss(0, noise))
def write_cu8(path, samples):
with open(path, "wb") as f:
with open(path, "wb") as output:
for i, q in samples:
f.write(bytes((max(0, min(255, int(round(i + 127.5)))),
max(0, min(255, int(round(q + 127.5)))))))
output.write(bytes((max(0, min(255, int(round(i + 127.5)))),
max(0, min(255, int(round(q + 127.5)))))))
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--id", default="2FC871")
p.add_argument("--pressure", type=float, default=260.0)
p.add_argument("--temp", type=float, default=23.0)
p.add_argument("--flags", default="4C900070")
p.add_argument("--mode", choices=("ook", "fsk"), default="ook")
p.add_argument("--deviation", type=float, default=47.6, help="FSK deviation kHz")
p.add_argument("--frames", type=int, default=3)
p.add_argument("--gap-ms", type=float, default=50.0, help="gap between burst frames")
p.add_argument("--amp", type=float, default=60.0)
p.add_argument("--noise", type=float, default=2.0)
p.add_argument("-o", "--out", default="/tmp/opencode/tpms_ref/sim.cu8")
args = p.parse_args()
parser = argparse.ArgumentParser()
parser.add_argument("--id", default="2FC871")
parser.add_argument("--pressure", type=float, default=260.0)
parser.add_argument("--temp", type=float, default=23.0)
parser.add_argument("--flags", default="4C900070")
parser.add_argument("--frames", type=int, default=3)
parser.add_argument("--gap-ms", type=float, default=50.0)
parser.add_argument("--amp", type=float, default=60.0)
parser.add_argument("--noise", type=float, default=2.0)
parser.add_argument("--corrupt", choices=("checksum", "manchester", "truncate"))
parser.add_argument("-o", "--out", required=True)
args = parser.parse_args()
if not 1 <= args.frames <= 32 or not 20 <= args.gap_ms <= 500:
parser.error("frames=1..32, gap-ms=20..500")
row = build_row(int(args.id, 16), args.pressure, args.temp, int(args.flags, 16))
if args.corrupt == "checksum":
row = row[:-1] + ("0" if row[-1] == "1" else "1")
bits = build_tx_bits(row)
print(f"frame: {len(bits)} chips, tx bytes:"
f" {' '.join(f'{int(bits[i:i+8],2):02X}' for i in range(0, len(bits), 8))}")
out_dir = os.path.dirname(os.path.abspath(args.out))
if out_dir:
os.makedirs(out_dir, exist_ok=True)
if args.corrupt == "manchester":
bits = bits[:20] + "00" + bits[22:]
if args.corrupt == "truncate":
bits = bits[:-24]
os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
rng = random.Random(1)
gap_sps = int(SAMPLE_RATE * args.gap_ms / 1000)
out = []
for f in range(args.frames):
out.extend(synth(bits, args.mode, args.deviation * 1000, args.amp,
args.noise, rng))
out.extend((0.0, 0.0) for _ in range(gap_sps))
write_cu8(args.out, out)
print(f"wrote {args.out} ({len(out) / SAMPLE_RATE:.3f} s, {args.frames} frames)")
gap = [(0.0, 0.0)] * int(SAMPLE_RATE * args.gap_ms / 1000)
output = []
for _ in range(args.frames):
output.extend(synth(bits, args.amp, args.noise, rng))
output.extend(gap)
write_cu8(args.out, output)
print(f"{args.out}: {len(output) / SAMPLE_RATE:.3f} s, {args.frames} frames")
return 0
if __name__ == "__main__":
sys.exit(main())
raise SystemExit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Builds the ESP32-S2 images, the full 4 MB image and the SHA-256 manifest.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
PIO_BIN="${PIO:-$ROOT/.venv/bin/pio}"
if [ ! -x "$PIO_BIN" ]; then PIO_BIN="${PIO:-pio}"; fi
export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-1761600000}"
OUT="$ROOT/artifacts/release"
BUILD="$ROOT/.pio/build/esp32s2mini"
BOOT_APP0="${PLATFORMIO_CORE_DIR:-$HOME/.platformio}/packages/framework-arduinoespressif32/tools/partitions/boot_app0.bin"
ESPTOOL="${ESPTOOL:-${PLATFORMIO_CORE_DIR:-$HOME/.platformio}/packages/tool-esptool/esptool}"
"$PIO_BIN" run -e esp32s2mini
mkdir -p "$OUT"
cp "$BUILD/bootloader.bin" "$BUILD/partitions.bin" "$BUILD/firmware.bin" \
"$BUILD/firmware.elf" "$OUT/"
cp "$BOOT_APP0" "$OUT/boot_app0.bin"
"$ESPTOOL" --chip esp32s2 merge-bin -o "$OUT/firmware-full.bin" \
--flash-mode dio --flash-freq 80m --flash-size 4MB \
0x1000 "$OUT/bootloader.bin" 0x8000 "$OUT/partitions.bin" \
0xe000 "$OUT/boot_app0.bin" 0x10000 "$OUT/firmware.bin"
(
cd "$OUT"
sha256sum bootloader.bin partitions.bin boot_app0.bin firmware.bin \
firmware-full.bin firmware.elf > SHA256SUMS
)
cat > "$OUT/BUILD-INFO.txt" <<'EOF'
Version: 2.0.0-rc.1 (release candidate, no HIL)
PlatformIO: 6.1.18
Platform: espressif32 8.0.0, ESP32-S2-MINI ESP32-S2FN4R2 (lolin_s2_mini)
CC1101: de6757ef633b3e626dae5c7835cdb66ab53f9a1d
Addresses: 0x1000 bootloader, 0x8000 partitions, 0xe000 boot_app0, 0x10000 firmware
Flash: dio, 80 MHz, 4 MB (consistent with the lolin_s2_mini board manifest)
Full image firmware-full.bin: flash from 0x0.
EOF
cat "$OUT/BUILD-INFO.txt"
cat "$OUT/SHA256SUMS"
+22
View File
@@ -0,0 +1,22 @@
ajsonrpc==1.2.0
anyio==4.15.1
bottle==0.13.4
certifi==2026.10.23
charset-normalizer==3.5.2
click==8.1.7
colorama==0.4.6
h11==0.16.0
idna==3.20
marshmallow==3.26.2
packaging==26.3
platformio==6.1.18
pyelftools==0.33
pyserial==3.5
requests==2.34.2
semantic-version==2.10.0
starlette==0.46.2
tabulate==0.10.0
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.34.3
wsproto==1.3.2
+106 -198
View File
@@ -1,241 +1,149 @@
#!/usr/bin/env python3
"""Reference frame builder for the Schrader EG53MA4 TPMS simulator.
"""Independent EG53MA4 frame model and auxiliary tests (OOK/Manchester).
This tool mirrors bit-for-bit what the ESP32 firmware (src/tpms_frame.c)
puts on air, and contains a copy of rtl_433's OOK_MC_ZEROBIT slicer
(pulse_slicer_manchester_zerobit() from src/pulse_slicer.c) so the frame
can be self-checked without any radio hardware.
Protocol reference: rtl_433 src/devices/schraeder.c (schrader_EG53MA4),
"Schrader TPMS EG53MA4, Saab, Opel, Vauxhall, Chevrolet", and the reference
capture rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01/gfile001.cu8.
On-air frame (G.E.T. Manchester, chip = one half bit-cell):
lead chip '1' + 119 two-chip cells + zero padding to a byte boundary
cell "01" -> data bit 0, cell "10" -> data bit 1 (G.E.T. MC, no inversion)
The rtl_433 MC_ZEROBIT slicer synthesises the very first bit of the decoded
row (a hardcoded 0), so the transmitter sends the row *without* its first bit.
Decoded row (120 bits) = 40 bit sync (zeros) + 80 bit payload:
SSSS SSSS SSSS SSSS SSSS SSSS SSSS SSSS | FFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFF
IIII IIII IIII IIII IIII IIII | PPPP PPPP | TTTT TTTT | CCCC CCCC
- S: sync (40 bits, not checked by the decoder, kept as in real captures)
- F: flags (32 bit) - status / battery nibble, unanalysed upstream
- I: sensor id (24 bit)
- P: pressure, 25 mbar per bit (kPa = byte * 2.5)
- T: temperature, degrees Fahrenheit
- C: checksum = sum(bytes[0..8]) & 0xff
DISCLAIMER: this is a diagnostic/test tool. It generates *artificial* tyre
pressure data and is no replacement for real TPMS sensors.
References: rtl_433 commit 406f9a33550a2b6b3d0d8a8a486417ce5b3f13ab,
rtl_433_tests commit 1aa8c29d6b9383739d1aeed495dbc5069b704392.
The tool generates synthetic data for diagnostics only.
"""
import argparse
import math
import sys
# --- protocol constants (keep in sync with src/config.h / src/tpms_frame.c) ---
CHIP_US = 120.0 # one Manchester half bit-cell, 8.333 kBaud chip rate
FRAME_BITS = 120 # decoded row length expected by schrader_EG53MA4
CHIP_US = 120.0
FRAME_BITS = 120
SYNC_BITS = 40
TX_BYTES = 30 # 240 chips = 1 lead + 238 data + 1 pad
DEFAULT_FLAGS = 0x4C900070 # captured from real EG53MA4 sensors
TX_BYTES = 30
DEFAULT_FLAGS = 0x4C900070
# Calibration of the P field (see docs/AUDIT.md): how many hundredths of a kPa
# one bit of the P byte represents. The rtl_433 scale (250 = 2.5 kPa/bit) is not
# confirmed by the captures (all have P=0), while a car measurement showed
# 260 kPa -> 284 kPa on the display at P=104 => a scaling correction of
# 2.73 kPa/bit (P=95 for 260). Confirmed with the car: 260 kPa -> 260 kPa -
# also change TPMS_PRESSURE_KPA100_PER_RAW in src/tpms_frame.h.
PRESSURE_KPA100_PER_RAW = 273
def press_raw(pressure_kpa: float) -> int:
kpa10 = int(math.floor(pressure_kpa * 10.0 + 0.5))
if not 0 <= kpa10 <= 6375:
raise ValueError("pressure must be in the range 0..637.5 kPa")
return (kpa10 * 10 + PRESSURE_KPA100_PER_RAW // 2) // PRESSURE_KPA100_PER_RAW
def valid_id(sensor_id: int) -> bool:
return 0 < sensor_id < 0xFFFFFF
def cell(bit: int) -> str:
"""G.E.T. Manchester cell for one data bit."""
return "01" if bit == 0 else "10"
def build_row(sensor_id: int, pressure_kpa: float, temp_c: float,
flags: int = DEFAULT_FLAGS, low_batt: bool = False,
flags_lowbat_mask: int = 0x00000008) -> str:
"""Return the 120 decoded row bits as a string of '0'/'1'.
Uses the same half-up integer rounding as src/tpms_frame.cpp.
"""
flags: int = DEFAULT_FLAGS) -> str:
if not valid_id(sensor_id):
raise ValueError("ID must be in the range 000001..FFFFFE")
if not 0 <= flags <= 0xFFFFFFFF:
raise ValueError("flags must be 32-bit")
kpa10 = int(math.floor(pressure_kpa * 10.0 + 0.5))
press_byte = min(max((kpa10 + 12) // 25, 0), 255) # 2.5 kPa per bit
if not 0 <= kpa10 <= 6375:
raise ValueError("pressure must be in the range 0..637.5 kPa")
press_byte = press_raw(pressure_kpa)
tc = int(math.floor(temp_c + 0.5))
num = 9 * tc + 160 # temp_F = (9C+160)/5
if not -40 <= tc <= 85:
raise ValueError("temperature must be in the range -40..85 C")
num = 9 * tc + 160
temp_f = (num + 2) // 5 if num >= 0 else -((-num + 2) // 5)
temp_f = min(max(temp_f, 0), 255)
if low_batt:
flags |= flags_lowbat_mask
payload = [
(flags >> 24) & 0xFF,
(flags >> 16) & 0xFF,
(flags >> 8) & 0xFF,
flags & 0xFF,
(sensor_id >> 16) & 0xFF,
(sensor_id >> 8) & 0xFF,
sensor_id & 0xFF,
press_byte,
temp_f,
]
payload.append(sum(payload) & 0xFF)
row = "0" * SYNC_BITS
for b in payload:
row += f"{b:08b}"
assert len(row) == FRAME_BITS
return row
# Saturation consistent with tpms_frame.cpp: without it a temperature
# <= -19 C produces a negative byte and corrupts the frame (difference
# between the Python model and the firmware).
temp_f = max(0, min(255, temp_f))
payload = [flags >> 24, (flags >> 16) & 255, (flags >> 8) & 255,
flags & 255, sensor_id >> 16, (sensor_id >> 8) & 255,
sensor_id & 255, press_byte, temp_f]
payload.append(sum(payload) & 255)
return "0" * SYNC_BITS + "".join(f"{byte:08b}" for byte in payload)
def build_tx_bits(row: str) -> str:
"""Return the chip bit string actually shifted into the CC1101 FIFO.
240 chips: 1 lead chip + 119 two-chip cells + 1 pad chip = 30 bytes.
"""
assert len(row) == FRAME_BITS
bits = "1" # lead chip (carrier on)
for b in row[1:]: # row[0] is synthesised by the receiver
bits += cell(int(b))
while len(bits) % 8: # pad with 'off' chips (silence for OOK)
bits += "0"
return bits
if len(row) != FRAME_BITS:
raise ValueError("frame must have 120 bits")
bits = "1" + "".join(cell(int(bit)) for bit in row[1:])
return bits.ljust(TX_BYTES * 8, "0")
def tx_bytes(bits: str) -> bytes:
assert len(bits) % 8 == 0
if len(bits) != TX_BYTES * 8:
raise ValueError("TX buffer must have 30 bytes")
return bytes(int(bits[i:i + 8], 2) for i in range(0, len(bits), 8))
# ---------------------------------------------------------------------------
# Reference slicer: verbatim model of rtl_433 pulse_slicer_manchester_zerobit()
# (src/pulse_slicer.c), used for self-testing the encoder.
# ---------------------------------------------------------------------------
def mc_zerobit_slicer(chips, short_us=123.0, chip_us=CHIP_US, reset_us=300.0):
runs = [] # (level, length_us)
cur, cnt = chips[0], 1
for c in chips[1:]:
if c == cur:
cnt += 1
else:
runs.append((cur, cnt * chip_us))
cur, cnt = c, 1
runs.append((cur, cnt * chip_us))
pairs = [] # (pulse_us, gap_us)
i = 0
while i < len(runs):
lvl, ln = runs[i]
if lvl:
gap = runs[i + 1][1] if i + 1 < len(runs) and not runs[i + 1][0] else 0.0
pairs.append((ln, gap))
i += 2
else:
pairs.append((0.0, ln))
i += 1
row = ["0"] # hardcoded leading zero bit
t = 0.0
for n, (pulse, gap) in enumerate(pairs):
last = n == len(pairs) - 1
if pulse + t > short_us * 1.5:
row.append("1")
t = 0.0
else:
t += pulse
if last:
break
if gap > reset_us:
break # end of message
if gap + t > short_us * 1.5:
row.append("0")
t = 0.0
else:
t += gap
return "".join(row)
def decode_row(row: str):
if len(row) != FRAME_BITS:
return None
by = [int(row[SYNC_BITS + 8 * k:SYNC_BITS + 8 * (k + 1)], 2) for k in range(10)]
return {
"flags": by[0] << 24 | by[1] << 16 | by[2] << 8 | by[3],
"id": by[4] << 16 | by[5] << 8 | by[6],
"pressure_kPa": by[7] * 2.5,
"temperature_F": by[8],
"checksum_ok": (sum(by[:9]) & 0xFF) == by[9],
"bytes": by,
}
data = [int(row[SYNC_BITS + 8 * i:SYNC_BITS + 8 * (i + 1)], 2)
for i in range(10)]
return {"flags": int.from_bytes(bytes(data[:4]), "big"),
"id": int.from_bytes(bytes(data[4:7]), "big"),
# 2.5 kPa/bit is the rtl_433 decoder scale (unconfirmed); the
# firmware corrects it with the PRESSURE_KPA100_PER_RAW constant,
# so the value below != the pressure set in the console.
"pressure_kPa": data[7] * 2.5, "temperature_F": data[8],
"checksum_ok": sum(data[:9]) & 255 == data[9], "bytes": data}
def self_test() -> int:
"""Cross-check against the rtl_433 reference capture (gfile001.cu8)."""
fails = 0
ref = build_row(0x2FC871, 0.0, (90 - 32) * 5 / 9, flags=0x4C900070)
# the capture carries temperature as the raw byte 90 (0x5A) = 90 F
ref_row = ("0" * 40
+ "01001100100100000000000001110000001011111100100001110001000000000101101000001110")
if ref_row[40:] != ref[40:]:
print("FAIL: reference capture row mismatch")
print(" want:", ref_row)
print(" got :", ref)
fails += 1
# random round trip: encode -> slicer -> data must survive intact
expected = [0x4C, 0x90, 0, 0x70, 0x2F, 0xC8, 0x71, 0, 0x5A, 0x0E]
row = build_row(0x2FC871, 0, 32)
got = decode_row(row)["bytes"]
if got != expected:
print(f"FAIL: capture gfile001: {got} != {expected}")
return 1
# Regression: temperature saturation consistent with the firmware
# (range -40..85 C).
for tc, want in ((-40, 0), (-19, 0), (-18, 0), (23, 73), (85, 185)):
byte = decode_row(build_row(0x2FC871, 0, tc))["bytes"][8]
if byte != want:
print(f"FAIL: temperature {tc} C: {byte} != {want}")
return 1
# Regression of the P field calibration (car measurement point: 260 kPa -> P=95).
for kpa, want in ((0, 0), (1.2, 0), (1.4, 1), (260.0, 95), (637.5, 234)):
byte = press_raw(kpa)
if byte != want:
print(f"FAIL: pressure {kpa} kPa: {byte} != {want}")
return 1
import random
random.seed(42)
rng = random.Random(42)
for _ in range(500):
sid = random.randrange(0, 0x1000000)
kpa = round(random.uniform(0, 637.5), 1)
tc = random.uniform(-40, 85)
row = build_row(sid, kpa, tc)
bits = build_tx_bits(row)
chips = [int(b) for b in bits]
out = mc_zerobit_slicer(chips)
if len(out) != FRAME_BITS or out[SYNC_BITS:] != row[SYNC_BITS:]:
print("FAIL: round trip", hex(sid), kpa, tc)
print(" row:", row)
print(" out:", out)
fails += 1
break
d = decode_row(out)
if not d["checksum_ok"] or d["id"] != sid:
print("FAIL: decode", hex(sid), d)
fails += 1
break
print("self-test:", "OK" if fails == 0 else "FAILED")
return 1 if fails else 0
sensor_id = rng.randrange(1, 0xFFFFFF)
pressure = round(rng.uniform(0, 637.5), 1)
temp = rng.randrange(-40, 86)
decoded = decode_row(build_row(sensor_id, pressure, temp))
if not decoded["checksum_ok"] or decoded["id"] != sensor_id:
print("FAIL: round trip")
return 1
print("self-test: OK (capture + 500 frames)")
return 0
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--id", default="2FC871", help="sensor id (hex, 24 bit)")
p.add_argument("--pressure", type=float, default=260.0, help="kPa")
p.add_argument("--temp", type=float, default=23.0, help="deg C")
p.add_argument("--flags", default="4C900070", help="flags word (hex)")
p.add_argument("--low-batt", action="store_true")
p.add_argument("--self-test", action="store_true")
args = p.parse_args()
parser = argparse.ArgumentParser()
parser.add_argument("--id", default="2FC871")
parser.add_argument("--pressure", type=float, default=260.0)
parser.add_argument("--temp", type=float, default=23.0)
parser.add_argument("--flags", default="4C900070")
parser.add_argument("--self-test", action="store_true")
args = parser.parse_args()
if args.self_test:
return self_test()
sid = int(args.id, 16)
flags = int(args.flags, 16)
row = build_row(sid, args.pressure, args.temp, flags, args.low_batt)
bits = build_tx_bits(row)
raw = tx_bytes(bits)
d = decode_row(row)
print(f"row (120 bit): {row}")
print(f"chips({len(bits):3d} bit): {bits}")
print(f"tx bytes ({len(raw)}): {' '.join(f'{b:02X}' for b in raw)}")
print(f"payload : {' '.join(f'{b:02X}' for b in d['bytes'])}")
print(f"checksum: {'OK' if d['checksum_ok'] else 'BAD'}")
print(f"id={d['id']:06X} pressure={d['pressure_kPa']:.1f} kPa "
f"temperature={d['temperature_F']} F ({args.temp:.0f} C) flags={d['flags']:08X}")
out = mc_zerobit_slicer([int(b) for b in bits])
print(f"slicer check: {'OK' if out[SYNC_BITS:] == row[SYNC_BITS:] and len(out) == FRAME_BITS else 'FAILED'}")
row = build_row(int(args.id, 16), args.pressure, args.temp, int(args.flags, 16))
raw = tx_bytes(build_tx_bits(row))
decoded = decode_row(row)
print(f"row: {row}\ntx: {raw.hex()}")
print("payload: " + " ".join(f"{byte:02X}" for byte in decoded["bytes"]))
print(f"id={decoded['id']:06X} pressure={decoded['pressure_kPa']:.1f} kPa "
f"temp={decoded['temperature_F']} F flags={decoded['flags']:08X}")
return 0
if __name__ == "__main__":
sys.exit(main())
raise SystemExit(main())
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Validation of real and synthetic CU8 with the pinned rtl_433."""
import argparse
import json
import pathlib
import subprocess
import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from tpms_frame import press_raw
EXPECTED = {
"gfile001.cu8": ("2FC871", 90.0),
"gfile002.cu8": ("2EAAF9", 90.0),
"gfile003.cu8": ("3495AC", 90.0),
"gfile004.cu8": ("2FC780", 91.0),
}
def decode(rtl433: str, capture: pathlib.Path):
result = subprocess.run([rtl433, "-q", "-F", "json", "-r", str(capture)],
text=True, capture_output=True, check=False)
records = []
for line in result.stdout.splitlines():
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if record.get("model") == "Schrader-EG53MA4":
records.append(record)
return result.returncode, records, result.stdout + result.stderr
def require(condition, message, failures):
if not condition:
failures.append(message)
return condition
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--rtl433", required=True)
parser.add_argument("--reference-dir", required=True, type=pathlib.Path)
args = parser.parse_args()
root = pathlib.Path(__file__).resolve().parent.parent
failures = []
print("rtl_433 commit: 406f9a33550a2b6b3d0d8a8a486417ce5b3f13ab")
print("rtl_433_tests commit: 1aa8c29d6b9383739d1aeed495dbc5069b704392")
for filename, (sensor_id, temp_f) in EXPECTED.items():
capture = args.reference_dir / filename
if not require(capture.is_file(), f"missing {capture}", failures):
continue
status, records, raw = decode(args.rtl433, capture)
valid = status == 0 and len(records) == 16 and all(
record.get("id") == sensor_id and record.get("flags") == "4c900070"
and record.get("pressure_kPa") == 0.0
and record.get("temperature_F") == temp_f
and record.get("mic") == "CHECKSUM" for record in records)
require(valid, f"{filename}: mismatched records\n{raw}", failures)
print(f"{'OK' if valid else 'FAIL'} reference {filename}: "
f"{len(records)}/16, id={sensor_id}, flags=4c900070")
# rtl_433 computes the P field on a 2.5 kPa/bit scale (unconfirmed); the
# firmware corrects it with the PRESSURE_KPA100_PER_RAW constant, so the
# expected rtl_433 value is the raw P byte * 2.5, not the requested kPa.
synthetic = [("2FC871", 260, 23, 73.0), ("3495AC", 220, -5, 23.0),
("ABCDEE", 262.5, 24, 75.0)]
with tempfile.TemporaryDirectory(prefix="tpms-rtl433-") as temp:
for index, (sensor_id, pressure, temp_c, temp_f) in enumerate(synthetic):
capture = pathlib.Path(temp) / f"valid{index}.cu8"
subprocess.run([sys.executable, str(root / "tools/gen_cu8.py"),
"--id", sensor_id, "--pressure", str(pressure),
"--temp", str(temp_c), "-o", str(capture)],
check=True, capture_output=True)
status, records, raw = decode(args.rtl433, capture)
expect_kpa = press_raw(pressure) * 2.5
valid = status == 0 and len(records) >= 1 and all(
record.get("id") == sensor_id
and record.get("pressure_kPa") == expect_kpa
and record.get("temperature_F") == temp_f
and record.get("flags") == "4c900070"
and record.get("mic") == "CHECKSUM" for record in records)
require(valid, f"synthetic {sensor_id}: {raw}", failures)
print(f"{'OK' if valid else 'FAIL'} synthetic id={sensor_id}: "
f"{len(records)} dekodowan, P={press_raw(pressure)} "
f"(rtl_433: {expect_kpa:.1f} kPa z {pressure:.1f} kPa), "
f"{temp_f:.1f} F")
for corruption in ("checksum", "manchester", "truncate"):
capture = pathlib.Path(temp) / f"bad-{corruption}.cu8"
subprocess.run([sys.executable, str(root / "tools/gen_cu8.py"),
"--corrupt", corruption, "-o", str(capture)],
check=True, capture_output=True)
status, records, raw = decode(args.rtl433, capture)
valid = status == 0 and not records
require(valid, f"negative {corruption}: decoded incorrectly\n{raw}", failures)
print(f"{'OK' if valid else 'FAIL'} negative {corruption}: "
f"{len(records)} dekodowan (oczekiwano 0)")
print(f"RESULT: {'PASS' if not failures else 'FAIL'}; errors={len(failures)}")
for failure in failures:
print(" - " + failure)
return 1 if failures else 0
if __name__ == "__main__":
raise SystemExit(main())
+9 -90
View File
@@ -1,91 +1,10 @@
#!/usr/bin/env bash
# verify_rtl433.sh - automatyczna weryfikacja ramek symulatora TPMS
# Schrader EG53MA4 za pomoca prawdziwego dekodera rtl_433 (bez sprzetu RF).
#
# Wymaga: python3, rtl_433 (binarka w PATH albo w zmiennej RTL433)
#
# Uzycie:
# RTL433=/sciezka/do/rtl_433 ./tools/verify_rtl433.sh
#
# Skrypt:
# 1) generuje syntezyczne nagrania IQ (.cu8) takie, jakie odbierze RTL-SDR
# podczas nadawania symulatora,
# 2) dekoduje je rtl_433 i porownuje wynik z zadanymi wartosciami:
# - OOK: wbudowany dekoder Schrader-EG53MA4 (model/id/pressure/temp)
# - FSK: dekoder flex, porownanie calego bitstreamu z ramka wzorcowa
#
# Uwaga: nazwy plikow nie moga zawierac tokenow "ook"/"fsk"/"am"/"fm" -
# parser formatow rtl_433 traktuje je jako opis formatu pliku.
set -u
RTL433="${RTL433:-rtl_433}"
DIR="$(cd "$(dirname "$0")/.." && pwd)"
TMP="${TMPDIR:-/tmp}/tpms_verify_$$"
mkdir -p "$TMP"
if ! command -v "$RTL433" >/dev/null 2>&1; then
echo "BLAD: nie znaleziono rtl_433 (ustaw zmienna RTL433=...)"; exit 1
fi
fail=0
check_ook() { # $1=plik $2=id $3=kPa $4=temp_F
local file="$1" id="$2" kpa="$3" tf="$4"
local out
out="$("$RTL433" -r "$file" 2>/dev/null)"
if echo "$out" | grep -qi "Schrader-EG53MA4" \
&& echo "$out" | grep -q "ID : $id" \
&& echo "$out" | grep -q "Pressure : $kpa kPa" \
&& echo "$out" | grep -q "Temperature: $tf"; then
echo "OK $(basename "$file") id=$id $kpa kPa $tf F"
else
echo "FAIL $(basename "$file") (oczekiwano id=$id $kpa kPa $tf F)"
echo "$out" | sed 's/^/ /'
fail=1
fi
}
check_fsk() { # $1=plik $2=id $3=kPa $4=temp_C
local file="$1" id="$2" kpa="$3" tc="$4"
local out codes want
out="$("$RTL433" -r "$file" \
-X 'n=schrader,m=FSK_MC_ZEROBIT,s=120,l=120,r=300' 2>/dev/null)"
codes="$(echo "$out" | grep -o 'codes : {120}[0-9a-f]*' | head -1 | sed 's/.*{120}//')"
want="0000000000$(python3 "$DIR/tools/tpms_frame.py" --id "$id" \
--pressure "$kpa" --temp "$tc" | grep payload | sed 's/.*payload : //' \
| tr 'A-Z' 'a-z' | tr -d ' ')"
if [ -n "$codes" ] && [ "$codes" = "$want" ]; then
echo "OK $(basename "$file") (FSK) bitstream zgodny: $codes"
else
echo "FAIL $(basename "$file") (FSK)"
echo " otrzymano: ${codes:-<brak>}"
echo " oczekiwano: $want"
fail=1
fi
}
echo "== OOK (domyslna modulacja, wbudowany dekoder Schrader-EG53MA4) =="
python3 "$DIR/tools/gen_cu8.py" --id 2FC871 --pressure 260 --temp 23 \
-o "$TMP/c1.cu8" >/dev/null
check_ook "$TMP/c1.cu8" 2FC871 260.0 73.0
python3 "$DIR/tools/gen_cu8.py" --id 3495AC --pressure 220 --temp -5 \
-o "$TMP/c2.cu8" >/dev/null
check_ook "$TMP/c2.cu8" 3495AC 220.0 23.0
python3 "$DIR/tools/gen_cu8.py" --id ABCDEE --pressure 262.5 --temp 24 \
-o "$TMP/c3.cu8" >/dev/null
check_ook "$TMP/c3.cu8" ABCDEE 262.5 75.0
echo "== FSK (wariant konfigurowalny, dekoder flex) =="
python3 "$DIR/tools/gen_cu8.py" --id 2FC871 --pressure 260 --temp 23 \
--mode fsk -o "$TMP/c4.cu8" >/dev/null
check_fsk "$TMP/c4.cu8" 2FC871 260 23
rm -rf "$TMP"
if [ "$fail" -eq 0 ]; then
echo "WSZYSTKO OK - ramki dekoduja sie poprawnie przez rtl_433"
else
echo "WERYFIKACJA NIEUDANA"
fi
exit "$fail"
# Returns a non-zero code on error and writes a readable report.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
RTL433="${RTL433:-$ROOT/.cache/rtl_433/build/src/rtl_433}"
REFERENCE_DIR="${REFERENCE_DIR:-$ROOT/.cache/rtl_433_tests/tests/Schrader_EG53MA4_TPMS/01}"
REPORT_DIR="${REPORT_DIR:-$ROOT/artifacts/validation}"
mkdir -p "$REPORT_DIR"
python3 "$ROOT/tools/verify_rtl433.py" --rtl433 "$RTL433" \
--reference-dir "$REFERENCE_DIR" | tee "$REPORT_DIR/rtl433-report.txt"