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 in009066d. 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 before009066d.
This commit is contained in:
@@ -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())
|
||||
@@ -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())
|
||||
Executable
+74
@@ -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"
|
||||
Reference in New Issue
Block a user