Compare commits
32 Commits
e66488fa71
...
feature/vf
| Author | SHA1 | Date | |
|---|---|---|---|
| ef875334c5 | |||
| 252caf1bf7 | |||
| 21b413eb57 | |||
| 2879be0ada | |||
| b6e4bfea33 | |||
| 59721477df | |||
| 7be9b59093 | |||
| 9a25805522 | |||
| 44afc207ea | |||
| 549a7c7d37 | |||
| 10ef3580b2 | |||
| f78d090f95 | |||
| ef986c2881 | |||
| 4cb4947bd1 | |||
| 18093092f0 | |||
| 358ddcaeb5 | |||
| 2282038391 | |||
| f7f7b389a0 | |||
| d9d17e5e5c | |||
| 4a7551e358 | |||
| 19b1a7c6e5 | |||
| 036fa045f8 | |||
| a9fc7cd0ed | |||
| cf2c55f5cf | |||
|
7aaf5ce334
|
|||
| 5bfa52c1ca | |||
|
3a7f98a3d2
|
|||
|
6cc0cff069
|
|||
| 271cf7d3e8 | |||
| 2c81ddfd6b | |||
| e521ef8a2a | |||
| d0be1e9b0a |
109
CLAUDE.md
Normal file
109
CLAUDE.md
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Build & Upload
|
||||||
|
|
||||||
|
Main firmware lives in `Gaugecontroller/Gaugecontroller.ino`. Requires the **FastLED** library (`arduino-cli lib install FastLED`). Use the Arduino IDE or `arduino-cli`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Compile (replace board/port as needed)
|
||||||
|
arduino-cli compile --fqbn arduino:avr:mega Gaugecontroller
|
||||||
|
|
||||||
|
# Upload
|
||||||
|
arduino-cli upload -p /dev/ttyACM0 --fqbn arduino:avr:mega Gaugecontroller
|
||||||
|
```
|
||||||
|
|
||||||
|
Current default serial setup: `CMD_PORT` and `DEBUG_PORT` both point to `Serial1` at 38400 baud.
|
||||||
|
|
||||||
|
## Switching serial ports (debug → production)
|
||||||
|
|
||||||
|
Two `#define`s at the top of `Gaugecontroller.ino` control where commands and debug output go:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define CMD_PORT Serial1 // command channel (host sends SET, HOME, etc.)
|
||||||
|
#define DEBUG_PORT Serial1 // diagnostic prints (homing, boot messages)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Current default:** both point to `Serial1`, so command and debug traffic share Mega pins TX1=18 / RX1=19 at 38400 baud.
|
||||||
|
|
||||||
|
**USB-only debug setup:** point both defines back at `Serial` if you want to talk to the sketch over the Arduino USB port instead:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define CMD_PORT Serial
|
||||||
|
#define DEBUG_PORT Serial
|
||||||
|
```
|
||||||
|
|
||||||
|
At that point the matching `begin()` call in `setup()` also needs to use the same baud rate you expect on the host side.
|
||||||
|
|
||||||
|
**Split command/debug ports:** if `CMD_PORT` and `DEBUG_PORT` do not point to the same serial port, `setup()` must initialise both. Right now it only calls:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
DEBUG_PORT.begin(38400);
|
||||||
|
```
|
||||||
|
|
||||||
|
If you split them, add a second `CMD_PORT.begin(...)` call.
|
||||||
|
|
||||||
|
Arduino Mega hardware UARTs for reference:
|
||||||
|
|
||||||
|
| Port | TX pin | RX pin |
|
||||||
|
|---------|--------|--------|
|
||||||
|
| Serial1 | 18 | 19 |
|
||||||
|
| Serial2 | 16 | 17 |
|
||||||
|
| Serial3 | 14 | 15 |
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The sketch controls `GAUGE_COUNT` stepper-motor gauges using a trapezoidal velocity profile and a simple text serial protocol.
|
||||||
|
|
||||||
|
### Key data structures
|
||||||
|
|
||||||
|
- `GaugePins` — hardware pin mapping per gauge (dir, step, enable, active-high/low polarity flags, `ledCount`). Declared `constexpr` so `TOTAL_LEDS` can be computed from it at compile time. Configured in the `gaugePins[]` array at the top.
|
||||||
|
- `Gauge` — per-gauge runtime state: position, target, velocity, accel, homing state machine, sweep mode.
|
||||||
|
|
||||||
|
### Motion control (`updateGauge`)
|
||||||
|
|
||||||
|
Each call to `updateGauge(id)` in `loop()` computes `dt` since last call and updates velocity using a braking-distance check to produce smooth trapezoidal motion. Steps are accumulated as floating-point and emitted via `doStep` when the accumulator crosses ±1.
|
||||||
|
|
||||||
|
### Homing sequence (`updateHoming`)
|
||||||
|
|
||||||
|
State machine: `HS_START → HS_BACKING → HS_SETTLE → HS_DONE → HS_IDLE`.
|
||||||
|
Backs up `homingBackoffSteps` at `homingSpeed`, waits 100 ms settle, then declares `currentPos = 0`. No physical end-stop is used; homing is purely time/step-count based.
|
||||||
|
|
||||||
|
### Sweep mode
|
||||||
|
|
||||||
|
When `sweepEnabled`, `updateSweepTarget` bounces `targetPos` between `minPos` and `maxPos` autonomously.
|
||||||
|
|
||||||
|
### LED strip
|
||||||
|
|
||||||
|
One shared WS2812B strip is driven from `LED_DATA_PIN` (currently 22). Each gauge owns a contiguous segment of the strip; `gaugePins[i].ledCount` sets the segment length (0 = no LEDs). `TOTAL_LEDS` is computed at compile time via `constexpr sumLedCounts()` — no manual constant to keep in sync. Per-gauge offsets into the flat `leds[]` array are computed once in `setup()` into `gaugeLedOffset[]`. LED commands and effects mark the strip dirty, and `FastLED.show()` is called once per main-loop iteration if anything changed.
|
||||||
|
|
||||||
|
### Serial command protocol
|
||||||
|
|
||||||
|
Commands arrive as newline-terminated ASCII lines. Each `parse*` function in `processLine` handles one command family:
|
||||||
|
|
||||||
|
| Command | Syntax | Effect |
|
||||||
|
|---|---|---|
|
||||||
|
| `SET` | `SET <id> <pos>` | Move gauge to absolute step position |
|
||||||
|
| `SPEED` | `SPEED <id> <steps/s>` | Set max speed |
|
||||||
|
| `ACCEL` | `ACCEL <id> <steps/s²>` | Set acceleration |
|
||||||
|
| `ENABLE` | `ENABLE <id> <0\|1>` | Enable/disable driver output |
|
||||||
|
| `ZERO` | `ZERO <id>` | Mark current position as home without moving |
|
||||||
|
| `HOME` | `HOME <id>` / `HOMEALL` | Run homing sequence |
|
||||||
|
| `SWEEP` | `SWEEP <id> <accel> <speed>` | Start sweep (0/0 stops) |
|
||||||
|
| `POS?` | `POS?` | Query all gauges: `POS <id> <cur> <tgt> <homed> <homingState> <sweep>` |
|
||||||
|
| `LED` | `LED <id> <idx> <r> <g> <b>` | Set one LED (0-based index within gauge segment) to RGB colour (0–255 each); `<idx>` may be a range `N-M` to set LEDs N through M in one command; also stops any active effect on those LEDs |
|
||||||
|
| `LED?` | `LED?` | Query all LEDs: one `LED <id> <idx> <r> <g> <b>` line per LED, then `OK` |
|
||||||
|
| `BLINK` | `BLINK <id> <idx> <on_ms> <off_ms> <r> <g> <b>` | Blink LED(s) at given colour; `<idx>` may be a range `N-M`; `on_ms`/`off_ms` both 0 stops blinking. 4-arg form (no colour) uses current LED colour |
|
||||||
|
| `BREATHE` | `BREATHE <id> <idx> <period_ms> <r> <g> <b>` | Smooth triangle-wave fade between black and the given colour; `<idx>` may be a range `N-M` |
|
||||||
|
| `DFLASH` | `DFLASH <id> <idx> <r> <g> <b>` | Two quick flashes (100 ms on/off each) followed by a 700 ms pause, then repeats; `<idx>` may be a range `N-M` |
|
||||||
|
| `PING` | `PING` | Responds `PONG` |
|
||||||
|
|
||||||
|
All commands reply `OK` or `ERR BAD_ID` / `ERR BAD_CMD` etc.
|
||||||
|
|
||||||
|
### Adding gauges
|
||||||
|
|
||||||
|
1. Increment `GAUGE_COUNT`.
|
||||||
|
2. Add a `constexpr GaugePins` entry to `gaugePins[]` (including `ledCount`).
|
||||||
|
3. Tune `maxPos` and `homingBackoffSteps` in the corresponding `Gauge` default or at runtime.
|
||||||
|
4. `TOTAL_LEDS` and `gaugeLedOffset[]` update automatically — no manual changes needed.
|
||||||
1150
Gaugecontroller/Gaugecontroller.ino
Normal file
1150
Gaugecontroller/Gaugecontroller.ino
Normal file
File diff suppressed because it is too large
Load Diff
56
VFDStandalone/Pinout.md
Normal file
56
VFDStandalone/Pinout.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# Pinout
|
||||||
|
|
||||||
|
This project uses an Arduino Mega 2560 with an `HV5812P` high-voltage shift register / latch driver.
|
||||||
|
|
||||||
|
The sketch in [VFDStandalone.ino](/home/adebaumann/development/arduino_gauge_controller/VFDStandalone/VFDStandalone.ino:1) currently expects these logic connections.
|
||||||
|
|
||||||
|
## Arduino Mega 2560 -> HV5812P
|
||||||
|
|
||||||
|
| Mega Pin | Mega Function | HV5812P Signal | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `D51` | `MOSI` | `DATA` / `DIN` | Serial data into the HV5812P |
|
||||||
|
| `D52` | `SCK` | `CLOCK` / `CLK` | Shift clock |
|
||||||
|
| `D53` | `SS` | `LATCH` / `STROBE` | Transfers shifted bits to the outputs |
|
||||||
|
| `D49` | GPIO | `BLANK` / `OE` | Optional. Set `kHvBlankPin = -1` in the sketch if unused |
|
||||||
|
| `GND` | Ground | Logic `GND` | Mega and HV5812P logic ground must be common |
|
||||||
|
|
||||||
|
## HV5812P Outputs -> VFD Tube
|
||||||
|
|
||||||
|
| HV5812P Output | Function |
|
||||||
|
|---|---|
|
||||||
|
| `HVOut1` | Segment `A` |
|
||||||
|
| `HVOut2` | Segment `B` |
|
||||||
|
| `HVOut3` | Segment `C` |
|
||||||
|
| `HVOut4` | Segment `D` |
|
||||||
|
| `HVOut5` | Segment `E` |
|
||||||
|
| `HVOut6` | Segment `F` |
|
||||||
|
| `HVOut7` | Segment `G` |
|
||||||
|
| `HVOut8` | Decimal point segment |
|
||||||
|
| `HVOut9` | Alarm bell segment |
|
||||||
|
| `HVOut10` | Digit grid 1 |
|
||||||
|
| `HVOut11` | Digit grid 2 |
|
||||||
|
| `HVOut12` | Digit grid 3 |
|
||||||
|
| `HVOut13` | Digit grid 4 |
|
||||||
|
| `HVOut14` | Indicator grid between digits 2 and 3 |
|
||||||
|
|
||||||
|
## Serial Input Format
|
||||||
|
|
||||||
|
Examples supported by the sketch:
|
||||||
|
|
||||||
|
- `1234` -> digits only
|
||||||
|
- `1234.` -> decimal point on
|
||||||
|
- `1234!` -> alarm bell on
|
||||||
|
- `1234.!` -> decimal point and alarm bell on
|
||||||
|
|
||||||
|
## Power and Safety Notes
|
||||||
|
|
||||||
|
- The Arduino `5V` pin is for the logic side only.
|
||||||
|
- The HV5812P also needs its required logic supply and high-voltage supply per the datasheet.
|
||||||
|
- The VFD filament, grid, and segment high-voltage wiring are separate from the Arduino logic pins.
|
||||||
|
- Do not connect any high-voltage VFD node directly to the Arduino Mega.
|
||||||
|
- If the blanking behavior is inverted on your board, change `kBlankActiveHigh` in the sketch.
|
||||||
|
|
||||||
|
## Important
|
||||||
|
|
||||||
|
This file names the functional signals on the `HV5812P`, not the package pin numbers.
|
||||||
|
If you want a package-pin wiring table too, I can add one once you confirm the exact datasheet variant / package orientation you are using.
|
||||||
342
VFDStandalone/VFDStandalone.ino
Normal file
342
VFDStandalone/VFDStandalone.ino
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
// Arduino Mega 2560 + HV5812P VFD driver
|
||||||
|
//
|
||||||
|
// Tube wiring:
|
||||||
|
// - HVOut1..HVOut7 -> digit segments A..G
|
||||||
|
// - HVOut8 -> decimal point segment on the indicator grid
|
||||||
|
// - HVOut9 -> alarm bell segment on the indicator grid
|
||||||
|
// - HVOut10..HVOut13 -> digits 1..4
|
||||||
|
// - HVOut14 -> indicator grid between digits 2 and 3
|
||||||
|
//
|
||||||
|
// Send an integer over the USB serial port and it will be shown on the VFD.
|
||||||
|
// Examples:
|
||||||
|
// 42<newline>
|
||||||
|
// -17<newline>
|
||||||
|
// 1234.<newline> // enables the decimal point
|
||||||
|
// 1234!<newline> // enables the alarm bell
|
||||||
|
// 1234.!<newline> // enables both
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kHvDataPin = 51; // MOSI on Mega 2560
|
||||||
|
constexpr uint8_t kHvClockPin = 52; // SCK on Mega 2560
|
||||||
|
constexpr uint8_t kHvLatchPin = 53; // User-configurable latch/strobe pin
|
||||||
|
constexpr int8_t kHvBlankPin = 49; // Set to -1 if BL/OE is not connected
|
||||||
|
constexpr bool kBlankActiveHigh = true;
|
||||||
|
|
||||||
|
constexpr unsigned long kSerialBaud = 115200;
|
||||||
|
constexpr unsigned long kDigitHoldMicros = 2000;
|
||||||
|
|
||||||
|
constexpr uint8_t kDigitCount = 4;
|
||||||
|
constexpr uint8_t kSegmentCount = 7;
|
||||||
|
constexpr uint8_t kDriverBits = 20;
|
||||||
|
|
||||||
|
constexpr uint8_t kSegmentStartBit = 0; // HVOut1 -> bit 0
|
||||||
|
constexpr uint8_t kPointSegmentBit = 7; // HVOut8 -> bit 7
|
||||||
|
constexpr uint8_t kBellSegmentBit = 8; // HVOut9 -> bit 8
|
||||||
|
constexpr uint8_t kGridStartBit = 9; // HVOut10 -> bit 9
|
||||||
|
constexpr uint8_t kIndicatorGridBit = 13; // HVOut14 -> bit 13
|
||||||
|
|
||||||
|
char g_displayBuffer[kDigitCount] = {' ', ' ', ' ', ' '};
|
||||||
|
char g_inputBuffer[16];
|
||||||
|
uint8_t g_inputLength = 0;
|
||||||
|
bool g_pointEnabled = false;
|
||||||
|
bool g_bellEnabled = false;
|
||||||
|
uint8_t g_rawOutput = 0;
|
||||||
|
|
||||||
|
// Seven-segment encoding order is A, B, C, D, E, F, G.
|
||||||
|
uint8_t encodeCharacter(char c) {
|
||||||
|
switch (c) {
|
||||||
|
case '0': return 0b0111111;
|
||||||
|
case '1': return 0b0000110;
|
||||||
|
case '2': return 0b1011011;
|
||||||
|
case '3': return 0b1001111;
|
||||||
|
case '4': return 0b1100110;
|
||||||
|
case '5': return 0b1101101;
|
||||||
|
case '6': return 0b1111101;
|
||||||
|
case '7': return 0b0000111;
|
||||||
|
case '8': return 0b1111111;
|
||||||
|
case '9': return 0b1101111;
|
||||||
|
case 'A':
|
||||||
|
case 'a': return 0b1110111;
|
||||||
|
case 'B':
|
||||||
|
case 'b': return 0b1111100;
|
||||||
|
case 'C':
|
||||||
|
case 'c': return 0b0111001;
|
||||||
|
case 'D':
|
||||||
|
case 'd': return 0b1011110;
|
||||||
|
case 'E':
|
||||||
|
case 'e': return 0b1111001;
|
||||||
|
case 'F':
|
||||||
|
case 'f': return 0b1110001;
|
||||||
|
case '-': return 0b1000000;
|
||||||
|
default: return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void shiftDriverWord(uint32_t word) {
|
||||||
|
digitalWrite(kHvLatchPin, HIGH);
|
||||||
|
digitalWrite(kHvClockPin, HIGH);
|
||||||
|
|
||||||
|
for (int8_t bit = kDriverBits - 1; bit >= 0; --bit) {
|
||||||
|
digitalWrite(kHvDataPin, (word >> bit) & 0x1U ? HIGH : LOW);
|
||||||
|
digitalWrite(kHvClockPin, LOW);
|
||||||
|
digitalWrite(kHvClockPin, HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
digitalWrite(kHvLatchPin, LOW);
|
||||||
|
digitalWrite(kHvLatchPin, HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setDisplayBlanked(bool blanked) {
|
||||||
|
if (kHvBlankPin < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool level = kBlankActiveHigh ? blanked : !blanked;
|
||||||
|
digitalWrite(kHvBlankPin, level ? HIGH : LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
void blankDisplay() {
|
||||||
|
shiftDriverWord(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t maskForHvOutput(uint8_t hvOutput) {
|
||||||
|
if (hvOutput == 0 || hvOutput > kDriverBits) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1UL << (hvOutput - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void renderDigit(uint8_t digitIndex) {
|
||||||
|
uint32_t word = 0;
|
||||||
|
const uint8_t segments = encodeCharacter(g_displayBuffer[digitIndex]);
|
||||||
|
|
||||||
|
for (uint8_t segment = 0; segment < kSegmentCount; ++segment) {
|
||||||
|
if ((segments >> segment) & 0x1U) {
|
||||||
|
word |= (1UL << (kSegmentStartBit + segment));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
word |= (1UL << (kGridStartBit + digitIndex));
|
||||||
|
shiftDriverWord(word);
|
||||||
|
}
|
||||||
|
|
||||||
|
void renderIndicator() {
|
||||||
|
uint32_t word = 1UL << kIndicatorGridBit;
|
||||||
|
|
||||||
|
if (g_pointEnabled) {
|
||||||
|
word |= 1UL << kPointSegmentBit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_bellEnabled) {
|
||||||
|
word |= 1UL << kBellSegmentBit;
|
||||||
|
}
|
||||||
|
|
||||||
|
shiftDriverWord(word);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeTextToDisplay(const char* text) {
|
||||||
|
for (uint8_t i = 0; i < kDigitCount; ++i) {
|
||||||
|
g_displayBuffer[i] = ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t len = strlen(text);
|
||||||
|
if (len > kDigitCount) {
|
||||||
|
text += len - kDigitCount;
|
||||||
|
len = kDigitCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t start = kDigitCount - len;
|
||||||
|
for (uint8_t i = 0; i < len; ++i) {
|
||||||
|
g_displayBuffer[start + i] = text[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setDisplayFromNumber(long value) {
|
||||||
|
char buffer[16];
|
||||||
|
ltoa(value, buffer, 10);
|
||||||
|
writeTextToDisplay(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool parseDisplayCommand(const char* input,
|
||||||
|
char* displayText,
|
||||||
|
size_t displayTextSize,
|
||||||
|
bool& pointEnabled,
|
||||||
|
bool& bellEnabled) {
|
||||||
|
size_t inputIndex = 0;
|
||||||
|
size_t displayIndex = 0;
|
||||||
|
|
||||||
|
if (input[inputIndex] == '-') {
|
||||||
|
if (displayIndex + 1 >= displayTextSize) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
displayText[displayIndex++] = input[inputIndex++];
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t digitStart = inputIndex;
|
||||||
|
while (isxdigit(static_cast<unsigned char>(input[inputIndex]))) {
|
||||||
|
if (displayIndex + 1 >= displayTextSize) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
displayText[displayIndex] = toupper(static_cast<unsigned char>(input[inputIndex]));
|
||||||
|
++displayIndex;
|
||||||
|
++inputIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inputIndex == digitStart) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
pointEnabled = false;
|
||||||
|
bellEnabled = false;
|
||||||
|
|
||||||
|
while (input[inputIndex] != '\0') {
|
||||||
|
if (input[inputIndex] == '.') {
|
||||||
|
pointEnabled = true;
|
||||||
|
} else if (input[inputIndex] == '!') {
|
||||||
|
bellEnabled = true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
++inputIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
displayText[displayIndex] = '\0';
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool parseRawOutputCommand(const char* input, uint8_t& hvOutput) {
|
||||||
|
if (strncmp(input, "RAW ", 4) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* endPtr = nullptr;
|
||||||
|
const long parsed = strtol(input + 4, &endPtr, 10);
|
||||||
|
if (*endPtr != '\0' || parsed < 0 || parsed > kDriverBits) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
hvOutput = static_cast<uint8_t>(parsed);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void commitSerialBuffer() {
|
||||||
|
if (g_inputLength == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_inputBuffer[g_inputLength] = '\0';
|
||||||
|
|
||||||
|
uint8_t rawOutput = 0;
|
||||||
|
if (parseRawOutputCommand(g_inputBuffer, rawOutput)) {
|
||||||
|
g_rawOutput = rawOutput;
|
||||||
|
if (g_rawOutput == 0) {
|
||||||
|
Serial.println(F("RAW mode OFF"));
|
||||||
|
} else {
|
||||||
|
Serial.print(F("RAW mode: HVOUT"));
|
||||||
|
Serial.println(g_rawOutput);
|
||||||
|
}
|
||||||
|
g_inputLength = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
char displayText[16];
|
||||||
|
bool pointEnabled = false;
|
||||||
|
bool bellEnabled = false;
|
||||||
|
if (parseDisplayCommand(g_inputBuffer, displayText, sizeof(displayText), pointEnabled, bellEnabled)) {
|
||||||
|
g_rawOutput = 0;
|
||||||
|
writeTextToDisplay(displayText);
|
||||||
|
g_pointEnabled = pointEnabled;
|
||||||
|
g_bellEnabled = bellEnabled;
|
||||||
|
Serial.print(F("Displaying: "));
|
||||||
|
Serial.println(displayText);
|
||||||
|
Serial.print(F("Point: "));
|
||||||
|
Serial.println(g_pointEnabled ? F("ON") : F("OFF"));
|
||||||
|
Serial.print(F("Bell: "));
|
||||||
|
Serial.println(g_bellEnabled ? F("ON") : F("OFF"));
|
||||||
|
} else {
|
||||||
|
Serial.print(F("Ignored invalid input: "));
|
||||||
|
Serial.println(g_inputBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
g_inputLength = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void pollSerial() {
|
||||||
|
while (Serial.available() > 0) {
|
||||||
|
const char incoming = static_cast<char>(Serial.read());
|
||||||
|
|
||||||
|
if (incoming == '\r' || incoming == '\n') {
|
||||||
|
commitSerialBuffer();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (incoming == '\b' || incoming == 127) {
|
||||||
|
if (g_inputLength > 0) {
|
||||||
|
--g_inputLength;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_inputLength < sizeof(g_inputBuffer) - 1) {
|
||||||
|
g_inputBuffer[g_inputLength++] = incoming;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void refreshDisplay() {
|
||||||
|
if (g_rawOutput != 0) {
|
||||||
|
setDisplayBlanked(true);
|
||||||
|
shiftDriverWord(maskForHvOutput(g_rawOutput));
|
||||||
|
setDisplayBlanked(false);
|
||||||
|
delayMicroseconds(kDigitHoldMicros);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t currentPhase = 0;
|
||||||
|
|
||||||
|
setDisplayBlanked(true);
|
||||||
|
if (currentPhase < kDigitCount) {
|
||||||
|
renderDigit(currentPhase);
|
||||||
|
} else if (g_pointEnabled || g_bellEnabled) {
|
||||||
|
renderIndicator();
|
||||||
|
} else {
|
||||||
|
blankDisplay();
|
||||||
|
}
|
||||||
|
setDisplayBlanked(false);
|
||||||
|
delayMicroseconds(kDigitHoldMicros);
|
||||||
|
setDisplayBlanked(true);
|
||||||
|
|
||||||
|
currentPhase = (currentPhase + 1) % (kDigitCount + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
pinMode(kHvDataPin, OUTPUT);
|
||||||
|
pinMode(kHvClockPin, OUTPUT);
|
||||||
|
pinMode(kHvLatchPin, OUTPUT);
|
||||||
|
if (kHvBlankPin >= 0) {
|
||||||
|
pinMode(kHvBlankPin, OUTPUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
digitalWrite(kHvDataPin, LOW);
|
||||||
|
digitalWrite(kHvClockPin, HIGH);
|
||||||
|
digitalWrite(kHvLatchPin, HIGH);
|
||||||
|
setDisplayBlanked(true);
|
||||||
|
|
||||||
|
Serial.begin(kSerialBaud);
|
||||||
|
writeTextToDisplay("0");
|
||||||
|
blankDisplay();
|
||||||
|
|
||||||
|
Serial.println(F("HV5812P VFD controller ready."));
|
||||||
|
Serial.println(F("Send an integer followed by newline."));
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
pollSerial();
|
||||||
|
refreshDisplay();
|
||||||
|
}
|
||||||
59
config.example.json
Normal file
59
config.example.json
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
{
|
||||||
|
"debug": false,
|
||||||
|
|
||||||
|
"wifi_ssid": "MyNetwork",
|
||||||
|
"wifi_password": "MyPassword",
|
||||||
|
|
||||||
|
"mqtt_broker": "192.168.1.10",
|
||||||
|
"mqtt_port": 1883,
|
||||||
|
"mqtt_user": "mqtt_user",
|
||||||
|
"mqtt_password": "mqtt_password",
|
||||||
|
"mqtt_client_id": "gauge_controller",
|
||||||
|
"mqtt_prefix": "gauges",
|
||||||
|
|
||||||
|
"heartbeat_ms": 10000,
|
||||||
|
"rezero_interval_ms": 3600000,
|
||||||
|
|
||||||
|
"device": {
|
||||||
|
"name": "Selsyn Multi",
|
||||||
|
"model": "Chernobyl Selsyn-inspired gauge",
|
||||||
|
"manufacturer": "AdeBaumann",
|
||||||
|
"area": "Control Panels"
|
||||||
|
},
|
||||||
|
|
||||||
|
"arduino_uart": 1,
|
||||||
|
"arduino_tx_pin": 17,
|
||||||
|
"arduino_rx_pin": 16,
|
||||||
|
"arduino_baud": 115200,
|
||||||
|
|
||||||
|
"gauges": [
|
||||||
|
{
|
||||||
|
"name": "Gauge 1",
|
||||||
|
"entity_name": "Selsyn 1 Power",
|
||||||
|
"min": 0,
|
||||||
|
"max": 7300,
|
||||||
|
"max_steps": 4000,
|
||||||
|
"speed": 5000,
|
||||||
|
"acceleration": 6000,
|
||||||
|
"unit": "W",
|
||||||
|
"leds": {
|
||||||
|
"ws2812_red": [255, 0, 0],
|
||||||
|
"ws2812_green": [0, 255, 0]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Gauge 2",
|
||||||
|
"entity_name": "Selsyn 2 Power",
|
||||||
|
"min": 0,
|
||||||
|
"max": 7300,
|
||||||
|
"max_steps": 4000,
|
||||||
|
"speed": 5000,
|
||||||
|
"acceleration": 6000,
|
||||||
|
"unit": "W",
|
||||||
|
"leds": {
|
||||||
|
"ws2812_red": [255, 0, 0],
|
||||||
|
"ws2812_green": [0, 255, 0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
474
ota.py
Normal file
474
ota.py
Normal file
@@ -0,0 +1,474 @@
|
|||||||
|
"""
|
||||||
|
ota.py — Gitea OTA updater for ESP32 / MicroPython
|
||||||
|
|
||||||
|
Call ota.update() from boot.py before importing anything else.
|
||||||
|
If the update or the subsequent boot fails, the updater retries
|
||||||
|
on the next boot rather than bricking the device.
|
||||||
|
|
||||||
|
Strategy
|
||||||
|
--------
|
||||||
|
1. Check if last boot was good (OK flag exists).
|
||||||
|
2. If good, fetch remote commit SHA and compare with local — if unchanged,
|
||||||
|
skip file check entirely.
|
||||||
|
3. If new commit or failed boot, fetch ota_manifest.txt from the repo
|
||||||
|
to determine which files to sync.
|
||||||
|
4. Compare SHA1 hashes with a local manifest (.ota_manifest.json).
|
||||||
|
5. Download only changed or missing files, writing to .tmp first.
|
||||||
|
6. On success, rename .tmp files into place and update the manifest.
|
||||||
|
7. If anything fails mid-update, the manifest is not updated, so the
|
||||||
|
next boot will retry. Partially written .tmp files are cleaned up.
|
||||||
|
8. A "safety" flag file (.ota_ok) is written by main.py on successful
|
||||||
|
startup. If it is absent on boot, the previous update is suspected
|
||||||
|
bad — the manifest is wiped so all files are re-fetched cleanly.
|
||||||
|
|
||||||
|
Manifest format (ota_manifest.txt)
|
||||||
|
---------------------------------
|
||||||
|
Each line specifies a file or directory to include:
|
||||||
|
boot.py # specific file
|
||||||
|
ota.py # another file
|
||||||
|
selsyn/ # entire directory (trailing slash)
|
||||||
|
lib/ # another directory
|
||||||
|
*.py # wildcard (matches anywhere)
|
||||||
|
selsyn/*.py # wildcard in subdirectory
|
||||||
|
|
||||||
|
Usage in boot.py
|
||||||
|
----------------
|
||||||
|
import ota
|
||||||
|
ota.update()
|
||||||
|
# imports of main etc. go here
|
||||||
|
|
||||||
|
Configuration
|
||||||
|
-------------
|
||||||
|
Edit the block below, or override from a local config file
|
||||||
|
(see SETTINGS_FILE). All settings can be left as module-level
|
||||||
|
constants or placed in /ota_config.json:
|
||||||
|
{
|
||||||
|
"gitea_base": "http://git.baumann.gr",
|
||||||
|
"repo_owner": "adebaumann",
|
||||||
|
"repo_name": "HomeControlPanel",
|
||||||
|
"repo_folder": "firmware",
|
||||||
|
"repo_branch": "main",
|
||||||
|
"api_token": "nicetry-nothere"
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import gc
|
||||||
|
import sys
|
||||||
|
import ujson
|
||||||
|
import urequests
|
||||||
|
import utime
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Default configuration — override via /ota_config.json
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
GITEA_BASE = "http://git.baumann.gr" # no trailing slash
|
||||||
|
REPO_OWNER = "adrian"
|
||||||
|
REPO_NAME = "esp32-gauge"
|
||||||
|
REPO_FOLDER = "firmware" # folder inside repo to sync
|
||||||
|
REPO_BRANCH = "main"
|
||||||
|
API_TOKEN = None # set to string for private repos
|
||||||
|
|
||||||
|
WIFI_SSID = None
|
||||||
|
WIFI_PASSWORD = None
|
||||||
|
|
||||||
|
SETTINGS_FILE = "/ota_config.json"
|
||||||
|
MANIFEST_FILE = "/.ota_manifest.json"
|
||||||
|
OK_FLAG_FILE = "/.ota_ok"
|
||||||
|
OTA_MANIFEST = "ota_manifest.txt"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Logging
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _ts():
|
||||||
|
ms = utime.ticks_ms()
|
||||||
|
return f"{(ms // 3600000) % 24:02d}:{(ms // 60000) % 60:02d}:{(ms // 1000) % 60:02d}.{ms % 1000:03d}"
|
||||||
|
|
||||||
|
|
||||||
|
def _log(level, msg):
|
||||||
|
print(f"[{_ts()}] {level:5s} [OTA] {msg}")
|
||||||
|
|
||||||
|
|
||||||
|
def info(msg):
|
||||||
|
_log("INFO", msg)
|
||||||
|
|
||||||
|
|
||||||
|
def warn(msg):
|
||||||
|
_log("WARN", msg)
|
||||||
|
|
||||||
|
|
||||||
|
def log_err(msg):
|
||||||
|
_log("ERROR", msg)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# HTTP helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _headers():
|
||||||
|
h = {"Accept": "application/json"}
|
||||||
|
if API_TOKEN:
|
||||||
|
h["Authorization"] = f"token {API_TOKEN}"
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Config loader
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def load_config():
|
||||||
|
global \
|
||||||
|
GITEA_BASE, \
|
||||||
|
REPO_OWNER, \
|
||||||
|
REPO_NAME, \
|
||||||
|
REPO_FOLDER, \
|
||||||
|
REPO_BRANCH, \
|
||||||
|
API_TOKEN, \
|
||||||
|
WIFI_SSID, \
|
||||||
|
WIFI_PASSWORD
|
||||||
|
try:
|
||||||
|
with open(SETTINGS_FILE) as f:
|
||||||
|
cfg = ujson.load(f)
|
||||||
|
GITEA_BASE = cfg.get("gitea_base", GITEA_BASE)
|
||||||
|
REPO_OWNER = cfg.get("repo_owner", REPO_OWNER)
|
||||||
|
REPO_NAME = cfg.get("repo_name", REPO_NAME)
|
||||||
|
REPO_FOLDER = cfg.get("repo_folder", REPO_FOLDER)
|
||||||
|
REPO_BRANCH = cfg.get("repo_branch", REPO_BRANCH)
|
||||||
|
API_TOKEN = cfg.get("api_token", API_TOKEN)
|
||||||
|
WIFI_SSID = cfg.get("wifi_ssid", WIFI_SSID)
|
||||||
|
WIFI_PASSWORD = cfg.get("wifi_password", WIFI_PASSWORD)
|
||||||
|
info(f"Config loaded from {SETTINGS_FILE}")
|
||||||
|
except OSError:
|
||||||
|
info(f"No {SETTINGS_FILE} found — using defaults")
|
||||||
|
except Exception as e:
|
||||||
|
warn(f"Config parse error: {e} — using defaults")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _match_pattern(name, pattern):
|
||||||
|
if "*" not in pattern:
|
||||||
|
return name == pattern
|
||||||
|
i, n = 0, len(pattern)
|
||||||
|
j, m = 0, len(name)
|
||||||
|
star = -1
|
||||||
|
while i < n and j < m:
|
||||||
|
if pattern[i] == "*":
|
||||||
|
star = i
|
||||||
|
i += 1
|
||||||
|
elif pattern[i] == name[j]:
|
||||||
|
i += 1
|
||||||
|
j += 1
|
||||||
|
elif star >= 0:
|
||||||
|
i = star + 1
|
||||||
|
j += 1
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
while i < n and pattern[i] == "*":
|
||||||
|
i += 1
|
||||||
|
return i == n and j == m
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_commit_sha():
|
||||||
|
url = f"{GITEA_BASE}/api/v1/repos/{REPO_OWNER}/{REPO_NAME}/branches/{REPO_BRANCH}"
|
||||||
|
try:
|
||||||
|
r = urequests.get(url, headers=_headers())
|
||||||
|
if r.status_code == 200:
|
||||||
|
data = r.json()
|
||||||
|
r.close()
|
||||||
|
return data.get("commit", {}).get("id")
|
||||||
|
r.close()
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"Failed to fetch commit: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_manifest():
|
||||||
|
url = (
|
||||||
|
f"{GITEA_BASE}/api/v1/repos/{REPO_OWNER}/{REPO_NAME}"
|
||||||
|
f"/contents/{OTA_MANIFEST}?ref={REPO_BRANCH}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
r = urequests.get(url, headers=_headers())
|
||||||
|
try:
|
||||||
|
if r.status_code == 200:
|
||||||
|
data = r.json()
|
||||||
|
if data.get("content"):
|
||||||
|
import ubinascii
|
||||||
|
|
||||||
|
content = ubinascii.a2b_base64(data["content"]).decode()
|
||||||
|
patterns = [line.strip() for line in content.splitlines()]
|
||||||
|
return [p for p in patterns if p and not p.startswith("#")]
|
||||||
|
else:
|
||||||
|
warn(f"Manifest not found at {OTA_MANIFEST}")
|
||||||
|
finally:
|
||||||
|
r.close()
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"Failed to fetch manifest: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_dir(path):
|
||||||
|
url = (
|
||||||
|
f"{GITEA_BASE}/api/v1/repos/{REPO_OWNER}/{REPO_NAME}"
|
||||||
|
f"/contents/{path}?ref={REPO_BRANCH}"
|
||||||
|
)
|
||||||
|
return _api_get(url)
|
||||||
|
|
||||||
|
|
||||||
|
def _api_get(url):
|
||||||
|
"""GET a URL and return parsed JSON, or None on failure."""
|
||||||
|
try:
|
||||||
|
r = urequests.get(url, headers=_headers())
|
||||||
|
if r.status_code == 200:
|
||||||
|
data = r.json()
|
||||||
|
r.close()
|
||||||
|
return data
|
||||||
|
warn(f"HTTP {r.status_code} for {url}")
|
||||||
|
r.close()
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"GET {url} failed: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _download(url, dest_path):
|
||||||
|
"""Download url to dest_path. Returns True on success."""
|
||||||
|
tmp = dest_path + ".tmp"
|
||||||
|
try:
|
||||||
|
r = urequests.get(url, headers=_headers())
|
||||||
|
if r.status_code != 200:
|
||||||
|
warn(f"Download failed HTTP {r.status_code}: {url}")
|
||||||
|
r.close()
|
||||||
|
return False
|
||||||
|
with open(tmp, "wb") as f:
|
||||||
|
f.write(r.content)
|
||||||
|
r.close()
|
||||||
|
# Rename into place
|
||||||
|
try:
|
||||||
|
os.remove(dest_path)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
os.rename(tmp, dest_path)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"Download error {url}: {e}")
|
||||||
|
try:
|
||||||
|
os.remove(tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _load_manifest():
|
||||||
|
try:
|
||||||
|
with open(MANIFEST_FILE) as f:
|
||||||
|
return ujson.load(f)
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _save_manifest(manifest, commit_sha=None):
|
||||||
|
try:
|
||||||
|
with open(MANIFEST_FILE, "w") as f:
|
||||||
|
if commit_sha:
|
||||||
|
manifest["_commit"] = commit_sha
|
||||||
|
ujson.dump(manifest, f)
|
||||||
|
except Exception as e:
|
||||||
|
warn(f"Could not save manifest: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _ok_flag_exists():
|
||||||
|
try:
|
||||||
|
os.stat(OK_FLAG_FILE)
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_ok_flag():
|
||||||
|
try:
|
||||||
|
os.remove(OK_FLAG_FILE)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def mark_ok():
|
||||||
|
"""
|
||||||
|
Call this from main.py after successful startup.
|
||||||
|
Signals to the OTA updater that the last update was good.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with open(OK_FLAG_FILE, "w") as f:
|
||||||
|
f.write("ok")
|
||||||
|
except Exception as e:
|
||||||
|
warn(f"Could not write OK flag: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Core update logic
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_file_list():
|
||||||
|
"""
|
||||||
|
Returns list of {name, sha, download_url} dicts based on the
|
||||||
|
ota_manifest.txt patterns in the repo folder, or None on failure.
|
||||||
|
"""
|
||||||
|
manifest_patterns = _fetch_manifest()
|
||||||
|
if manifest_patterns is None:
|
||||||
|
log_err("No manifest — cannot determine what to fetch")
|
||||||
|
return None
|
||||||
|
|
||||||
|
info(f"Manifest patterns: {manifest_patterns}")
|
||||||
|
files = []
|
||||||
|
visited = set()
|
||||||
|
|
||||||
|
def fetch_matching(entries, patterns):
|
||||||
|
for entry in entries:
|
||||||
|
if entry.get("type") == "dir":
|
||||||
|
for p in patterns:
|
||||||
|
if p.endswith("/") and entry["name"].startswith(p.rstrip("/")):
|
||||||
|
sub = _fetch_dir(entry["path"])
|
||||||
|
if sub:
|
||||||
|
fetch_matching(sub, patterns)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
name = entry["name"]
|
||||||
|
for p in patterns:
|
||||||
|
p = p.rstrip("/")
|
||||||
|
if _match_pattern(name, p) or _match_pattern(entry["path"], p):
|
||||||
|
if entry["path"] not in visited:
|
||||||
|
visited.add(entry["path"])
|
||||||
|
files.append(
|
||||||
|
{
|
||||||
|
"name": entry["path"],
|
||||||
|
"sha": entry["sha"],
|
||||||
|
"download_url": entry["download_url"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
break
|
||||||
|
|
||||||
|
root = _fetch_dir(REPO_FOLDER)
|
||||||
|
if root is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
fetch_matching(root, manifest_patterns)
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def _do_update(commit_sha=None):
|
||||||
|
"""
|
||||||
|
Fetch file list, download changed files, update manifest.
|
||||||
|
Returns True if all succeeded (or nothing needed updating).
|
||||||
|
"""
|
||||||
|
info(
|
||||||
|
f"Checking {GITEA_BASE}/{REPO_OWNER}/{REPO_NAME}/{REPO_FOLDER} @ {REPO_BRANCH}"
|
||||||
|
)
|
||||||
|
file_list = _fetch_file_list()
|
||||||
|
if file_list is None:
|
||||||
|
log_err("Could not fetch file list — skipping update")
|
||||||
|
return False
|
||||||
|
|
||||||
|
info(f"Found {len(file_list)} file(s) to sync")
|
||||||
|
manifest = _load_manifest()
|
||||||
|
updated = []
|
||||||
|
failed = []
|
||||||
|
|
||||||
|
for entry in file_list:
|
||||||
|
name = entry["name"]
|
||||||
|
sha = entry["sha"]
|
||||||
|
|
||||||
|
if manifest.get(name) == sha:
|
||||||
|
info(f" {name} up to date")
|
||||||
|
continue
|
||||||
|
|
||||||
|
info(f" {name} updating (sha={sha[:8]}...)")
|
||||||
|
gc.collect()
|
||||||
|
ok = _download(entry["download_url"], f"/{name}")
|
||||||
|
if ok:
|
||||||
|
manifest[name] = sha
|
||||||
|
updated.append(name)
|
||||||
|
info(f" {name} OK")
|
||||||
|
else:
|
||||||
|
failed.append(name)
|
||||||
|
log_err(f" {name} FAILED")
|
||||||
|
|
||||||
|
if failed:
|
||||||
|
log_err(f"Update incomplete — {len(failed)} file(s) failed: {failed}")
|
||||||
|
_save_manifest(manifest, commit_sha)
|
||||||
|
return False
|
||||||
|
|
||||||
|
_save_manifest(manifest, commit_sha)
|
||||||
|
|
||||||
|
if updated:
|
||||||
|
info(f"Update complete — {len(updated)} file(s) updated: {updated}")
|
||||||
|
else:
|
||||||
|
info("All files up to date — nothing to do")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public entry point
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def update():
|
||||||
|
"""
|
||||||
|
Main entry point. Call from boot.py before importing application code.
|
||||||
|
|
||||||
|
- If the OK flag is missing, the previous boot is assumed to have
|
||||||
|
failed — wipes the manifest so everything is re-fetched cleanly.
|
||||||
|
- If the commit hash hasn't changed and last boot was good, skip
|
||||||
|
file comparison entirely.
|
||||||
|
- Runs the update.
|
||||||
|
- Clears the OK flag so main.py must re-assert it on successful start.
|
||||||
|
"""
|
||||||
|
info("=" * 40)
|
||||||
|
info("OTA updater starting")
|
||||||
|
info("=" * 40)
|
||||||
|
|
||||||
|
load_config()
|
||||||
|
|
||||||
|
ok_flag = _ok_flag_exists()
|
||||||
|
manifest = _load_manifest()
|
||||||
|
|
||||||
|
if not ok_flag:
|
||||||
|
warn("OK flag missing — last boot may have failed")
|
||||||
|
warn("Re-checking all files, will only download changed ones")
|
||||||
|
else:
|
||||||
|
info("OK flag present — last boot was good")
|
||||||
|
|
||||||
|
commit_sha = _fetch_commit_sha()
|
||||||
|
|
||||||
|
if ok_flag and commit_sha and manifest.get("_commit") == commit_sha:
|
||||||
|
info(f"Commit unchanged ({commit_sha[:8]}) — skipping file check")
|
||||||
|
info("-" * 40)
|
||||||
|
return
|
||||||
|
|
||||||
|
if commit_sha:
|
||||||
|
info(f"Remote commit: {commit_sha[:8]}")
|
||||||
|
else:
|
||||||
|
warn("Could not fetch remote commit — proceeding with file check")
|
||||||
|
|
||||||
|
# Clear the flag now; main.py must call ota.mark_ok() to re-set it
|
||||||
|
_clear_ok_flag()
|
||||||
|
|
||||||
|
success = _do_update(commit_sha)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
info("OTA check complete — booting application")
|
||||||
|
else:
|
||||||
|
warn("OTA check had errors — booting with current files")
|
||||||
|
|
||||||
|
info("-" * 40)
|
||||||
|
gc.collect()
|
||||||
9
ota_config.example.json
Normal file
9
ota_config.example.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"gitea_base": "http://git.baumann.gr",
|
||||||
|
"repo_owner": "adebaumann",
|
||||||
|
"repo_name": "Selsyn_inspired_gauge",
|
||||||
|
"repo_folder": "",
|
||||||
|
"repo_branch": "main",
|
||||||
|
"wifi_ssid": "YourNetwork",
|
||||||
|
"wifi_password": "YourPassword"
|
||||||
|
}
|
||||||
1
ota_manifest.txt
Normal file
1
ota_manifest.txt
Normal file
@@ -0,0 +1 @@
|
|||||||
|
*.py
|
||||||
Reference in New Issue
Block a user