Build the two sketches with PlatformIO, add offline checks and rewrite the README

Sumbrella had no build definition: it was two .ino files to open in the Arduino
IDE. This adds one PlatformIO project per sketch (PlatformIO only converts a
*.ino sitting at the top of its own src_dir) and there is now a real, repeated
compile for the boards the project actually used:

  Projeto.ino       -> Arduino Nano        206 B RAM, 3508 B flash of 30720
  Fetch_rain.ino    -> ESP8266 ESP-01     28972 B RAM, 280119 B of 434160 flash

The boards come from the course poster kept in the repository (Sumbrella.pdf,
"Listagem de material": Arduino Nano and ESP8226 ESP-01), not from the code:
neither sketch names its board. The ESP-01 flash size is not given anywhere, so
the 512 KB variant is targeted.

Dependencies are now reproducible. LiquidCrystal_I2C comes from the PlatformIO
registry by name and version. DS3231 1.01 cannot: all 87 registry hits were
checked and none exposes class Time / getTimeStr() / DS3231(data, sclk), so it is
pinned to tag v1.01 of a mirror whose files were verified byte-for-byte equal to
the libs/DS3231 removed in 009066d. A clean clone compiles as it is.

The unused LCD stays unused and no sensor is invented: the only thing this commit
does to the sketches is compile them.

tests/ holds the checks that need no board, each with a negative selftest that
proves the check bites: secrets hygiene (secrets.h not tracked and ignored, the
example complete and placeholder-only, no credential literal in any tracked file)
and pin validity against the Nano and ESP-01 pin maps. run.sh builds both targets
and then runs them, exiting non-zero on any failure. .gitignore now covers the
PlatformIO artefacts (.pio/, *.bin, *.elf and friends).

README.md is rewritten in the common format, with the real build and test output.
Two things it no longer says, because they are not true of this repository: no
revision reachable from main ever contained a credential literal (the deleted
ESP8266_Fetching_Data.ino carried the string "<REDACTED>"), and the DS3231
dependency is not installable from the PlatformIO registry.

Known, left unfixed on purpose: the LCD is constructed and never written to; the
rain values are printed and discarded; loop() calls setup() on failure; and
libs/DS3231 is still reachable in the history before 009066d.
This commit is contained in:
Andre Neto
2026-10-08 16:11:49 +01:00
parent 009066d182
commit 5d4b62c40b
9 changed files with 733 additions and 22 deletions
+25 -1
View File
@@ -1,2 +1,26 @@
# Local WiFi credentials (see Fetch_rain/secrets.h.example)
# Local WiFi credentials and ThingHTTP API keys (see Fetch_rain/secrets.h.example)
secrets.h
# PlatformIO build output and installed dependencies
.pio/
.pioenvs/
.piolibdeps/
# Compiler and linker artefacts
*.bin
*.elf
*.hex
*.map
*.lst
*.o
*.d
*.a
*.ino.cpp
# Editors / OS
.vscode/
.idea/
*.swp
.DS_Store
Thumbs.db
desktop.ini
+21
View File
@@ -20,3 +20,24 @@ foi retirada do repositório e tem de ser instalada à parte:
A remoção foi feita **no repositório** (índice e histórico a partir daqui); não
apaga nenhuma cópia da biblioteca que exista fora do Git, no disco do autor.
## Como a dependência é declarada agora
`lib_deps` em `platformio.ini` (projecto do `Projeto.ino`):
```ini
lib_deps =
https://github.com/whonore/DS3231.git#v1.01
```
A biblioteca **não está no registry oficial do PlatformIO**: foram verificados
os 87 resultados da pesquisa por `DS3231` e nenhum expõe a API que `Projeto.ino`
usa (`class Time` com o campo `hour`, `char *getTimeStr()`, e o construtor
`DS3231(data_pin, sclk_pin)`). Por isso fica fixa à tag `v1.01` de um espelho,
cujos ficheiros foram comparados byte a byte com o `libs/DS3231` que saiu deste
repositório: `DS3231.h`, `DS3231.cpp`, `hardware/avr/HW_AVR.h`,
`hardware/avr/HW_AVR_defines.h`, `keywords.txt` e `Documentation/version.txt`
têm o mesmo SHA-256, e `version.txt` diz 1.01 (25 de Agosto de 2014).
O espelho é uma cópia da biblioteca original, redistribuída sob a mesma licença
CC BY-NC-SA 3.0; continua a não ser este repositório a redistribuí-la.
+22
View File
@@ -0,0 +1,22 @@
; PlatformIO project for Fetch_rain.ino (ESP8266).
; Build it from the repository root with: pio run -d Fetch_rain
;
; The board is named on the course poster kept in this repository,
; Sumbrella.pdf: "ESP8226 ESP-01" (sic) — an ESP-01, whose flash size the poster
; does not give. esp01 targets the 512 KB module, which is the variant the
; firmware fits either way; use board = esp01_1m for a 1 MB ESP-01.
;
; Fetch_rain.ino does not compile without secrets.h, which is not versioned:
; cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
[platformio]
src_dir = .
[env:esp8266]
platform = espressif8266
board = esp01
framework = arduino
monitor_speed = 115200
upload_speed = 115200
lib_deps =
marcoschwartz/LiquidCrystal_I2C@1.1.4
+187 -21
View File
@@ -1,34 +1,200 @@
https://youtu.be/7n7HcTeeHdM
# sumbrella
## Configuration
Two Arduino sketches for a smart umbrella: an ESP8266 ESP-01 sketch that fetches the rain probability for today, tomorrow and the day after from ThingSpeak over WiFi, and an Arduino Nano sketch that drives a red/green LED from a DS3231 real-time clock.
The WiFi credentials are **not** stored in the repository. The sketch
`Fetch_rain/Fetch_rain.ino` includes a non-versioned header `secrets.h`
that defines `WIFI_SSID` and `WIFI_PASSWORD`:
## What it is
Two independent sketches, in two PlatformIO projects. Neither sketch names its own board in its source; the board is named on the course poster kept in this repository, `Sumbrella.pdf` ("Listagem de material"): *Arduino Nano* and *ESP8226 ESP-01*.
`Fetch_rain/Fetch_rain.ino` (176 lines, ESP8266 ESP-01)
| Lines | What |
|---|---|
| 1-3 | `ESP8266WiFi.h`, `Wire.h`, `LiquidCrystal_I2C.h` |
| 5 | `#include "secrets.h"` — not versioned, see *Requirements* |
| 7 | `LiquidCrystal_I2C lcd(0x27, 16, 2);` |
| 10-11 | `ssid` and `password`, taken from `secrets.h` |
| 13 | `host = "api.thingspeak.com"` |
| 15-37 | `setup()`: serial at 115200 baud, joins the WiFi network and blocks until connected |
| 40-73 | `loop()`: calls `today()`, `tmrw()`, `aftmrw()` in turn and prints each result |
| 91-119, 121-148, 150-176 | one helper per day, identical apart from the ThingHTTP key |
Each helper opens a TCP connection to `api.thingspeak.com:80`, sends `GET /apps/thinghttp/send_request?api_key=<key>` (lines 103, 132, 160), skips 18 lines of response headers, reads the body up to the first `%` and returns it as an `int` (lines 116-118). On a failed connection it returns `-1`, and `loop()` then prints `Something went wrong, resetting...` and calls `setup()` again from inside `loop()` (lines 49, 59, 69). The rain percentages go to the serial port; that is the whole user interface.
`Projeto.ino` (31 lines, Arduino Nano)
- Lines 1-3: `#include <DS3231.h>` and `DS3231 rtc(SDA, SCL)` — SDA/SCL are A4/A5, i.e. pins 18 and 19.
- Lines 6-12 `setup()`: serial at 9600 baud, `rtc.begin()`, pins 5 and 6 as `OUTPUT`.
- Lines 14-26 `loop()`: prints `rtc.getTimeStr()`, takes `hour` out of the `Time` struct returned by `rtc.getTime()`, and calls `rgLed(150, 150)` while `7 < hour < 14` (08:00-13:59), otherwise `rgLed(0, 0)`; one second per iteration.
- Lines 28-31 `rgLed()`: `analogWrite` on pins 5 and 6. Which of the two is the red LED and which is the green one is not stated anywhere in the code or the poster.
Things that are dead or missing — recorded here, deliberately not changed:
- The LCD is never used. `lcd` is constructed on line 7 of `Fetch_rain.ino` and there is not a single `lcd.` call in either sketch. It costs one library dependency and nothing else.
- There is no rain sensor. Every rain value comes from the ThingSpeak HTTP responses; neither sketch reads an analogue or digital sensor.
- Lines 75-90 of `Fetch_rain.ino` are blank.
- The values returned by `today()`, `tmrw()` and `aftmrw()` are printed and discarded; nothing drives the LED from the rain probability, and `Projeto.ino` never reads the network.
## Requirements
- [PlatformIO Core](https://docs.platformio.org/) 6.2.0, on Python 3.13 (tested in a virtualenv; nothing was installed system-wide).
- Internet access on the first build: PlatformIO downloads the `espressif8266` and `atmelavr` platforms, their toolchains, and the two libraries below (about 200 MB).
- No board is needed to build or to run the tests. Flashing needs the Nano on a USB port and the ESP-01 on a 3.3 V serial adapter; nothing here was run on hardware.
- Two external libraries, both declared in `lib_deps`:
- `marcoschwartz/LiquidCrystal_I2C@1.1.4` — for the unused LCD, from the PlatformIO registry.
- DS3231 1.01 (Rinky-Dink Electronics, Henning Karlsen) — for `Projeto.ino`. **It is not in the PlatformIO registry**: all 87 registry search hits for "DS3231" were checked and none exposes the `class Time` / `getTimeStr()` / `DS3231(data_pin, sclk_pin)` API this sketch uses. It is therefore pinned in `lib_deps` to the tag `v1.01` of a mirror whose files were verified byte-for-byte identical to the `libs/DS3231` that was removed from this repository. It is CC BY-NC-SA 3.0 and is not redistributed here — see [DEPENDENCIAS.md](DEPENDENCIAS.md).
`Fetch_rain.ino` does not compile without `Fetch_rain/secrets.h`, which is not versioned. Copy the example and fill in your own values:
```bash
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
# edit Fetch_rain/secrets.h with your own network name and password
# then edit Fetch_rain/secrets.h: WIFI_SSID, WIFI_PASSWORD and the three
# THINGHTTP_KEY_* values
```
`secrets.h` is listed in `.gitignore`, so it is never committed. The
sketch does not compile without it. If the old password was ever
pushed, change it on the router as well as in `secrets.h`.
## Install / Build
`secrets.h` also defines the three ThingHTTP API keys used by the daily
scheduled channels (`THINGHTTP_KEY_TODAY`, `THINGHTTP_KEY_TMRW`,
`THINGHTTP_KEY_AFTMRW`). They used to be hard-coded in the sketch; the old
values were committed, so they must be regenerated in ThingHTTP.
There is one PlatformIO project per sketch, because PlatformIO only converts a `*.ino` file that sits at the top of its own `src_dir`.
## Dependencies
```bash
# canonical copy on the self-hosted Gitea (aneto/sumbrella), mirrored to GitHub:
git clone ssh://git@127.0.0.1:2222/aneto/sumbrella.git
cd sumbrella
`Projeto.ino` needs the third-party DS3231 RTC library — Rinky-Dink Electronics,
Henning Karlsen, version 1.01 (25 Aug 2014), http://www.RinkyDinkElectronics.com/.
It is **not** vendored here: it is CC BY-NC-SA 3.0 (non-commercial), which cannot
be mixed with this repository's MIT licence. Install it separately — see
[DEPENDENCIAS.md](DEPENDENCIAS.md).
python3 -m venv ~/.venvs/platformio
~/.venvs/platformio/bin/pip install platformio
export PATH="$HOME/.venvs/platformio/bin:$PATH"
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h # or ./run.sh does it
pio run # Projeto.ino -> Arduino Nano
pio run -d Fetch_rain # Fetch_rain.ino -> ESP8266 ESP-01
./run.sh # both, then the offline test suite
```
## Usage
Upload with `pio run -t upload` (`pio run -d Fetch_rain -t upload` for the ESP-01; it needs `board = esp01_1m` if the module has 1 MB of flash instead of 512 KB). Then read the serial port at the baud rate in `platformio.ini`: 115200 for the ESP-01, 9600 for the Nano (`pio device monitor`).
No board was attached to the machine this was built on, so this is not a captured session — it is the exact shape of the output, taken from the `Serial.print` calls:
```text
Connecting to <ssid>
.....
WiFi connected
IP address:
192.168.1.23
Today: 20
Tomorrow: 45
After tomorrow: 10
```
with `Something went wrong, resetting...` replacing a value when the connection to `api.thingspeak.com` fails, after which `setup()` runs again. `Projeto.ino` prints one line per second, `HH:MM:SS`, and lights the two LEDs on pins 5 and 6 while the hour is 8 to 13.
## Tests
```bash
./run.sh # equivalent to: pio run && pio run -d Fetch_rain && bash tests/run_tests.sh
```
Everything below runs without hardware and fails the shell (`exit != 0`) on the first real problem. Output of a run on the machine this was written on:
```text
== pio check, ESP8266 ESP-01
Component HIGH MEDIUM LOW
Fetch_rain.ino 0 0 7
Total 0 4 33
esp8266 cppcheck PASSED 00:00:00.112
== pio check, Arduino Nano
Component HIGH MEDIUM LOW
Fetch_rain 0 0 7
Fetch_rain/.pio/libdeps/esp8266/LiquidCrystal_I2C 0 4 26
Projeto.ino 0 0 2
Total 0 5 61
nano cppcheck PASSED 00:00:00.467
== compile ESP8266 ESP-01 (Fetch_rain.ino)
RAM: [==== ] 35.4% (used 28972 bytes from 81920 bytes)
Flash: [====== ] 64.5% (used 280119 bytes from 434160 bytes)
artefact: Fetch_rain/.pio/build/esp8266/firmware.bin (284272 bytes)
-> PASS
== compile Arduino Nano (Projeto.ino)
RAM: [= ] 10.1% (used 206 bytes from 2048 bytes)
Flash: [= ] 11.4% (used 3508 bytes from 30720 bytes)
artefact: .pio/build/nano/firmware.hex (9889 bytes)
-> PASS
== secrets hygiene
PASS secrets.h untracked and ignored; secrets.h.example defines every symbol the sketch uses and holds no real value; no tracked file holds a literal credential
-> PASS
== secrets negative tests
PASS negative case detected: secrets.h.example loses one symbol
PASS negative case detected: .gitignore loses the secrets.h rule
PASS negative case detected: a tracked file gains a literal api_key
PASS negative case detected: secrets.h.example is deleted
PASS control copy is clean
SELFTEST OK
-> PASS
== pin validity
PASS all pins used are valid and PWM-capable where required
-> PASS
== pin negative tests
PASS negative case detected: pin outside the board range
PASS negative case detected: analogWrite on a non-PWM pin
PASS negative case detected: ESP8266 Dn pin name in an AVR sketch
PASS control copy is clean
SELFTEST OK
-> PASS
== overall
ALL TESTS PASSED
```
Each run ends with a full compile of both targets and checks that the linked `firmware.bin` and `firmware.hex` really came out, with their size. The static analysis is placed first on purpose: `pio check` empties the build directory and deletes those binaries.
The zero-warning figure is for the two sketches: a clean build prints no warning for `Projeto.ino` or `Fetch_rain.ino`. The DS3231 library itself prints 41 warnings (40 `-Wwrite-strings`, 1 `-Wparentheses`) and `LiquidCrystal_I2C` raises 4 cppcheck `medium` findings; both are third-party and were left alone.
What the suite covers:
- **Compile.** Both targets are built for real, for the board named in `platformio.ini`. A compile error fails the run.
- **Static analysis.** `pio check` on both projects; it fails on any `high` defect.
- **Secrets.** `tests/check_secrets.py` fails if `Fetch_rain/secrets.h` is tracked or is missing from `.gitignore`, if `Fetch_rain/secrets.h.example` is missing or does not define every `WIFI_*`/`THINGHTTP_KEY_*` symbol `Fetch_rain.ino` uses, if the example holds anything that is not a placeholder, or if any tracked file holds a literal value for `api_key`/`password`/`passwd`/`pwd`/`ssid`/`secret`/`token` (quoted or not; a value that is a SCREAMING_SNAKE_CASE identifier counts as a symbol reference, not a literal).
- **Negative cases.** `--selftest` re-runs the same checkers against throwaway copies in which a symbol was deleted from `secrets.h.example`, the `secrets.h` rule was removed from `.gitignore`, a literal key was appended to `README.md`, the example was deleted, a pin was pushed out of range, `analogWrite` was moved to a non-PWM pin, and an ESP8266 `Dn` name was put in an AVR sketch. Each mutation must be detected, and an untouched copy must be clean; if a mutation goes undetected the selftest fails.
- **Pins.** `tests/check_pins.py` resolves every `pinMode`/`digitalWrite`/`digitalRead`/`analogWrite`/`analogRead` argument and the `SDA`/`SCL` macros against the Nano pin map, and checks that `analogWrite` is only used on PWM-capable pins.
Not covered, because it needs hardware: uploading, the WiFi association, the ThingSpeak responses, the I2C conversation with the DS3231, the LCD (which the code never writes to) and the LED behaviour. Nothing here was flashed.
## Structure
```text
Projeto.ino Nano + DS3231: 08:00-13:59 window, two LEDs on pins 5 and 6 (31 lines)
Fetch_rain/Fetch_rain.ino ESP-01: three ThingHTTP GETs, percentages on the serial port (176 lines)
Fetch_rain/secrets.h.example the five symbols the sketch needs, with placeholder values (11 lines)
Fetch_rain/platformio.ini PlatformIO project for the ESP-01 (src_dir = .) (22 lines)
platformio.ini PlatformIO project for Projeto.ino (src_dir = .) (32 lines)
run.sh build both targets, then run the tests (6 lines)
tests/run_tests.sh the suite: pio check, the two compiles, and the two checkers (74 lines)
tests/check_secrets.py secrets hygiene, with --selftest for the negative cases (196 lines)
tests/check_pins.py pins against the board pin maps, with --selftest (170 lines)
DEPENDENCIAS.md the DS3231 library: origin, version, licence, why it is not here
LICENSE MIT
Sumbrella.pdf the course poster; the only place the boards are named
Screenshot_6.jpg photo of the assembly; no code reads it
README.md this file
```
Every path above is in the repository. `Fetch_rain/secrets.h` is created from the example, is listed in `.gitignore` and is never committed.
## License
MIT — see [LICENSE](LICENSE). The DS3231 library is third-party, is not
redistributed here and keeps its own licence (CC BY-NC-SA 3.0).
MIT — see [LICENSE](LICENSE). Copyright (c) 2020 André Neto. `Sumbrella.pdf`, the course poster kept in this repository, names two students as authors of the work (André Guilherme dos Santos Neto and João Miguel Alves Moitas); the `LICENSE` file names only the first of them.
The DS3231 library used by `Projeto.ino` is third-party. It is CC BY-NC-SA 3.0, incompatible with MIT, and for that reason it is not redistributed here: it was removed from `libs/DS3231` and is now declared as an external dependency in [DEPENDENCIAS.md](DEPENDENCIAS.md) and pinned in `lib_deps`. It keeps its own licence, and commercial use of it requires a paid licence from its author (Rinky-Dink Electronics).
The WiFi password and the three ThingHTTP keys are not in the repository and never were: every revision reachable from `main` (six commits, including the `ESP8266_Fetching_Data.ino` sketch that was deleted in `b804d9a`) was scanned for a credential-looking literal and none was found — the old sketch carried the literal string `<REDACTED>` in its place.
+32
View File
@@ -0,0 +1,32 @@
; PlatformIO project for Projeto.ino, the DS3231 sketch that sits in the
; repository root. The ESP8266 sketch has its own project, because PlatformIO
; only converts a *.ino file that is at the top of its src_dir:
;
; pio run -> Projeto.ino (Arduino Nano)
; pio run -d Fetch_rain -> Fetch_rain.ino (ESP8266 ESP-01)
; ./run.sh -> both, then the offline tests
;
; Neither sketch names its board in its own source. The board is named on the
; course poster kept in this repository, Sumbrella.pdf, under "Listagem de
; material": "Arduino Nano" and "ESP8226 ESP-01" (sic). Projeto.ino agrees with
; the Nano: analogWrite() on pins 5 and 6, both PWM-capable, plus the SDA/SCL
; macros, which are A4/A5 = 18/19 on the Nano exactly as on the Uno.
[platformio]
src_dir = .
[env:nano]
platform = atmelavr
board = nanoatmega328new
framework = arduino
monitor_speed = 9600
; src_dir is the repository root, so keep the ESP8266 sketch's own project
; directory (and the .pio tree PlatformIO creates inside it) out of this build.
build_src_filter = +<*> -<Fetch_rain/>
lib_deps =
; DS3231 1.01 — Rinky-Dink Electronics / Henning Karlsen. It is NOT in the
; PlatformIO registry (all 87 registry search hits were checked for the
; class Time / getTimeStr() / DS3231(data, sclk) API it needs), so it is
; pinned to a byte-identical mirror of the removed libs/DS3231 at tag v1.01.
; See DEPENDENCIAS.md.
https://github.com/whonore/DS3231.git#v1.01
Executable
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Build both targets and run the offline test suite. Exit status != 0 on any
# build error or test failure. No board is needed.
set -uo pipefail
cd "$(dirname "$0")"
exec bash tests/run_tests.sh
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Offline check: every MCU pin used by the sketches exists on the target board.
Board data is the published pin map of each board:
- Arduino Nano (ATmega328P, DIP-30): digital pins 0-19, where A0-A5 are 14-19,
PWM on 3, 5, 6, 9, 10 and 11, and SDA/SCL are A4/A5 = 18/19.
- ESP-01 (ESP8266EX, 8-pin module): GPIO0-GPIO3 are the pins broken out; PWM is
available on every ESP8266 GPIO except GPIO16.
The board of each sketch is the one named on the course poster kept in this
repository (Sumbrella.pdf, "Listagem de material": Arduino Nano and ESP8266
ESP-01) and declared in platformio.ini.
Run with --selftest to prove the check bites: copies with an out-of-range pin
and with analogWrite() on a non-PWM pin must both be rejected.
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BOARDS = {
"nano": {
"env": "nano",
"sketch": "Projeto.ino",
"pins": set(range(0, 20)),
"pwm": {3, 5, 6, 9, 10, 11},
"macros": {"SDA": 18, "SCL": 19},
"dn_pins": False,
},
"esp01": {
"env": "esp8266",
"sketch": os.path.join("Fetch_rain", "Fetch_rain.ino"),
"pins": {0, 1, 2, 3},
"pwm": {0, 1, 2, 3},
"macros": {},
"dn_pins": True,
},
}
CALL_RE = re.compile(
r"\b(pinMode|digitalWrite|digitalRead|analogWrite|analogRead)\s*\(\s*"
r"([A-Za-z_][A-Za-z0-9_]*|\d+)"
)
ESPNUM_RE = re.compile(r"\bD(\d{1,2})\b")
def read(path):
with open(path, encoding="utf-8") as fh:
return fh.read()
def used_pins(text, macros):
"""Return [(function, raw_pin_text, resolved_int)] for a sketch."""
found = []
for func, raw in CALL_RE.findall(text):
if raw.isdigit():
found.append((func, raw, int(raw)))
elif raw in macros:
found.append((func, raw, macros[raw]))
return found
def check(root):
errors = []
for board, cfg in BOARDS.items():
path = os.path.join(root, cfg["sketch"])
if not os.path.isfile(path):
errors.append("%s: sketch %s is missing" % (board, cfg["sketch"]))
continue
text = read(path)
for func, raw, pin in used_pins(text, cfg["macros"]):
if pin not in cfg["pins"]:
errors.append("%s: %s(%s) -> pin %s does not exist on %s "
"(valid: 0-%d)"
% (board, func, raw, pin, board,
max(cfg["pins"])))
elif func == "analogWrite" and pin not in cfg["pwm"]:
errors.append("%s: analogWrite(%s) -> pin %s is not PWM-capable"
% (board, raw, pin))
# A stray D0..D16 style pin on the AVR target would not compile.
if not cfg["dn_pins"] and ESPNUM_RE.search(text):
errors.append("%s: %s uses an ESP8266 Dn pin name"
% (board, cfg["sketch"]))
return errors
def run_selftest():
failures = []
def copy():
tmp = tempfile.mkdtemp(prefix="sumbrella-pin-selftest-")
dst = os.path.join(tmp, "repo")
shutil.copytree(REPO, dst, symlinks=True)
return tmp, dst
cases = [
("pin outside the board range",
"Projeto.ino",
lambda t: t.replace("pinMode(5, OUTPUT)", "pinMode(23, OUTPUT)")),
("analogWrite on a non-PWM pin",
"Projeto.ino",
lambda t: t.replace("analogWrite(5, redValue)",
"analogWrite(4, redValue)")),
("ESP8266 Dn pin name in an AVR sketch",
"Projeto.ino",
lambda t: t.replace("pinMode(6, OUTPUT)", "pinMode(D6, OUTPUT)")),
]
for name, rel, mutate in cases:
tmp, dst = copy()
try:
p = os.path.join(dst, rel)
text = read(p)
new = mutate(text)
if new == text:
print(" FAIL selftest could not mutate %s (%s)" % (rel, name))
failures.append(name)
continue
with open(p, "w", encoding="utf-8") as fh:
fh.write(new)
if check(dst):
print(" PASS negative case detected: %s" % name)
else:
print(" FAIL negative case NOT detected: %s" % name)
failures.append(name)
finally:
shutil.rmtree(tmp, ignore_errors=True)
tmp, dst = copy()
try:
if check(dst):
print(" FAIL control copy is not clean: %s" % "; ".join(check(dst)))
failures.append("control")
else:
print(" PASS control copy is clean")
finally:
shutil.rmtree(tmp, ignore_errors=True)
return failures
def main():
if "--selftest" in sys.argv:
print("check_pins.py --selftest")
failures = run_selftest()
if failures:
print("SELFTEST FAILED: %s" % ", ".join(failures))
return 1
print("SELFTEST OK")
return 0
errors = check(REPO)
for err in errors:
print(" FAIL %s" % err)
if errors:
return 1
print(" PASS all pins used are valid and PWM-capable where required")
return 0
if __name__ == "__main__":
sys.exit(main())
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Offline checks: no credential leaks and a complete secrets.h.example.
Failure conditions (each one makes this script exit non-zero):
1. Fetch_rain/secrets.h is tracked by git.
2. Fetch_rain/secrets.h is not covered by .gitignore.
3. Fetch_rain/secrets.h.example is missing, or does not define every
WIFI_*/THINGHTTP_KEY_* symbol that Fetch_rain.ino references.
4. Fetch_rain/secrets.h.example holds anything that does not look like a
placeholder.
5. Any git-tracked file holds a literal value for a credential-looking key
(api_key / password / passwd / pwd / ssid / secret / token), quoted or
not. A value that is a SCREAMING_SNAKE_CASE identifier is treated as a
reference to a symbol, not as a literal.
Run with --selftest to prove those checks actually bite: the checker is re-run
against deliberately broken copies and MUST fail on each one.
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SKETCH = os.path.join("Fetch_rain", "Fetch_rain.ino")
EXAMPLE = os.path.join("Fetch_rain", "secrets.h.example")
SECRETS = os.path.join("Fetch_rain", "secrets.h")
SYMBOL_RE = re.compile(r"\b((?:WIFI|THINGHTTP_KEY)_[A-Z0-9_]+)\b")
KEY = r"(api[_-]?key|password|passwd|pwd|ssid|secret|token)"
QUOTED_RE = re.compile(KEY + r"""\s*[=:]\s*["']([^"'\n]{6,})["']""", re.I)
BARE_RE = re.compile(KEY + r"\s*[=:]\s*([A-Za-z0-9_\-\.]{8,})", re.I)
SYMBOL_VALUE_RE = re.compile(r"^[A-Z0-9_]+$")
PLACEHOLDER_HINTS = ("your-", "your_", "example", "changeme", "change-me",
"xxx", "todo", "placeholder", "<", "$", "{}")
SKIP_SUFFIX = (".jpg", ".jpeg", ".png", ".pdf", ".gif", ".ico", ".zip")
def read(root, rel):
with open(os.path.join(root, rel), encoding="utf-8") as fh:
return fh.read()
def git(root, *args):
return subprocess.run(["git", "-C", root, *args], capture_output=True,
text=True)
def is_real(value):
"""True if `value` is a literal that must not be in a tracked file."""
if "(" in value or ")" in value or "+" in value or " " in value:
return False
if SYMBOL_VALUE_RE.match(value):
return False
return not any(h in value.lower() for h in PLACEHOLDER_HINTS)
def check(root):
errors = []
tracked = [p for p in git(root, "ls-files").stdout.splitlines() if p]
if not tracked:
return ["%s is not a git checkout with tracked files" % root]
if SECRETS in tracked:
errors.append("SECURITY: %s is tracked by git" % SECRETS)
if git(root, "check-ignore", "-q", SECRETS).returncode != 0:
errors.append("SECURITY: %s is not matched by .gitignore" % SECRETS)
if not os.path.isfile(os.path.join(root, EXAMPLE)):
errors.append("%s is missing" % EXAMPLE)
example_text = ""
else:
example_text = read(root, EXAMPLE)
used = set(SYMBOL_RE.findall(read(root, SKETCH)))
defined = set(re.findall(r"^\s*(?:const\s+char\s*\*\s*)?([A-Z0-9_]+)\s*=",
example_text, re.MULTILINE))
missing = sorted(used - defined)
if missing:
errors.append("%s does not define %s (used by %s)"
% (EXAMPLE, ", ".join(missing), SKETCH))
for name, value in re.findall(r"\b([A-Z0-9_]+)\s*=\s*\"([^\"]*)\"",
example_text):
if not any(h in value.lower() for h in PLACEHOLDER_HINTS):
errors.append("%s looks like a real value, not a placeholder: "
"%s = \"%s\"" % (EXAMPLE, name, value))
for rel in tracked:
if rel.endswith(SKIP_SUFFIX) or rel == EXAMPLE:
continue
try:
text = read(root, rel)
except (UnicodeDecodeError, IsADirectoryError):
continue
for lineno, line in enumerate(text.splitlines(), 1):
for regex in (QUOTED_RE, BARE_RE):
for key, value in regex.findall(line):
if is_real(value):
errors.append("SECURITY: literal %s in %s:%d (%s)"
% (key.lower(), rel, lineno, value))
return errors
def run_selftest():
failures = []
# The literal is assembled at run time so that this file itself does not
# contain the pattern the checker looks for.
fake_key = "Th1ngsP34k" + "RealKey" + "0001"
def temp_copy():
tmp = tempfile.mkdtemp(prefix="sumbrella-selftest-")
dst = os.path.join(tmp, "repo")
shutil.copytree(REPO, dst, symlinks=True)
return tmp, dst
def drop_symbol(dst):
p = os.path.join(dst, EXAMPLE)
lines = [l for l in open(p, encoding="utf-8")
if not l.startswith("const char* THINGHTTP_KEY_TMRW")]
open(p, "w", encoding="utf-8").writelines(lines)
shutil.copyfile(p, os.path.join(dst, SECRETS))
def drop_gitignore_rule(dst):
p = os.path.join(dst, ".gitignore")
lines = [l for l in open(p, encoding="utf-8")
if l.strip() != "secrets.h"]
open(p, "w", encoding="utf-8").writelines(lines)
def inject_literal(dst):
with open(os.path.join(dst, "README.md"), "a", encoding="utf-8") as fh:
fh.write("\n<!-- api_key=" + fake_key + " -->\n")
def remove_example(dst):
os.remove(os.path.join(dst, EXAMPLE))
cases = [
("secrets.h.example loses one symbol", drop_symbol),
(".gitignore loses the secrets.h rule", drop_gitignore_rule),
("a tracked file gains a literal api_key", inject_literal),
("secrets.h.example is deleted", remove_example),
]
for name, mutate in cases:
tmp, dst = temp_copy()
try:
mutate(dst)
if check(dst):
print(" PASS negative case detected: %s" % name)
else:
print(" FAIL negative case NOT detected: %s" % name)
failures.append(name)
finally:
shutil.rmtree(tmp, ignore_errors=True)
# Control: the untouched copy must be clean, otherwise the negative cases
# above prove nothing.
tmp, dst = temp_copy()
try:
errs = check(dst)
if errs:
print(" FAIL control copy is not clean: %s" % "; ".join(errs))
failures.append("control")
else:
print(" PASS control copy is clean")
finally:
shutil.rmtree(tmp, ignore_errors=True)
return failures
def main():
if "--selftest" in sys.argv:
print("check_secrets.py --selftest")
failures = run_selftest()
if failures:
print("SELFTEST FAILED: %s" % ", ".join(failures))
return 1
print("SELFTEST OK")
return 0
errors = check(REPO)
for err in errors:
print(" FAIL %s" % err)
if errors:
return 1
print(" PASS secrets.h untracked and ignored; secrets.h.example defines "
"every symbol the sketch uses and holds no real value; no tracked "
"file holds a literal credential")
return 0
if __name__ == "__main__":
sys.exit(main())
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Offline test suite for sumbrella. Exit status != 0 if anything fails.
# Nothing here needs a board: it is a real compile for both targets plus
# static analysis of the sources. See README.md, section "Tests".
#
# The static analysis runs first on purpose: `pio check` triggers a clean build
# and removes firmware.bin/firmware.elf/firmware.hex, so the real compiles come
# last and leave the linked binaries in place.
set -uo pipefail
cd "$(dirname "$0")/.."
PIO="${PIO:-}"
if [ -z "$PIO" ]; then
for c in "$(command -v pio || true)" "$HOME/.venvs/platformio/bin/pio"; do
[ -n "$c" ] && [ -x "$c" ] && PIO="$c" && break
done
fi
if [ ! -f Fetch_rain/secrets.h ]; then
cp Fetch_rain/secrets.h.example Fetch_rain/secrets.h
fi
rc=0
run() {
local name="$1"; shift
echo "== $name"
if "$@"; then
echo " -> PASS"
else
echo " -> FAIL"
rc=1
fi
echo
}
build() {
local name="$1" dir="$2" artefact="$3"
echo "== $name"
if "$PIO" run ${dir:+-d "$dir"}; then
if [ -f "$artefact" ]; then
echo " artefact: $artefact ($(stat -c%s "$artefact") bytes)"
else
echo " artefact missing: $artefact"
rc=1
fi
echo " -> PASS"
else
echo " -> FAIL"
rc=1
fi
echo
}
if [ -n "$PIO" ]; then
run "pio check, ESP8266 ESP-01" "$PIO" check -d Fetch_rain --skip-packages
run "pio check, Arduino Nano" "$PIO" check --skip-packages
build "compile ESP8266 ESP-01 (Fetch_rain.ino)" "Fetch_rain" \
"Fetch_rain/.pio/build/esp8266/firmware.bin"
build "compile Arduino Nano (Projeto.ino)" "" \
".pio/build/nano/firmware.hex"
else
echo "== compile + static analysis: SKIPPED (no pio on PATH or in ~/.venvs/platformio)"
echo
rc=1
fi
run "secrets hygiene" python3 tests/check_secrets.py
run "secrets negative tests" python3 tests/check_secrets.py --selftest
run "pin validity" python3 tests/check_pins.py
run "pin negative tests" python3 tests/check_pins.py --selftest
echo "== overall"
if [ "$rc" -eq 0 ]; then echo "ALL TESTS PASSED"; else echo "TESTS FAILED"; fi
exit "$rc"