# The Bib O'Tron project

A proof of concept for replacing the raspberry pi that is managing the bib button by an ESP32 microcontroller.

## Features

- Read the status of the bib button using a digital input
- Display the state of the bib button using a trafic lights
- Implement a HTTP server to serve :
  - A basic home page with some links
  - A bib button status page, that is meant to be included in the future static version of the [bib web site](https://lebib.org/)
    - CSS/images are not hosted locally (links to the [bib web site](https://www.lebib.org/))
  - A web OTA page to update the firmware through the network
  - A REST API to force the button state remotely
- Periodically pings a remote host and displays an error code on the RGB LED in case of failure (blinking orange color)
- Connects to the network through an RJ45 ethernet interface
- Implements Multicast DNS so that its IP address can be found through the bibotron.local name
- Can be powered by USB-C, using a 5V power supply connected to screw terminals or though the ethernet cable if the optional POE module is installed.

## Hardware

The microcontroller board used is a [Waveshare ESP32-S3-ETH](https://www.waveshare.com/wiki/ESP32-S3-ETH).  
The RGB LED is a WS2812

## /!\ Warning /!\

This board, doesn't have any protection between the USB 5V line and the POE 5V line. you MUST remove the POE module and/or disconnect the ethernet cable before plugging-in a USB cable, or else the proverbial magic smoke will be released!!!
(potentially on your computer side)

## Pictures

check [the pictures](doc/pictures.md) in the doc directory

## License

CC0 1.0 Universal
A copy of the license is in the LICENSE file

## User guide

### Changing the bibutton state physically from Le Bib

Juste operate the switch that is next to the traffic lighs.
**ToDo :** add a picture of the switch

### Changing the bibutton state remotely

In case the person who last closed Le Bib has forgotten to switch the bibutton state to the closed position, or if the physical switch is broken, it is possible to call a remote API to force the button state.
This can be done from the command line with curl as below :

- To force the bibutton to the closed state :
  ```
  curl -i -u "${bibutton_user}:${bibutton_password}" --request POST --data "{forceState:0}" --header "Content-Type: application/json" ${TARGET}
  ```
- To force the bibutton to the opened state :
  ```
  curl -i -u "${bibutton_user}:${bibutton_password}" --request POST --data "{forceState:0}" --header "Content-Type: application/json" ${TARGET}
  ```

**ToDo :** The user and password to use need to be stored in the password manager used by Le Bib

While the bibutton state is being remotely forced to a diffent state than the physical switch state, the red and green traffic lights will be both illuminated at the same time.
As soon as the the physical switch is changed to the same state as the remotely forced state, or the state is remotly forced back to the same state as the physical switch, the "remotly forced" mode will be canceled, and only the red or green light will be on, according the physical switch state.

### Traffic lights

Depending on the bibutton state, the traffic lights will be illuminated as follow :

- Red color (upper light) when the bibutton is closed,
- Green color (bottom light) when button is opened, Solid )
- Orange color (middle light) when the network is down (the last ping to the reverse proxy failed)
- Both Green and Red color at the same time when the bibutton state has been remotely forced to a diffent state than the physical switch

### LED light strip

This is work in progress.

The light strip currently displays the count of requests received to read the bibutton state since the last boot of the microntroller, as a 64 bits binary number.
And there is an effect with sliding LED from the right side to the left side, each time a new request is processed.  
It is also possible to change the LEDs through a REST API, that is only accessible from the local network. Check the scripts in the test directory to learn more.  
But note that the request count is frequently displayed to the LED strip, which will overwrite the least significant bits of whatever has been set through the API. Also the slifing effect will overwrite everything each time a request is processed.

The LED strip behavior is not functionally usefull for the Bibutton feature. You can hack it any way you want.

## Developer guide

The project is developed using the Arduino IDE and the following libraries :

- FastLED, to drive the addressable RGB LEDs
- EthernetESP32, to drive the SPI ethernet chip (W5500) of the ESP32-S3-ETH
- ESPping, to periodically check network connectivity
- ElegantOTA light, to updade the firmware through the network
- ArduinoJson, to parse json in the rest api handlers

Additionally to these libraries, the esp32 boards package must be installed in Arduino IDE.  
Then in the `Tools` menu, select :

- `Board` > `esp32` > `ESP32-S3-Box`
- `Partition scheme` > `16 MB Flash`
- `USB mode" > `Hardware CDC and JTAG`
- `Programmer` > `esptools`
- `Port` > the tty port of the board (if programming through USB)

Before building the project, you need to add in your working copy the secret.h file that contains the sensitive information that we not want to publish in the this git repository
**ToDo :** The secret.h needs to be stored in the password manager used by Le Bib
If your are building the source code for a different site than Le Bib, you can create your own secret.h based on secret.h.example

To update the firmware through Web OTA, first create the binary using the menu `Sketch` > `Export compiled Binary`.  


### Alternative: Compilation via Arduino CLI (Linux/Mac)

If you prefer the command line, you can use `arduino-cli`.

1.  **Install arduino-cli**:
    - **Mac**: `brew install arduino-cli`
    - **Linux**: Follow the [official installation guide](https://arduino.github.io/arduino-cli/latest/installation/).

2.  **Setup the ESP32 environment**:

    ```bash
    arduino-cli config init
    arduino-cli config add board_manager.additional_urls https://espressif.github.io/arduino-esp32/package_esp32_index.json
    arduino-cli core update-index
    arduino-cli core install esp32:esp32
    ```

3.  **Install the libraries**:

    ```bash
    arduino-cli lib install "FastLED" "EthernetESP32" "ESPping" "ElegantOTA" "ArduinoJson"
    ```

4.  **Compile the project for uploading through Web OTA**:
    ```bash
    arduino-cli compile --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc --build-property "build.partitions=default_16MB" --output-dir ./build  .
    ```

5.  **Compile the project and upload to the board through USB serial **: 
    To compile and upload a normal build :  
    ```bash
    arduino-cli compile --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc --build-property "build.partitions=default_16MB" && \
    arduino-cli upload -p /dev/ttyACM0 --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc
    ```

    To upload a debug build and debug locally from the command line with GDB :  
    ```bash
    arduino-cli compile --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc,DebugLevel=verbose --build-property "build.partitions=default_16MB" --build-property "build.code_debug=5" --optimize-for-debug  && \
    arduino-cli debug -p /dev/ttyACM0 --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc,DebugLevel=verbose
    ```

    To compile adebug build, upload it and debug remotely or from an IDE:  
    ```bash
    arduino-cli compile --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc,DebugLevel=verbose --build-property "build.partitions=default_16MB" --build-property "build.code_debug=5" --optimize-for-debug && \
    arduino-cli upload -p /dev/ttyACM0 --fqbn esp32:esp32:esp32s3box:USBMode=hwcdc,DebugLevel=verbose && \
    openocd -f ~/esp32s3-remote.cfg
    ```

ToDo : Need more detailed documentation for debugging
- how to install esptool
- how to install/configure openocd
- how to attach gdb to remote openocd
- how to attach to openocd from vs-code/vs-codium

### Update the firmware through Web OTA

- In your web browser, go to http://bibotron.local/update (or use the local IP address if the MDNS resolution of bibotron.local is not working, example : `http://10.13.12.40/update` )
- **ToDo :** The user and password to use need to be stored in the password manager used by Le Bib
- In `OTA Mode` select firmware
- Click on `Select file` and select the file `bibotron.ino.bin` that should have been generated somewhere under the project build folder (do not use any of the other .bin files that have been generated).
- Wait for the upload to complete.
- The ESP32 should automatically restart after the upgrade. (The LEDs and traffic lights will turn off for a while during the reset)
- Check on www.lebib.org that the bibutton state is correctly displayed
