Scénarios à plusieurs cartes
Scénarios à plusieurs cartes
Trois scénarios Bluetooth où chaque carte tient un rôle : un capteur mesure une distance, des relais la transmettent, un actionneur allume une LED. Chaque rôle a son croquis. Les annonces sont non connectables, sans réponse de scan, et identiques octet pour octet à celles des programmes MicroPython : une classe peut mêler des cartes des deux langages dans un même scénario. Chaque carte demande la pile radio (voir Bluetooth) ; les textes à l'écran et du moniteur série sont en anglais.
Deux défauts des programmes MicroPython sont gardés tels quels, pour que les réseaux mêlant les deux langages se comportent de la même façon. La distance vaut −1 quand le capteur ne voit rien, et les relais la prennent alors pour une présence proche. Le code d'un octet n'a pas le même sens dans les deux premiers scénarios : 0 veut dire « loin » dans le scénario 1 et « proche » dans le scénario 2. Ne pas faire tourner ces deux scénarios à portée l'un de l'autre.
Sur cette page :
- Scénario 1 : capteur
- Scénario 1 : relais
- Scénario 1 : actionneur
- Scénario 2 : capteur
- Scénario 2 : premier relais
- Scénario 2 : second relais
- Scénario 2 : actionneur
- Scénario 3 : périphérique P1
- Scénario 3 : périphérique P2
- Scénario 3 : périphérique P3
- Scénario 3 : relais R1
- Scénario 3 : relais R2
- Scénario 3 : relais R3
Scénario 1 : capteur
Le scénario 1 compte trois cartes : le capteur STeaMi-S, le relais STeaMi-R et l'actionneur STeaMi-A. Le capteur mesure la distance toutes les secondes et l'annonce : son nom, puis la distance en mm dans les données fabricant (entier signé de 2 octets, petit-boutiste, sans identifiant de fabricant). Chaque annonce dure 1 s, puis la carte se tait 200 ms.
Matériel : trois cartes, V1a, V1b ou V1c, une par rôle : celle-ci, Scénario 1 : relais et Scénario 1 : actionneur.
Ce qu'on observe : l'écran montre le nom, la distance et le courant de la batterie ; le moniteur série suit les annonces.
En MicroPython : scenario/scenario_1/peripheral_1.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 1 : capteur », portée du programme MicroPython
// scenario/scenario_1/peripheral_1 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_1/peripheral_1/main.py
//
// Nœud capteur « STeaMi-S » du scénario à un relais : capteur « STeaMi-S »,
// relais « STeaMi-R » (croquis scenario-1-relay), actionneur « STeaMi-A »
// (croquis scenario-1-peripheral-2). Il mesure la distance toutes les
// secondes et l'annonce en BLE, sans connexion possible : son nom, puis la
// distance en mm dans les données du fabricant (entier signé de 2 octets,
// petit-boutiste, sans identifiant de fabricant). Chaque annonce dure 1 s,
// puis la carte se tait 200 ms. L'écran montre le nom, la distance et le
// courant de la batterie ; le moniteur série (115200 bauds) suit les annonces.
//
// La trame est octet pour octet celle du programme MicroPython (ni Flags ni
// réponse de scan) : les cartes des deux langages se comprennent.
// Comme dans l'original, la distance vaut -1 quand le capteur ne voit rien :
// le relais la prend alors pour une présence proche.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiDistance.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-S";
const uint32_t ADV_MS = 1000; // durée d'une annonce
const uint32_t ADV_PAUSE_MS = 200; // silence entre deux annonces
const uint16_t ADV_INTERVAL = 240; // 150 ms, en pas de 0,625 ms
const uint32_t SENSOR_MS = 1000; // une mesure de distance par seconde
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
SteamiScreen screen;
SteamiDistance distance;
SteamiBattery battery;
int localDistance = 0; // mm
int16_t energyCurrent = 0; // mA
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
bool advertising = false;
uint32_t phaseStart = 0;
// La trame de advertising_payload() du programme MicroPython : le nom complet
// (type 0x09) puis les données du fabricant (type 0xFF), sans Flags.
int buildPayload(uint8_t* out, const char* name, const uint8_t* data, int n) {
int nameLen = strlen(name);
int i = 0;
out[i++] = nameLen + 1;
out[i++] = 0x09;
memcpy(out + i, name, nameLen);
i += nameLen;
out[i++] = n + 1;
out[i++] = 0xFF;
memcpy(out + i, data, n);
return i + n;
}
void startAdvertising() {
Serial.println("BLE Task: Advertising...");
uint8_t manData[2] = {(uint8_t)(localDistance & 0xFF), (uint8_t)((localDistance >> 8) & 0xFF)};
advData.setRawData(advPayload, buildPayload(advPayload, DEVICE_NAME, manData, 2));
BLE.setAdvertisingData(advData);
BLE.advertise();
advertising = true;
phaseStart = millis();
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
// Trois lignes centrées, espacées d'une hauteur de texte plus une marge
int y = u(50);
int step = screen.textHeight() + u(2);
char line[24];
screen.clear();
centered(DEVICE_NAME, DEVICE_NAME, y);
snprintf(line, sizeof line, "Me: %d", localDistance);
centered(line, "Me: XXX", y + step);
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + 2 * step);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
distance.begin();
battery.begin();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
localDistance = distance.read();
energyCurrent = battery.current();
startAdvertising();
}
void loop() {
static uint32_t lastSensor = millis(), lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
uint32_t now = millis();
if (advertising && now - phaseStart >= ADV_MS) {
BLE.stopAdvertise();
Serial.println("Advertisement timeout (non-connectable).");
advertising = false;
phaseStart = now;
} else if (!advertising && now - phaseStart >= ADV_PAUSE_MS) {
startAdvertising();
}
if (now - lastSensor >= SENSOR_MS) {
lastSensor = now;
localDistance = distance.read();
}
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 1 : relais
Le relais STeaMi-R écoute 500 ms les annonces des cartes STeaMi qui portent une distance et retient la dernière reçue d'un STeaMi-S. Il en tire une commande d'un octet, 0 au-delà de 300 mm, 1 sinon, qu'il annonce 500 ms sous son nom. Comme dans l'original, il attend encore 550 ms après la fin de l'écoute avant d'annoncer.
Matériel : trois cartes, V1a, V1b ou V1c (voir Scénario 1 : capteur).
Ce qu'on observe : la LED verte s'allume pour la commande 1 (présence proche), la rouge pour la commande 0. L'écran montre les 3 dernières cartes entendues et le courant de la batterie ; le moniteur série suit l'écoute et les annonces.
En MicroPython : scenario/scenario_1/relay.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 1 : relais », portée du programme MicroPython
// scenario/scenario_1/relay :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_1/relay/main.py
//
// Relais « STeaMi-R » du scénario à un relais : capteur « STeaMi-S »
// (croquis scenario-1-peripheral-1), relais « STeaMi-R », actionneur
// « STeaMi-A » (croquis scenario-1-peripheral-2). Il écoute 500 ms les
// annonces des cartes « STeaMi… » qui portent une distance (2 octets) et
// retient la dernière reçue d'un « STeaMi-S… ». Il en tire une commande d'un
// octet : 0 au-delà de 300 mm (LED rouge), 1 sinon (LED verte), qu'il
// annonce 500 ms sous son nom. L'écran montre les 3 dernières cartes
// entendues et le courant de la batterie ; le moniteur série (115200 bauds)
// suit le scan et les annonces.
//
// Les trames sont octet pour octet celles du programme MicroPython (ni Flags
// ni réponse de scan) : les cartes des deux langages se comprennent.
// Comme dans l'original, le relais attend encore 550 ms après la fin du scan
// avant d'annoncer, et une distance de -1 (le capteur ne voit rien) donne la
// commande 1 « proche ».
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-R";
const uint32_t SCAN_MS = 500; // durée de l'écoute
const uint32_t AFTER_SCAN_MS = SCAN_MS + 50; // pause de l'original après le scan
const uint32_t ADV_MS = 500; // durée de l'annonce de la commande
const uint32_t ADV_PAUSE_MS = 200; // silence après une annonce
const uint16_t ADV_INTERVAL = 240; // 150 ms, en pas de 0,625 ms
const int THRESHOLD_MM = 300; // au-delà : commande 0 « loin »
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
const int SHOWN = 3; // cartes affichées
SteamiScreen screen;
SteamiBattery battery;
int16_t energyCurrent = 0; // mA
bool hasForwarded = false; // forwarded_distance n'est pas None
int forwardedDistance = 0;
// devices_distances : dernière valeur reçue de chaque carte, avec son heure.
struct Seen {
bool used;
char name[32];
int value;
uint32_t ms;
};
const int MAX_SEEN = 8;
Seen seen[MAX_SEEN];
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, AFTER_SCAN, ADVERTISING, ADV_PAUSE };
Phase phase;
uint32_t phaseStart = 0;
// La trame de advertising_payload() du programme MicroPython : le nom complet
// (type 0x09) puis les données du fabricant (type 0xFF), sans Flags.
int buildPayload(uint8_t* out, const char* name, const uint8_t* data, int n) {
int nameLen = strlen(name);
int i = 0;
out[i++] = nameLen + 1;
out[i++] = 0x09;
memcpy(out + i, name, nameLen);
i += nameLen;
out[i++] = n + 1;
out[i++] = 0xFF;
memcpy(out + i, data, n);
return i + n;
}
// extract_manufacturer_data() : les octets du premier champ 0xFF de la trame.
int extractManufacturerData(const uint8_t* adv, int n, const uint8_t** data) {
int i = 0;
while (i + 1 < n) {
int length = adv[i];
if (length == 0) break;
if (adv[i + 1] == 0xFF) {
int end = min(i + 1 + length, n);
*data = adv + i + 2;
return max(end - (i + 2), 0);
}
i += 1 + length;
}
return 0;
}
void remember(const char* name, int value) {
int slot = -1, oldest = 0;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && strcmp(seen[i].name, name) == 0) { slot = i; break; }
if (!seen[i].used && slot < 0) slot = i;
if (seen[i].ms < seen[oldest].ms) oldest = i;
}
if (slot < 0) slot = oldest;
seen[slot].used = true;
strncpy(seen[slot].name, name, sizeof seen[slot].name - 1);
seen[slot].name[sizeof seen[slot].name - 1] = '\0';
seen[slot].value = value;
seen[slot].ms = millis();
}
void startScan() {
Serial.println("BLE Task: Starting scan...");
BLE.scan(true); // scan actif, avec les doublons
Serial.println("BLE Task: Scanning...");
phase = SCANNING;
phaseStart = millis();
}
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name.startsWith("STeaMi") && name != DEVICE_NAME) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
const uint8_t* man = nullptr;
if (extractManufacturerData(adv, n, &man) == 2) {
int distance = (int16_t)(man[0] | (man[1] << 8)); // struct.unpack("h")
remember(name.c_str(), distance);
Serial.print("Received from ");
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" mm");
if (name.startsWith("STeaMi-S")) {
forwardedDistance = distance;
hasForwarded = true;
}
}
}
d = BLE.available();
}
}
void ledsOff() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
}
void bleTask() {
uint32_t now = millis();
switch (phase) {
case SCANNING:
listen();
if (now - phaseStart >= SCAN_MS) {
BLE.stopScan();
phase = AFTER_SCAN;
phaseStart = now;
}
break;
case AFTER_SCAN:
if (now - phaseStart < AFTER_SCAN_MS) break;
Serial.println("BLE Task: Advertising...");
if (!hasForwarded) {
startScan();
break;
}
{
uint8_t command;
if (forwardedDistance > THRESHOLD_MM) {
command = 0;
digitalWrite(LED_RED, HIGH);
} else {
command = 1;
digitalWrite(LED_GREEN, HIGH);
}
advData.setRawData(advPayload, buildPayload(advPayload, DEVICE_NAME, &command, 1));
BLE.setAdvertisingData(advData);
BLE.advertise();
}
phase = ADVERTISING;
phaseStart = now;
break;
case ADVERTISING:
if (now - phaseStart < ADV_MS) break;
BLE.stopAdvertise();
Serial.println("Advertisement timeout (non-connectable).");
ledsOff();
hasForwarded = false;
phase = ADV_PAUSE;
phaseStart = now;
break;
case ADV_PAUSE:
if (now - phaseStart >= ADV_PAUSE_MS) startScan();
break;
}
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// Les cartes entendues le plus récemment d'abord
bool shown[MAX_SEEN] = {};
// Une hauteur de texte plus une marge entre deux lignes
int y = u(36);
int step = screen.textHeight() + u(2);
char line[48];
for (int k = 0; k < SHOWN; k++) {
int best = -1;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && !shown[i] && (best < 0 || seen[i].ms > seen[best].ms)) best = i;
}
if (best < 0) break;
shown[best] = true;
const char* name = seen[best].name;
int len = strlen(name);
snprintf(line, sizeof line, "%s: %d", len > 4 ? name + len - 4 : name, seen[best].value); // name[-4:]
centered(line, "XXXX: XXX", y);
y += step;
}
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + u(5));
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
battery.begin();
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
ledsOff();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
energyCurrent = battery.current();
startScan();
}
void loop() {
static uint32_t lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
bleTask();
uint32_t now = millis();
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 1 : actionneur
L'actionneur STeaMi-A écoute 500 ms. Quand un STeaMi-R annonce une commande d'un octet, il fait clignoter 200 ms la LED verte (commande 1 : présence proche) ou la LED rouge (sinon). Il garde aussi les distances des cartes STeaMi qu'il entend directement.
Matériel : trois cartes, V1a, V1b ou V1c (voir Scénario 1 : capteur).
Ce qu'on observe : la LED clignote en vert quand un objet est à moins de 300 mm du capteur, en rouge sinon. L'écran montre les 3 dernières cartes entendues et le courant de la batterie ; le moniteur série suit l'écoute et les commandes.
En MicroPython : scenario/scenario_1/peripheral_2.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 1 : actionneur », portée du programme MicroPython
// scenario/scenario_1/peripheral_2 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_1/peripheral_2/main.py
//
// Actionneur « STeaMi-A » du scénario à un relais : capteur « STeaMi-S »
// (croquis scenario-1-peripheral-1), relais « STeaMi-R » (croquis
// scenario-1-relay), actionneur « STeaMi-A ». Il écoute 500 ms. Si un
// « STeaMi-R… » annonce une commande d'un octet, il fait clignoter 200 ms la
// LED verte (commande 1 : présence proche) ou la LED rouge (sinon). Il garde
// aussi les distances (2 octets) des cartes « STeaMi… » qu'il entend
// directement. L'écran montre les 3 dernières et le courant de la batterie ;
// le moniteur série (115200 bauds) suit le scan et les commandes.
//
// Il lit les trames du programme MicroPython octet pour octet : les cartes
// des deux langages se comprennent. Comme dans l'original, il attend encore
// 550 ms après la fin du scan avant d'allumer la LED.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-A";
const uint32_t SCAN_MS = 500; // durée de l'écoute
const uint32_t AFTER_SCAN_MS = SCAN_MS + 50; // pause de l'original après le scan
const uint32_t BLINK_MS = 200; // durée du clignotement
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
const int SHOWN = 3; // cartes affichées
SteamiScreen screen;
SteamiBattery battery;
int16_t energyCurrent = 0; // mA
bool hasPresence = false; // forwarded_presence n'est pas None
uint8_t forwardedPresence = 0;
// devices_distances : dernière valeur reçue de chaque carte, avec son heure.
struct Seen {
bool used;
char name[32];
int value;
uint32_t ms;
};
const int MAX_SEEN = 8;
Seen seen[MAX_SEEN];
enum Phase { SCANNING, AFTER_SCAN, BLINK };
Phase phase;
uint32_t phaseStart = 0;
// extract_manufacturer_data() : les octets du premier champ 0xFF de la trame.
int extractManufacturerData(const uint8_t* adv, int n, const uint8_t** data) {
int i = 0;
while (i + 1 < n) {
int length = adv[i];
if (length == 0) break;
if (adv[i + 1] == 0xFF) {
int end = min(i + 1 + length, n);
*data = adv + i + 2;
return max(end - (i + 2), 0);
}
i += 1 + length;
}
return 0;
}
void remember(const char* name, int value) {
int slot = -1, oldest = 0;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && strcmp(seen[i].name, name) == 0) { slot = i; break; }
if (!seen[i].used && slot < 0) slot = i;
if (seen[i].ms < seen[oldest].ms) oldest = i;
}
if (slot < 0) slot = oldest;
seen[slot].used = true;
strncpy(seen[slot].name, name, sizeof seen[slot].name - 1);
seen[slot].name[sizeof seen[slot].name - 1] = '\0';
seen[slot].value = value;
seen[slot].ms = millis();
}
void startScan() {
Serial.println("BLE Task: Starting scan...");
BLE.scan(true); // scan actif, avec les doublons
Serial.println("BLE Task: Scanning...");
phase = SCANNING;
phaseStart = millis();
}
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name.startsWith("STeaMi") && name != DEVICE_NAME) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
const uint8_t* man = nullptr;
int manLen = extractManufacturerData(adv, n, &man);
if (manLen == 2) {
int distance = (int16_t)(man[0] | (man[1] << 8)); // struct.unpack("h")
remember(name.c_str(), distance);
Serial.print("Received from ");
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" mm");
}
if (manLen == 1 && name.startsWith("STeaMi-R")) {
forwardedPresence = man[0];
hasPresence = true;
char repr[12];
snprintf(repr, sizeof repr, "b'\\x%02x'", forwardedPresence); // comme print(bytes)
Serial.print("Received presence from ");
Serial.print(name);
Serial.print(": ");
Serial.println(repr);
}
}
d = BLE.available();
}
}
void ledsOff() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
}
void bleTask() {
uint32_t now = millis();
switch (phase) {
case SCANNING:
listen();
if (now - phaseStart >= SCAN_MS) {
BLE.stopScan();
phase = AFTER_SCAN;
phaseStart = now;
}
break;
case AFTER_SCAN:
if (now - phaseStart < AFTER_SCAN_MS) break;
if (!hasPresence) {
startScan();
break;
}
if (forwardedPresence == 0x01) {
digitalWrite(LED_GREEN, HIGH);
Serial.println("Presence detected!");
} else {
digitalWrite(LED_RED, HIGH);
Serial.println("No presence detected.");
}
phase = BLINK;
phaseStart = now;
break;
case BLINK:
if (now - phaseStart < BLINK_MS) break;
ledsOff();
hasPresence = false;
startScan();
break;
}
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// Les cartes entendues le plus récemment d'abord
bool shown[MAX_SEEN] = {};
// Une hauteur de texte plus une marge entre deux lignes
int y = u(36);
int step = screen.textHeight() + u(2);
char line[48];
for (int k = 0; k < SHOWN; k++) {
int best = -1;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && !shown[i] && (best < 0 || seen[i].ms > seen[best].ms)) best = i;
}
if (best < 0) break;
shown[best] = true;
const char* name = seen[best].name;
int len = strlen(name);
snprintf(line, sizeof line, "%s: %d", len > 4 ? name + len - 4 : name, seen[best].value); // name[-4:]
centered(line, "XXXX: XXX", y);
y += step;
}
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + u(5));
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
battery.begin();
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
ledsOff();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
energyCurrent = battery.current();
startScan();
}
void loop() {
static uint32_t lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
bleTask();
uint32_t now = millis();
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 2 : capteur
Le scénario 2 compte quatre cartes : le capteur STeaMi-S, le premier relais STeaMi-R1, le second relais STeaMi-R2 et l'actionneur STeaMi-A. Le capteur est celui du scénario 1, avec un écran redessiné toutes les 0,3 s au lieu de 0,5 s.
Matériel : quatre cartes, V1a, V1b ou V1c, une par rôle : celle-ci, Scénario 2 : premier relais, Scénario 2 : second relais et Scénario 2 : actionneur.
Ce qu'on observe : l'écran montre le nom, la distance et le courant de la batterie ; le moniteur série suit les annonces.
En MicroPython : scenario/scenario_2/peripheral_1.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 2 : capteur », portée du programme MicroPython
// scenario/scenario_2/peripheral_1 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_2/peripheral_1/main.py
//
// Nœud capteur « STeaMi-S » du scénario à deux relais : capteur « STeaMi-S »,
// relais « STeaMi-R1 » (croquis scenario-2-relay-1), relais « STeaMi-R2 »
// (croquis scenario-2-relay-2), actionneur « STeaMi-A » (croquis
// scenario-2-peripheral-2). Il mesure la distance toutes les secondes et
// l'annonce en BLE, sans connexion possible : son nom, puis la distance en mm
// dans les données du fabricant (entier signé de 2 octets, petit-boutiste,
// sans identifiant de fabricant). Chaque annonce dure 1 s, puis la carte se
// tait 200 ms. L'écran montre le nom, la distance et le courant de la
// batterie ; le moniteur série (115200 bauds) suit les annonces.
//
// C'est le capteur du scénario 1 (croquis scenario-1-peripheral-1), avec un
// écran redessiné toutes les 0,3 s au lieu de 0,5 s.
// La trame est octet pour octet celle du programme MicroPython (ni Flags ni
// réponse de scan) : les cartes des deux langages se comprennent.
// Comme dans l'original, la distance vaut -1 quand le capteur ne voit rien :
// le relais R1 la classe alors à moins de 300 mm.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiDistance.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-S";
const uint32_t ADV_MS = 1000; // durée d'une annonce
const uint32_t ADV_PAUSE_MS = 200; // silence entre deux annonces
const uint16_t ADV_INTERVAL = 240; // 150 ms, en pas de 0,625 ms
const uint32_t SENSOR_MS = 1000; // une mesure de distance par seconde
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 300; // l'écran est redessiné toutes les 0,3 s
SteamiScreen screen;
SteamiDistance distance;
SteamiBattery battery;
int localDistance = 0; // mm
int16_t energyCurrent = 0; // mA
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
bool advertising = false;
uint32_t phaseStart = 0;
// La trame de advertising_payload() du programme MicroPython : le nom complet
// (type 0x09) puis les données du fabricant (type 0xFF), sans Flags.
int buildPayload(uint8_t* out, const char* name, const uint8_t* data, int n) {
int nameLen = strlen(name);
int i = 0;
out[i++] = nameLen + 1;
out[i++] = 0x09;
memcpy(out + i, name, nameLen);
i += nameLen;
out[i++] = n + 1;
out[i++] = 0xFF;
memcpy(out + i, data, n);
return i + n;
}
void startAdvertising() {
Serial.println("BLE Task: Advertising...");
uint8_t manData[2] = {(uint8_t)(localDistance & 0xFF), (uint8_t)((localDistance >> 8) & 0xFF)};
advData.setRawData(advPayload, buildPayload(advPayload, DEVICE_NAME, manData, 2));
BLE.setAdvertisingData(advData);
BLE.advertise();
advertising = true;
phaseStart = millis();
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
// Trois lignes centrées, espacées d'une hauteur de texte plus une marge
int y = u(50);
int step = screen.textHeight() + u(2);
char line[24];
screen.clear();
centered(DEVICE_NAME, DEVICE_NAME, y);
snprintf(line, sizeof line, "Me: %d", localDistance);
centered(line, "Me: XXX", y + step);
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + 2 * step);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
distance.begin();
battery.begin();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
localDistance = distance.read();
energyCurrent = battery.current();
startAdvertising();
}
void loop() {
static uint32_t lastSensor = millis(), lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
uint32_t now = millis();
if (advertising && now - phaseStart >= ADV_MS) {
BLE.stopAdvertise();
Serial.println("Advertisement timeout (non-connectable).");
advertising = false;
phaseStart = now;
} else if (!advertising && now - phaseStart >= ADV_PAUSE_MS) {
startAdvertising();
}
if (now - lastSensor >= SENSOR_MS) {
lastSensor = now;
localDistance = distance.read();
}
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 2 : premier relais
Le premier relais STeaMi-R1 écoute 500 ms les cartes STeaMi qui portent une distance et retient la dernière reçue d'un STeaMi-S. Il la classe sur trois niveaux, 0 sous 300 mm, 1 sous 600 mm, 2 au-delà, et annonce ce code d'un octet 500 ms sous son nom.
Matériel : quatre cartes, V1a, V1b ou V1c (voir Scénario 2 : capteur).
Ce qu'on observe : la LED rouge s'allume pour le code 0, la verte pour le code 1, la bleue pour le code 2. L'écran montre les 4 dernières cartes entendues et le courant de la batterie ; le moniteur série suit l'écoute et les annonces.
En MicroPython : scenario/scenario_2/relay_1.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 2 : premier relais », portée du programme MicroPython
// scenario/scenario_2/relay_1 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_2/relay_1/main.py
//
// Premier relais « STeaMi-R1 » du scénario à deux relais : capteur
// « STeaMi-S » (croquis scenario-2-peripheral-1), relais « STeaMi-R1 »,
// relais « STeaMi-R2 » (croquis scenario-2-relay-2), actionneur « STeaMi-A »
// (croquis scenario-2-peripheral-2). Il écoute 500 ms les annonces des cartes
// « STeaMi… » qui portent une distance (2 octets) et retient la dernière
// reçue d'un « STeaMi-S… ». Il la classe sur trois niveaux : 0 sous 300 mm
// (LED rouge), 1 sous 600 mm (LED verte), 2 au-delà (LED bleue), et annonce
// ce code d'un octet 500 ms sous son nom. L'écran montre les 4 dernières
// cartes entendues et le courant de la batterie ; le moniteur série
// (115200 bauds) suit le scan et les annonces.
//
// Les trames sont octet pour octet celles du programme MicroPython (ni Flags
// ni réponse de scan) : les cartes des deux langages se comprennent.
// Attention : le code 0 veut dire « proche » ici, et « loin » dans le
// scénario 1 ; ne pas faire tourner les deux scénarios à portée l'un de
// l'autre. Comme dans l'original, le relais attend encore 550 ms après la fin
// du scan avant d'annoncer, puis 200 ms à chaque tour, et une distance de -1
// (le capteur ne voit rien) donne le code 0.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-R1";
const uint32_t SCAN_MS = 500; // durée de l'écoute
const uint32_t AFTER_SCAN_MS = SCAN_MS + 50; // pause de l'original après le scan
const uint32_t ADV_MS = 500; // durée de l'annonce de la commande
const uint32_t ADV_PAUSE_MS = 200; // silence à la fin de chaque tour
const uint16_t ADV_INTERVAL = 240; // 150 ms, en pas de 0,625 ms
const int NEAR_MM = 300; // en dessous : code 0, LED rouge
const int MIDDLE_MM = 600; // en dessous : code 1, LED verte ; au-delà : code 2, LED bleue
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 300; // l'écran est redessiné toutes les 0,3 s
const int SHOWN = 4; // cartes affichées
SteamiScreen screen;
SteamiBattery battery;
int16_t energyCurrent = 0; // mA
bool hasForwarded = false; // forwarded_distance n'est pas None
int forwardedDistance = 0;
// devices_distances : dernière valeur reçue de chaque carte, avec son heure.
struct Seen {
bool used;
char name[32];
int value;
uint32_t ms;
};
const int MAX_SEEN = 8;
Seen seen[MAX_SEEN];
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, AFTER_SCAN, ADVERTISING, ADV_PAUSE };
Phase phase;
uint32_t phaseStart = 0;
// La trame de advertising_payload() du programme MicroPython : le nom complet
// (type 0x09) puis les données du fabricant (type 0xFF), sans Flags.
int buildPayload(uint8_t* out, const char* name, const uint8_t* data, int n) {
int nameLen = strlen(name);
int i = 0;
out[i++] = nameLen + 1;
out[i++] = 0x09;
memcpy(out + i, name, nameLen);
i += nameLen;
out[i++] = n + 1;
out[i++] = 0xFF;
memcpy(out + i, data, n);
return i + n;
}
// extract_manufacturer_data() : les octets du premier champ 0xFF de la trame.
int extractManufacturerData(const uint8_t* adv, int n, const uint8_t** data) {
int i = 0;
while (i + 1 < n) {
int length = adv[i];
if (length == 0) break;
if (adv[i + 1] == 0xFF) {
int end = min(i + 1 + length, n);
*data = adv + i + 2;
return max(end - (i + 2), 0);
}
i += 1 + length;
}
return 0;
}
void remember(const char* name, int value) {
int slot = -1, oldest = 0;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && strcmp(seen[i].name, name) == 0) { slot = i; break; }
if (!seen[i].used && slot < 0) slot = i;
if (seen[i].ms < seen[oldest].ms) oldest = i;
}
if (slot < 0) slot = oldest;
seen[slot].used = true;
strncpy(seen[slot].name, name, sizeof seen[slot].name - 1);
seen[slot].name[sizeof seen[slot].name - 1] = '\0';
seen[slot].value = value;
seen[slot].ms = millis();
}
void startScan() {
Serial.println("BLE Task: Scanning...");
BLE.scan(true); // scan actif, avec les doublons
phase = SCANNING;
phaseStart = millis();
}
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name.startsWith("STeaMi") && name != DEVICE_NAME) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
const uint8_t* man = nullptr;
if (extractManufacturerData(adv, n, &man) == 2) {
int distance = (int16_t)(man[0] | (man[1] << 8)); // struct.unpack("h")
remember(name.c_str(), distance);
Serial.print("Received from ");
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" mm");
if (name.startsWith("STeaMi-S")) {
forwardedDistance = distance;
hasForwarded = true;
}
}
}
d = BLE.available();
}
}
void ledsOff() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_BLUE, LOW);
}
void bleTask() {
uint32_t now = millis();
switch (phase) {
case SCANNING:
listen();
if (now - phaseStart >= SCAN_MS) {
BLE.stopScan();
phase = AFTER_SCAN;
phaseStart = now;
}
break;
case AFTER_SCAN:
if (now - phaseStart < AFTER_SCAN_MS) break;
if (!hasForwarded) {
phase = ADV_PAUSE;
phaseStart = now;
break;
}
Serial.print(DEVICE_NAME);
Serial.print(" advertising distance: ");
Serial.print(forwardedDistance);
Serial.println(" mm");
{
uint8_t code;
if (forwardedDistance < NEAR_MM) {
code = 0;
digitalWrite(LED_RED, HIGH);
} else if (forwardedDistance < MIDDLE_MM) {
code = 1;
digitalWrite(LED_GREEN, HIGH);
} else {
code = 2;
digitalWrite(LED_BLUE, HIGH);
}
advData.setRawData(advPayload, buildPayload(advPayload, DEVICE_NAME, &code, 1));
BLE.setAdvertisingData(advData);
BLE.advertise();
}
phase = ADVERTISING;
phaseStart = now;
break;
case ADVERTISING:
if (now - phaseStart < ADV_MS) break;
BLE.stopAdvertise();
Serial.println("Advertisement timeout.");
ledsOff();
hasForwarded = false;
phase = ADV_PAUSE;
phaseStart = now;
break;
case ADV_PAUSE:
if (now - phaseStart >= ADV_PAUSE_MS) startScan();
break;
}
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// Les cartes entendues le plus récemment d'abord
bool shown[MAX_SEEN] = {};
// Une hauteur de texte plus une marge entre deux lignes
int y = u(40);
int step = screen.textHeight() + u(2);
char line[48];
for (int k = 0; k < SHOWN; k++) {
int best = -1;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && !shown[i] && (best < 0 || seen[i].ms > seen[best].ms)) best = i;
}
if (best < 0) break;
shown[best] = true;
const char* name = seen[best].name;
int len = strlen(name);
snprintf(line, sizeof line, "%s: %d", len > 4 ? name + len - 4 : name, seen[best].value); // name[-4:]
centered(line, "XXXX: XXX", y);
y += step;
}
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + u(5));
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
battery.begin();
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
ledsOff();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
energyCurrent = battery.current();
startScan();
}
void loop() {
static uint32_t lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
bleTask();
uint32_t now = millis();
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 2 : second relais
Le second relais STeaMi-R2 écoute 500 ms le code d'un octet d'un STeaMi-R (en pratique R1), allume la LED qui lui correspond et réannonce ce code 500 ms sous son nom. Tout code autre que 0 et 1 est réannoncé comme 2.
Matériel : quatre cartes, V1a, V1b ou V1c (voir Scénario 2 : capteur).
Ce qu'on observe : la LED rouge (0), verte (1) ou bleue (2) reprend celle du premier relais. L'écran montre le courant de la batterie et les 4 dernières cartes entendues, avec leur distance ou le code reçu d'un relais.
En MicroPython : scenario/scenario_2/relay_2.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 2 : second relais », portée du programme MicroPython
// scenario/scenario_2/relay_2 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_2/relay_2/main.py
//
// Second relais « STeaMi-R2 » du scénario à deux relais : capteur
// « STeaMi-S » (croquis scenario-2-peripheral-1), relais « STeaMi-R1 »
// (croquis scenario-2-relay-1), relais « STeaMi-R2 », actionneur
// « STeaMi-A » (croquis scenario-2-peripheral-2). Il écoute 500 ms le code
// d'un octet d'un « STeaMi-R… » (en pratique R1), allume la LED qui lui
// correspond (0 rouge, 1 verte, sinon bleue) et réannonce ce code 500 ms
// sous son nom. L'écran montre le courant de la batterie et les 4 dernières
// cartes entendues (distance, ou code reçu d'un relais) ; le moniteur série
// (115200 bauds) suit le scan et les annonces.
//
// Les trames sont octet pour octet celles du programme MicroPython (ni Flags
// ni réponse de scan) : les cartes des deux langages se comprennent.
// Comme dans l'original, le relais attend encore 550 ms après la fin du scan
// avant d'annoncer, puis 200 ms à chaque tour, et tout code autre que 0 et 1
// est réannoncé comme 2.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-R2";
const uint32_t SCAN_MS = 500; // durée de l'écoute
const uint32_t AFTER_SCAN_MS = SCAN_MS + 50; // pause de l'original après le scan
const uint32_t ADV_MS = 500; // durée de l'annonce de la commande
const uint32_t ADV_PAUSE_MS = 200; // silence à la fin de chaque tour
const uint16_t ADV_INTERVAL = 240; // 150 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // courant lu et écran redessiné toutes les 0,5 s
const int SHOWN = 4; // cartes affichées
SteamiScreen screen;
SteamiBattery battery;
int16_t energyValue = 0; // mA
bool hasPresence = false; // forwarded_presence n'est pas None
int forwardedPresence = 0;
// devices_distances : dernière valeur reçue de chaque carte, avec son heure.
struct Seen {
bool used;
char name[32];
int value;
uint32_t ms;
};
const int MAX_SEEN = 8;
Seen seen[MAX_SEEN];
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, AFTER_SCAN, ADVERTISING, ADV_PAUSE };
Phase phase;
uint32_t phaseStart = 0;
// La trame de advertising_payload() du programme MicroPython : le nom complet
// (type 0x09) puis les données du fabricant (type 0xFF), sans Flags.
int buildPayload(uint8_t* out, const char* name, const uint8_t* data, int n) {
int nameLen = strlen(name);
int i = 0;
out[i++] = nameLen + 1;
out[i++] = 0x09;
memcpy(out + i, name, nameLen);
i += nameLen;
out[i++] = n + 1;
out[i++] = 0xFF;
memcpy(out + i, data, n);
return i + n;
}
// extract_manufacturer_data() : les octets du premier champ 0xFF de la trame.
int extractManufacturerData(const uint8_t* adv, int n, const uint8_t** data) {
int i = 0;
while (i + 1 < n) {
int length = adv[i];
if (length == 0) break;
if (adv[i + 1] == 0xFF) {
int end = min(i + 1 + length, n);
*data = adv + i + 2;
return max(end - (i + 2), 0);
}
i += 1 + length;
}
return 0;
}
void remember(const char* name, int value) {
int slot = -1, oldest = 0;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && strcmp(seen[i].name, name) == 0) { slot = i; break; }
if (!seen[i].used && slot < 0) slot = i;
if (seen[i].ms < seen[oldest].ms) oldest = i;
}
if (slot < 0) slot = oldest;
seen[slot].used = true;
strncpy(seen[slot].name, name, sizeof seen[slot].name - 1);
seen[slot].name[sizeof seen[slot].name - 1] = '\0';
seen[slot].value = value;
seen[slot].ms = millis();
}
void startScan() {
Serial.println("BLE Task: Scanning...");
BLE.scan(true); // scan actif, avec les doublons
phase = SCANNING;
phaseStart = millis();
}
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name.startsWith("STeaMi") && name != DEVICE_NAME) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
const uint8_t* man = nullptr;
int manLen = extractManufacturerData(adv, n, &man);
if (manLen == 2) {
int distance = (int16_t)(man[0] | (man[1] << 8)); // struct.unpack("h")
remember(name.c_str(), distance);
Serial.print("Received from ");
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" mm");
}
if (manLen == 1 && name.startsWith("STeaMi-R")) {
forwardedPresence = (int8_t)man[0]; // struct.unpack("b")
hasPresence = true;
remember(name.c_str(), forwardedPresence);
Serial.print("Received presence from ");
Serial.print(name);
Serial.print(": ");
Serial.println(forwardedPresence);
}
}
d = BLE.available();
}
}
void ledsOff() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_BLUE, LOW);
}
void bleTask() {
uint32_t now = millis();
switch (phase) {
case SCANNING:
listen();
if (now - phaseStart >= SCAN_MS) {
BLE.stopScan();
phase = AFTER_SCAN;
phaseStart = now;
}
break;
case AFTER_SCAN:
if (now - phaseStart < AFTER_SCAN_MS) break;
if (!hasPresence) {
phase = ADV_PAUSE;
phaseStart = now;
break;
}
Serial.print(DEVICE_NAME);
Serial.print(" advertising presence: ");
Serial.println(forwardedPresence);
{
// Indicateur lumineux selon la présence
uint8_t code;
if (forwardedPresence == 0) {
code = 0;
digitalWrite(LED_RED, HIGH);
} else if (forwardedPresence == 1) {
code = 1;
digitalWrite(LED_GREEN, HIGH);
} else {
code = 2;
digitalWrite(LED_BLUE, HIGH);
}
advData.setRawData(advPayload, buildPayload(advPayload, DEVICE_NAME, &code, 1));
BLE.setAdvertisingData(advData);
BLE.advertise();
}
phase = ADVERTISING;
phaseStart = now;
break;
case ADVERTISING:
if (now - phaseStart < ADV_MS) break;
BLE.stopAdvertise();
Serial.println("Advertisement timeout.");
ledsOff();
hasPresence = false;
phase = ADV_PAUSE;
phaseStart = now;
break;
case ADV_PAUSE:
if (now - phaseStart >= ADV_PAUSE_MS) startScan();
break;
}
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
// Lecture du courant de la batterie
energyValue = battery.current();
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// Afficher le courant
char line[48];
snprintf(line, sizeof line, "E:%d.00 mA", energyValue); // .2f d'un entier
centered(line, "E:000.00 mA", u(34));
// Les cartes entendues le plus récemment d'abord
bool shown[MAX_SEEN] = {};
// Une hauteur de texte plus une marge entre deux lignes
int y = u(48);
int step = screen.textHeight() + u(2);
for (int k = 0; k < SHOWN; k++) {
int best = -1;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && !shown[i] && (best < 0 || seen[i].ms > seen[best].ms)) best = i;
}
if (best < 0) break;
shown[best] = true;
const char* name = seen[best].name;
int len = strlen(name);
snprintf(line, sizeof line, "%s: %d", len > 4 ? name + len - 4 : name, seen[best].value); // name[-4:]
centered(line, "XXXX: XXX", y);
y += step;
}
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
battery.begin();
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
ledsOff();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
startScan();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
uint32_t now = millis();
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 2 : actionneur
L'actionneur STeaMi-A écoute 500 ms le code d'un octet de STeaMi-R2 et fait clignoter 200 ms la LED rouge (0 : sous 300 mm), verte (1 : de 300 à 600 mm) ou bleue (2 : au-delà de 600 mm). Comme dans l'original, il n'écoute que R2, ce qui oblige le message à passer par les deux relais.
Matériel : quatre cartes, V1a, V1b ou V1c (voir Scénario 2 : capteur).
Ce qu'on observe : la couleur de la LED suit la distance mesurée par le capteur, avec le retard des deux relais. L'écran montre les 4 dernières cartes entendues et le courant de la batterie.
En MicroPython : scenario/scenario_2/peripheral_2.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 2 : actionneur », portée du programme MicroPython
// scenario/scenario_2/peripheral_2 :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_2/peripheral_2/main.py
//
// Actionneur « STeaMi-A » du scénario à deux relais : capteur « STeaMi-S »
// (croquis scenario-2-peripheral-1), relais « STeaMi-R1 » (croquis
// scenario-2-relay-1), relais « STeaMi-R2 » (croquis scenario-2-relay-2),
// actionneur « STeaMi-A ». Il écoute 500 ms le code d'un octet de
// « STeaMi-R2… » et fait clignoter 200 ms la LED rouge (0 : sous 300 mm),
// verte (1 : de 300 à 600 mm) ou bleue (2 : au-delà de 600 mm). Il garde
// aussi les distances (2 octets) des cartes « STeaMi… » qu'il entend
// directement. L'écran montre les 4 dernières cartes entendues et le courant
// de la batterie ; le moniteur série (115200 bauds) suit le scan.
//
// Il lit les trames du programme MicroPython octet pour octet : les cartes
// des deux langages se comprennent. Comme dans l'original, il n'écoute que
// R2, ce qui oblige à passer par les deux relais, et il attend encore 550 ms
// après la fin du scan avant d'allumer la LED.
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include <SteamiBattery.h>
const char DEVICE_NAME[] = "STeaMi-A";
const uint32_t SCAN_MS = 500; // durée de l'écoute
const uint32_t AFTER_SCAN_MS = SCAN_MS + 50; // pause de l'original après le scan
const uint32_t BLINK_MS = 200; // durée du clignotement
const uint32_t ENERGY_MS = 1000; // une lecture du courant par seconde
const uint32_t DISPLAY_MS = 300; // l'écran est redessiné toutes les 0,3 s
const int SHOWN = 4; // cartes affichées
SteamiScreen screen;
SteamiBattery battery;
int16_t energyCurrent = 0; // mA
bool hasPresence = false; // forwarded_presence n'est pas None
int forwardedPresence = 0;
// devices_distances : dernière valeur reçue de chaque carte, avec son heure.
struct Seen {
bool used;
char name[32];
int value;
uint32_t ms;
};
const int MAX_SEEN = 8;
Seen seen[MAX_SEEN];
enum Phase { SCANNING, AFTER_SCAN, BLINK };
Phase phase;
uint32_t phaseStart = 0;
// extract_manufacturer_data() : les octets du premier champ 0xFF de la trame.
int extractManufacturerData(const uint8_t* adv, int n, const uint8_t** data) {
int i = 0;
while (i + 1 < n) {
int length = adv[i];
if (length == 0) break;
if (adv[i + 1] == 0xFF) {
int end = min(i + 1 + length, n);
*data = adv + i + 2;
return max(end - (i + 2), 0);
}
i += 1 + length;
}
return 0;
}
void remember(const char* name, int value) {
int slot = -1, oldest = 0;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && strcmp(seen[i].name, name) == 0) { slot = i; break; }
if (!seen[i].used && slot < 0) slot = i;
if (seen[i].ms < seen[oldest].ms) oldest = i;
}
if (slot < 0) slot = oldest;
seen[slot].used = true;
strncpy(seen[slot].name, name, sizeof seen[slot].name - 1);
seen[slot].name[sizeof seen[slot].name - 1] = '\0';
seen[slot].value = value;
seen[slot].ms = millis();
}
void startScan() {
Serial.println("BLE Task: Starting scan...");
BLE.scan(true); // scan actif, avec les doublons
Serial.println("BLE Task: Scanning...");
phase = SCANNING;
phaseStart = millis();
}
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name.startsWith("STeaMi") && name != DEVICE_NAME) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
const uint8_t* man = nullptr;
int manLen = extractManufacturerData(adv, n, &man);
if (manLen == 2) {
int distance = (int16_t)(man[0] | (man[1] << 8)); // struct.unpack("h")
remember(name.c_str(), distance);
Serial.print("Received from ");
Serial.print(name);
Serial.print(": ");
Serial.print(distance);
Serial.println(" mm");
} else if (manLen == 1 && name.startsWith("STeaMi-R2")) {
forwardedPresence = (int8_t)man[0]; // struct.unpack("b")
hasPresence = true;
remember(name.c_str(), forwardedPresence);
}
}
d = BLE.available();
}
}
void ledsOff() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_BLUE, LOW);
}
void bleTask() {
uint32_t now = millis();
switch (phase) {
case SCANNING:
listen();
if (now - phaseStart >= SCAN_MS) {
BLE.stopScan();
phase = AFTER_SCAN;
phaseStart = now;
}
break;
case AFTER_SCAN:
if (now - phaseStart < AFTER_SCAN_MS) break;
if (!hasPresence) {
startScan();
break;
}
if (forwardedPresence == 0) {
digitalWrite(LED_RED, HIGH);
Serial.println("Presence detected within 300 mm !");
} else if (forwardedPresence == 1) {
digitalWrite(LED_GREEN, HIGH);
Serial.println("Presence detected between 300 mm and 600 mm !");
} else if (forwardedPresence == 2) {
digitalWrite(LED_BLUE, HIGH);
Serial.println("Presence detected beyond 600 mm !");
}
phase = BLINK;
phaseStart = now;
break;
case BLINK:
if (now - phaseStart < BLINK_MS) break;
ledsOff();
hasPresence = false;
startScan();
break;
}
}
// Ligne posée à l'abscisse qui centre le modèle, comme text_x_center() de l'original.
void centered(const char* s, const char* model, int y) {
int x = max((screen.width() - screen.textWidth(model)) / 2, 0);
screen.text(s, x, y);
}
int u(int v128) { // SCREEN.u() : v sur un écran de 128 px
return v128 * screen.width() / 128;
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// Les cartes entendues le plus récemment d'abord
bool shown[MAX_SEEN] = {};
// Une hauteur de texte plus une marge entre deux lignes
int y = u(40);
int step = screen.textHeight() + u(2);
char line[48];
for (int k = 0; k < SHOWN; k++) {
int best = -1;
for (int i = 0; i < MAX_SEEN; i++) {
if (seen[i].used && !shown[i] && (best < 0 || seen[i].ms > seen[best].ms)) best = i;
}
if (best < 0) break;
shown[best] = true;
const char* name = seen[best].name;
int len = strlen(name);
snprintf(line, sizeof line, "%s: %d", len > 4 ? name + len - 4 : name, seen[best].value); // name[-4:]
centered(line, "XXXX: XXX", y);
y += step;
}
snprintf(line, sizeof line, "I: %d.0 mA", energyCurrent); // .1f d'un entier
centered(line, "I: XX.X mA", y + u(5));
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
battery.begin();
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
ledsOff();
Serial.print("Device name: ");
Serial.println(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
energyCurrent = battery.current();
startScan();
}
void loop() {
static uint32_t lastEnergy = millis(), lastDisplay = 0;
BLE.poll();
bleTask();
uint32_t now = millis();
if (now - lastEnergy >= ENERGY_MS) {
lastEnergy = now;
energyCurrent = battery.current();
}
if (now - lastDisplay >= DISPLAY_MS) {
lastDisplay = now;
draw();
}
}
Scénario 3 : périphérique P1
Le scénario 3 est un petit maillage de six cartes : trois périphériques, STeaMi-P1 à STeaMi-P3, et trois relais, STeaMi-R1 à STeaMi-R3. P1 envoie sa distance à P2, P2 à P3 et P3 à P1, à travers les relais : un message arrive même quand le destinataire est hors de portée de l'émetteur. Les messages font 6 octets, masqués par un XOR avec 0x5A, après l'identifiant de fabricant 0xFFFF ; ils portent un numéro de séquence et le nombre de relais traversés. Leur format est dans le fichier mesh.h, recopié dans le dossier de chacun des six croquis (dossier de ce croquis).
Chaque périphérique mesure la distance et l'annonce 500 ms pour le suivant de la chaîne, puis écoute les relais 1 s. Il allume sa LED quand la distance reçue du précédent est sous 300 mm, et l'éteint sinon. La LED de P1 est la verte.
Matériel : six cartes, V1a, V1b ou V1c : les trois périphériques (P2, P3) et les trois relais (R1, R2, R3).
Ce qu'on observe : la LED verte de P1 s'allume quand un objet est à moins de 300 mm du capteur de P3. L'écran montre « Peripheral node » et le nom de la carte ; le moniteur série suit les envois et les réceptions.
En MicroPython : scenario/scenario_3/peripheral_1.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : périphérique P1 », portée du programme MicroPython
// scenario/scenario_3/peripheral_1 (avec peripheral_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/peripheral_1/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). P1 envoie sa distance à P2, P2 à
// P3 et P3 à P1, à travers les relais : un message arrive même quand le
// destinataire est hors de portée de l'émetteur.
//
// Ce périphérique mesure la distance et l'annonce 500 ms pour le suivant de
// la chaîne, puis écoute les relais 1 s. Il allume sa LED quand la distance
// reçue du précédent est sous 300 mm, et l'éteint sinon. L'écran montre
// « Peripheral node » et son nom ; le moniteur série (115200 bauds) suit les
// envois et les réceptions. Le format des messages est dans mesh.h.
//
// La trame est octet pour octet celle du programme MicroPython : les cartes
// des deux langages se comprennent. Comme dans l'original, la distance vaut
// -1 quand le capteur ne voit rien, ce qui allume la LED du destinataire.
#include <STM32duinoBLE.h>
#include <utility/HCI.h>
#include <SteamiScreen.h>
#include <SteamiDistance.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-P1";
const int LED = LED_GREEN;
const int THRESHOLD_MM = 300;
const uint32_t ADV_MS = 500; // annoncer chaque message 500 ms...
const uint32_t SCAN_MS = 1000; // ...puis écouter les relais 1 s
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
SteamiScreen screen;
SteamiDistance distance;
int self = -1; // rang de DEVICE_NAME dans NODES
int dst = -1; // le périphérique suivant
uint8_t seq = 0;
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage sent;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
bool advertising = false;
uint32_t phaseStart = 0;
// P1 envoie à P2, P2 à P3 et P3 à P1.
int nextPeripheral(int index) {
int peripherals[NODE_COUNT];
int count = 0, here = 0;
for (int i = 0; i < NODE_COUNT; i++) {
if (strncmp(NODES[i], "STeaMi-P", 8) == 0) {
if (i == index) here = count;
peripherals[count++] = i;
}
}
return peripherals[(here + 1) % count];
}
// Un octet au hasard, tiré par la puce radio (HCI LE Rand).
uint8_t randomByte() {
uint8_t r[8];
if (HCI.leRand(r) == 0) {
return r[0];
}
return micros() & 0xFF; // la radio n'a pas répondu
}
// === Envoyer la distance locale ===
void startAdvertising() {
seq = (seq + 1) % 256;
sent = MeshMessage{(uint8_t)self, (uint8_t)dst, seq, 0, (int16_t)distance.read()};
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, sent));
BLE.setAdvertisingData(advData);
BLE.advertise();
advertising = true;
phaseStart = millis();
}
// === Recevoir les messages adressés à ce périphérique ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.startsWith("STeaMi-R")) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.dst == self && isNew(lastSeq, m.src, m.seq)) {
digitalWrite(LED, m.value < THRESHOLD_MM ? HIGH : LOW);
Serial.print(DEVICE_NAME);
Serial.print(" received ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" via ");
Serial.print(name);
Serial.print(" (");
Serial.print(m.hop);
Serial.println(" hops)");
}
}
d = BLE.available();
}
}
void bleTask() {
uint32_t now = millis();
if (advertising) {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
Serial.print(DEVICE_NAME);
Serial.print(" sent ");
Serial.print(sent.value);
Serial.print(" mm to ");
Serial.print(NODES[dst]);
Serial.print(" (seq ");
Serial.print(seq);
Serial.println(")");
BLE.scan(true); // scan actif, avec les doublons
advertising = false;
phaseStart = now;
} else {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
startAdvertising();
}
}
void draw() {
screen.clear();
// Deux lignes centrées, espacées d'une hauteur de texte plus une marge
const char label[] = "Peripheral node";
int step = screen.textHeight() + screen.width() * 2 / 128;
int y = (screen.height() - step - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.text(DEVICE_NAME, (screen.width() - screen.textWidth(DEVICE_NAME)) / 2, y + step);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
distance.begin();
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
dst = nextPeripheral(self);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Peripheral ");
Serial.print(DEVICE_NAME);
Serial.print(" active, sends to ");
Serial.println(NODES[dst]);
// Départ au hasard : après un redémarrage, les relais ignoreraient une
// reprise à 0 jusqu'à ce qu'elle rattrape le dernier numéro qu'ils ont vu.
seq = randomByte();
startAdvertising();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}
Scénario 3 : périphérique P2
Le périphérique P2 reçoit la distance de P1 et envoie la sienne à P3. Sa LED est la rouge.
Matériel : six cartes, V1a, V1b ou V1c (voir Scénario 3 : périphérique P1).
Ce qu'on observe : la LED rouge de P2 s'allume quand un objet est à moins de 300 mm du capteur de P1. L'écran montre « Peripheral node » et le nom de la carte.
En MicroPython : scenario/scenario_3/peripheral_2.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : périphérique P2 », portée du programme MicroPython
// scenario/scenario_3/peripheral_2 (avec peripheral_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/peripheral_2/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). P1 envoie sa distance à P2, P2 à
// P3 et P3 à P1, à travers les relais : un message arrive même quand le
// destinataire est hors de portée de l'émetteur.
//
// Ce périphérique mesure la distance et l'annonce 500 ms pour le suivant de
// la chaîne, puis écoute les relais 1 s. Il allume sa LED quand la distance
// reçue du précédent est sous 300 mm, et l'éteint sinon. L'écran montre
// « Peripheral node » et son nom ; le moniteur série (115200 bauds) suit les
// envois et les réceptions. Le format des messages est dans mesh.h.
//
// La trame est octet pour octet celle du programme MicroPython : les cartes
// des deux langages se comprennent. Comme dans l'original, la distance vaut
// -1 quand le capteur ne voit rien, ce qui allume la LED du destinataire.
#include <STM32duinoBLE.h>
#include <utility/HCI.h>
#include <SteamiScreen.h>
#include <SteamiDistance.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-P2";
const int LED = LED_RED;
const int THRESHOLD_MM = 300;
const uint32_t ADV_MS = 500; // annoncer chaque message 500 ms...
const uint32_t SCAN_MS = 1000; // ...puis écouter les relais 1 s
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
SteamiScreen screen;
SteamiDistance distance;
int self = -1; // rang de DEVICE_NAME dans NODES
int dst = -1; // le périphérique suivant
uint8_t seq = 0;
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage sent;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
bool advertising = false;
uint32_t phaseStart = 0;
// P1 envoie à P2, P2 à P3 et P3 à P1.
int nextPeripheral(int index) {
int peripherals[NODE_COUNT];
int count = 0, here = 0;
for (int i = 0; i < NODE_COUNT; i++) {
if (strncmp(NODES[i], "STeaMi-P", 8) == 0) {
if (i == index) here = count;
peripherals[count++] = i;
}
}
return peripherals[(here + 1) % count];
}
// Un octet au hasard, tiré par la puce radio (HCI LE Rand).
uint8_t randomByte() {
uint8_t r[8];
if (HCI.leRand(r) == 0) {
return r[0];
}
return micros() & 0xFF; // la radio n'a pas répondu
}
// === Envoyer la distance locale ===
void startAdvertising() {
seq = (seq + 1) % 256;
sent = MeshMessage{(uint8_t)self, (uint8_t)dst, seq, 0, (int16_t)distance.read()};
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, sent));
BLE.setAdvertisingData(advData);
BLE.advertise();
advertising = true;
phaseStart = millis();
}
// === Recevoir les messages adressés à ce périphérique ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.startsWith("STeaMi-R")) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.dst == self && isNew(lastSeq, m.src, m.seq)) {
digitalWrite(LED, m.value < THRESHOLD_MM ? HIGH : LOW);
Serial.print(DEVICE_NAME);
Serial.print(" received ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" via ");
Serial.print(name);
Serial.print(" (");
Serial.print(m.hop);
Serial.println(" hops)");
}
}
d = BLE.available();
}
}
void bleTask() {
uint32_t now = millis();
if (advertising) {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
Serial.print(DEVICE_NAME);
Serial.print(" sent ");
Serial.print(sent.value);
Serial.print(" mm to ");
Serial.print(NODES[dst]);
Serial.print(" (seq ");
Serial.print(seq);
Serial.println(")");
BLE.scan(true); // scan actif, avec les doublons
advertising = false;
phaseStart = now;
} else {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
startAdvertising();
}
}
void draw() {
screen.clear();
// Deux lignes centrées, espacées d'une hauteur de texte plus une marge
const char label[] = "Peripheral node";
int step = screen.textHeight() + screen.width() * 2 / 128;
int y = (screen.height() - step - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.text(DEVICE_NAME, (screen.width() - screen.textWidth(DEVICE_NAME)) / 2, y + step);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
distance.begin();
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
dst = nextPeripheral(self);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Peripheral ");
Serial.print(DEVICE_NAME);
Serial.print(" active, sends to ");
Serial.println(NODES[dst]);
// Départ au hasard : après un redémarrage, les relais ignoreraient une
// reprise à 0 jusqu'à ce qu'elle rattrape le dernier numéro qu'ils ont vu.
seq = randomByte();
startAdvertising();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}
Scénario 3 : périphérique P3
Le périphérique P3 reçoit la distance de P2 et envoie la sienne à P1. Sa LED est la bleue.
Matériel : six cartes, V1a, V1b ou V1c (voir Scénario 3 : périphérique P1).
Ce qu'on observe : la LED bleue de P3 s'allume quand un objet est à moins de 300 mm du capteur de P2. L'écran montre « Peripheral node » et le nom de la carte.
En MicroPython : scenario/scenario_3/peripheral_3.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : périphérique P3 », portée du programme MicroPython
// scenario/scenario_3/peripheral_3 (avec peripheral_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/peripheral_3/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). P1 envoie sa distance à P2, P2 à
// P3 et P3 à P1, à travers les relais : un message arrive même quand le
// destinataire est hors de portée de l'émetteur.
//
// Ce périphérique mesure la distance et l'annonce 500 ms pour le suivant de
// la chaîne, puis écoute les relais 1 s. Il allume sa LED quand la distance
// reçue du précédent est sous 300 mm, et l'éteint sinon. L'écran montre
// « Peripheral node » et son nom ; le moniteur série (115200 bauds) suit les
// envois et les réceptions. Le format des messages est dans mesh.h.
//
// La trame est octet pour octet celle du programme MicroPython : les cartes
// des deux langages se comprennent. Comme dans l'original, la distance vaut
// -1 quand le capteur ne voit rien, ce qui allume la LED du destinataire.
#include <STM32duinoBLE.h>
#include <utility/HCI.h>
#include <SteamiScreen.h>
#include <SteamiDistance.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-P3";
const int LED = LED_BLUE;
const int THRESHOLD_MM = 300;
const uint32_t ADV_MS = 500; // annoncer chaque message 500 ms...
const uint32_t SCAN_MS = 1000; // ...puis écouter les relais 1 s
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
SteamiScreen screen;
SteamiDistance distance;
int self = -1; // rang de DEVICE_NAME dans NODES
int dst = -1; // le périphérique suivant
uint8_t seq = 0;
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage sent;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
bool advertising = false;
uint32_t phaseStart = 0;
// P1 envoie à P2, P2 à P3 et P3 à P1.
int nextPeripheral(int index) {
int peripherals[NODE_COUNT];
int count = 0, here = 0;
for (int i = 0; i < NODE_COUNT; i++) {
if (strncmp(NODES[i], "STeaMi-P", 8) == 0) {
if (i == index) here = count;
peripherals[count++] = i;
}
}
return peripherals[(here + 1) % count];
}
// Un octet au hasard, tiré par la puce radio (HCI LE Rand).
uint8_t randomByte() {
uint8_t r[8];
if (HCI.leRand(r) == 0) {
return r[0];
}
return micros() & 0xFF; // la radio n'a pas répondu
}
// === Envoyer la distance locale ===
void startAdvertising() {
seq = (seq + 1) % 256;
sent = MeshMessage{(uint8_t)self, (uint8_t)dst, seq, 0, (int16_t)distance.read()};
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, sent));
BLE.setAdvertisingData(advData);
BLE.advertise();
advertising = true;
phaseStart = millis();
}
// === Recevoir les messages adressés à ce périphérique ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.startsWith("STeaMi-R")) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.dst == self && isNew(lastSeq, m.src, m.seq)) {
digitalWrite(LED, m.value < THRESHOLD_MM ? HIGH : LOW);
Serial.print(DEVICE_NAME);
Serial.print(" received ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" via ");
Serial.print(name);
Serial.print(" (");
Serial.print(m.hop);
Serial.println(" hops)");
}
}
d = BLE.available();
}
}
void bleTask() {
uint32_t now = millis();
if (advertising) {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
Serial.print(DEVICE_NAME);
Serial.print(" sent ");
Serial.print(sent.value);
Serial.print(" mm to ");
Serial.print(NODES[dst]);
Serial.print(" (seq ");
Serial.print(seq);
Serial.println(")");
BLE.scan(true); // scan actif, avec les doublons
advertising = false;
phaseStart = now;
} else {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
startAdvertising();
}
}
void draw() {
screen.clear();
// Deux lignes centrées, espacées d'une hauteur de texte plus une marge
const char label[] = "Peripheral node";
int step = screen.textHeight() + screen.width() * 2 / 128;
int y = (screen.height() - step - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.text(DEVICE_NAME, (screen.width() - screen.textWidth(DEVICE_NAME)) / 2, y + step);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
distance.begin();
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
dst = nextPeripheral(self);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Peripheral ");
Serial.print(DEVICE_NAME);
Serial.print(" active, sends to ");
Serial.println(NODES[dst]);
// Départ au hasard : après un redémarrage, les relais ignoreraient une
// reprise à 0 jusqu'à ce qu'elle rattrape le dernier numéro qu'ils ont vu.
seq = randomByte();
startAdvertising();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}
Scénario 3 : relais R1
Chaque relais écoute 800 ms toutes les cartes du maillage, puis réannonce 300 ms sous son nom chaque nouveau message, avec un relais de plus dans son compte. Il jette un message déjà passé par 3 relais ou déjà vu. Les trois relais ne diffèrent que par leur nom.
Matériel : six cartes, V1a, V1b ou V1c (voir Scénario 3 : périphérique P1).
Ce qu'on observe : l'écran montre le nom de la carte et « Relay mesh node » ; le moniteur série suit les messages relayés.
Écart avec le programme MicroPython : l'original n'a pas de limite au nombre de messages relayés en un tour ; ici, au-delà de MAX_FORWARD, les suivants attendent le tour d'après, et un périphérique les réannonce de toute façon.
En MicroPython : scenario/scenario_3/relay_1.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : relais R1 », portée du programme MicroPython
// scenario/scenario_3/relay_1 (avec relay_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/relay_1/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). Ensemble, les relais forment un
// maillage : un message de P1 arrive à P2 même quand P2 est hors de portée
// de P1.
//
// Ce relais écoute 800 ms toutes les cartes du maillage, puis réannonce
// 300 ms sous son nom chaque nouveau message, avec un relais de plus (hop).
// Il jette un message déjà passé par 3 relais ou déjà vu. L'écran montre son
// nom et « Relay mesh node » ; le moniteur série (115200 bauds) suit les
// messages relayés. Le format des messages est dans mesh.h.
//
// Les trames sont octet pour octet celles du programme MicroPython : les
// cartes des deux langages se comprennent. L'original n'a pas de limite au
// nombre de messages d'un tour ; ici, au-delà de MAX_FORWARD, les suivants
// attendent le tour d'après (un périphérique les réannonce de toute façon).
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-R1";
const uint32_t SCAN_MS = 800; // écouter 800 ms...
const uint32_t ADV_MS = 300; // ...puis réannoncer chaque nouveau message 300 ms
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
const int MAX_FORWARD = 16; // messages réannoncés au plus par tour
SteamiScreen screen;
int self = -1; // rang de DEVICE_NAME dans NODES
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage toForward[MAX_FORWARD];
int forwardCount = 0;
int forwardIndex = 0;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, FORWARDING };
Phase phase;
uint32_t phaseStart = 0;
void startScan() {
forwardCount = 0;
BLE.scan(true); // scan actif, avec les doublons
phase = SCANNING;
phaseStart = millis();
}
// === Relever les nouveaux messages ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name != DEVICE_NAME && nodeIndex(name.c_str()) >= 0) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.src != self && m.hop < MAX_HOPS
&& forwardCount < MAX_FORWARD && isNew(lastSeq, m.src, m.seq)) {
toForward[forwardCount++] = m;
}
}
d = BLE.available();
}
}
// === Les réannoncer, avec un relais de plus ===
void forward(int i) {
MeshMessage m = toForward[i];
m.hop++;
Serial.print(DEVICE_NAME);
Serial.print(" relays ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" to ");
Serial.print(NODES[m.dst]);
Serial.print(" (hop ");
Serial.print(m.hop);
Serial.println(")");
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, m));
BLE.setAdvertisingData(advData);
BLE.advertise();
phaseStart = millis();
}
void bleTask() {
uint32_t now = millis();
if (phase == SCANNING) {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
if (forwardCount == 0) {
startScan();
return;
}
phase = FORWARDING;
forwardIndex = 0;
forward(forwardIndex);
} else {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
forwardIndex++;
if (forwardIndex < forwardCount) {
forward(forwardIndex);
} else {
startScan();
}
}
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// 15 caractères : sur la ligne du milieu, où le cercle est le plus large
const char label[] = "Relay mesh node";
int y = (screen.height() - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Relay ");
Serial.print(DEVICE_NAME);
Serial.println(" active");
startScan();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}
Scénario 3 : relais R2
Le relais STeaMi-R2 fonctionne comme R1, sous son propre nom.
Matériel : six cartes, V1a, V1b ou V1c (voir Scénario 3 : périphérique P1).
Ce qu'on observe : l'écran montre le nom de la carte et « Relay mesh node » ; le moniteur série suit les messages relayés.
En MicroPython : scenario/scenario_3/relay_2.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : relais R2 », portée du programme MicroPython
// scenario/scenario_3/relay_2 (avec relay_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/relay_2/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). Ensemble, les relais forment un
// maillage : un message de P1 arrive à P2 même quand P2 est hors de portée
// de P1.
//
// Ce relais écoute 800 ms toutes les cartes du maillage, puis réannonce
// 300 ms sous son nom chaque nouveau message, avec un relais de plus (hop).
// Il jette un message déjà passé par 3 relais ou déjà vu. L'écran montre son
// nom et « Relay mesh node » ; le moniteur série (115200 bauds) suit les
// messages relayés. Le format des messages est dans mesh.h.
//
// Les trames sont octet pour octet celles du programme MicroPython : les
// cartes des deux langages se comprennent. L'original n'a pas de limite au
// nombre de messages d'un tour ; ici, au-delà de MAX_FORWARD, les suivants
// attendent le tour d'après (un périphérique les réannonce de toute façon).
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-R2";
const uint32_t SCAN_MS = 800; // écouter 800 ms...
const uint32_t ADV_MS = 300; // ...puis réannoncer chaque nouveau message 300 ms
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
const int MAX_FORWARD = 16; // messages réannoncés au plus par tour
SteamiScreen screen;
int self = -1; // rang de DEVICE_NAME dans NODES
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage toForward[MAX_FORWARD];
int forwardCount = 0;
int forwardIndex = 0;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, FORWARDING };
Phase phase;
uint32_t phaseStart = 0;
void startScan() {
forwardCount = 0;
BLE.scan(true); // scan actif, avec les doublons
phase = SCANNING;
phaseStart = millis();
}
// === Relever les nouveaux messages ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name != DEVICE_NAME && nodeIndex(name.c_str()) >= 0) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.src != self && m.hop < MAX_HOPS
&& forwardCount < MAX_FORWARD && isNew(lastSeq, m.src, m.seq)) {
toForward[forwardCount++] = m;
}
}
d = BLE.available();
}
}
// === Les réannoncer, avec un relais de plus ===
void forward(int i) {
MeshMessage m = toForward[i];
m.hop++;
Serial.print(DEVICE_NAME);
Serial.print(" relays ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" to ");
Serial.print(NODES[m.dst]);
Serial.print(" (hop ");
Serial.print(m.hop);
Serial.println(")");
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, m));
BLE.setAdvertisingData(advData);
BLE.advertise();
phaseStart = millis();
}
void bleTask() {
uint32_t now = millis();
if (phase == SCANNING) {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
if (forwardCount == 0) {
startScan();
return;
}
phase = FORWARDING;
forwardIndex = 0;
forward(forwardIndex);
} else {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
forwardIndex++;
if (forwardIndex < forwardCount) {
forward(forwardIndex);
} else {
startScan();
}
}
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// 15 caractères : sur la ligne du milieu, où le cercle est le plus large
const char label[] = "Relay mesh node";
int y = (screen.height() - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Relay ");
Serial.print(DEVICE_NAME);
Serial.println(" active");
startScan();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}
Scénario 3 : relais R3
Le relais STeaMi-R3 fonctionne comme R1, sous son propre nom.
Matériel : six cartes, V1a, V1b ou V1c (voir Scénario 3 : périphérique P1).
Ce qu'on observe : l'écran montre le nom de la carte et « Relay mesh node » ; le moniteur série suit les messages relayés.
En MicroPython : scenario/scenario_3/relay_3.
Télécharger le .bin Glisser ce fichier sur le lecteur STEAMI de la carte.
// Activité « Scénario 3 : relais R3 », portée du programme MicroPython
// scenario/scenario_3/relay_3 (avec relay_base.py et mesh.py) :
// https://github.com/steamicc/micropython-steami-sample/blob/main/scenario/scenario_3/relay_3/main.py
//
// Maillage BLE du scénario 3 : trois périphériques « STeaMi-P1 » à « P3 »
// (croquis scenario-3-peripheral-1 à 3) et trois relais « STeaMi-R1 » à
// « R3 » (croquis scenario-3-relay-1 à 3). Ensemble, les relais forment un
// maillage : un message de P1 arrive à P2 même quand P2 est hors de portée
// de P1.
//
// Ce relais écoute 800 ms toutes les cartes du maillage, puis réannonce
// 300 ms sous son nom chaque nouveau message, avec un relais de plus (hop).
// Il jette un message déjà passé par 3 relais ou déjà vu. L'écran montre son
// nom et « Relay mesh node » ; le moniteur série (115200 bauds) suit les
// messages relayés. Le format des messages est dans mesh.h.
//
// Les trames sont octet pour octet celles du programme MicroPython : les
// cartes des deux langages se comprennent. L'original n'a pas de limite au
// nombre de messages d'un tour ; ici, au-delà de MAX_FORWARD, les suivants
// attendent le tour d'après (un périphérique les réannonce de toute façon).
#include <STM32duinoBLE.h>
#include <SteamiScreen.h>
#include "mesh.h"
const char DEVICE_NAME[] = "STeaMi-R3";
const uint32_t SCAN_MS = 800; // écouter 800 ms...
const uint32_t ADV_MS = 300; // ...puis réannoncer chaque nouveau message 300 ms
const uint16_t ADV_INTERVAL = 160; // 100 ms, en pas de 0,625 ms
const uint32_t DISPLAY_MS = 500; // l'écran est redessiné toutes les 0,5 s
const int MAX_FORWARD = 16; // messages réannoncés au plus par tour
SteamiScreen screen;
int self = -1; // rang de DEVICE_NAME dans NODES
int lastSeq[NODE_COUNT]; // dernier numéro vu de chaque émetteur, -1 : aucun
MeshMessage toForward[MAX_FORWARD];
int forwardCount = 0;
int forwardIndex = 0;
// BLEAdvertisingData garde un pointeur vers la trame : elle reste en mémoire.
uint8_t advPayload[31];
BLEAdvertisingData advData;
enum Phase { SCANNING, FORWARDING };
Phase phase;
uint32_t phaseStart = 0;
void startScan() {
forwardCount = 0;
BLE.scan(true); // scan actif, avec les doublons
phase = SCANNING;
phaseStart = millis();
}
// === Relever les nouveaux messages ===
void listen() {
BLEDevice d = BLE.available();
while (d) {
String name = d.localName();
if (name.length() > 0 && name != DEVICE_NAME && nodeIndex(name.c_str()) >= 0) {
uint8_t adv[62];
int n = d.advertisementData(adv, sizeof adv);
MeshMessage m;
if (meshDecode(adv, n, m) && m.src != self && m.hop < MAX_HOPS
&& forwardCount < MAX_FORWARD && isNew(lastSeq, m.src, m.seq)) {
toForward[forwardCount++] = m;
}
}
d = BLE.available();
}
}
// === Les réannoncer, avec un relais de plus ===
void forward(int i) {
MeshMessage m = toForward[i];
m.hop++;
Serial.print(DEVICE_NAME);
Serial.print(" relays ");
Serial.print(m.value);
Serial.print(" mm from ");
Serial.print(NODES[m.src]);
Serial.print(" to ");
Serial.print(NODES[m.dst]);
Serial.print(" (hop ");
Serial.print(m.hop);
Serial.println(")");
advData.setRawData(advPayload, meshEncode(advPayload, DEVICE_NAME, m));
BLE.setAdvertisingData(advData);
BLE.advertise();
phaseStart = millis();
}
void bleTask() {
uint32_t now = millis();
if (phase == SCANNING) {
listen();
if (now - phaseStart < SCAN_MS) return;
BLE.stopScan();
if (forwardCount == 0) {
startScan();
return;
}
phase = FORWARDING;
forwardIndex = 0;
forward(forwardIndex);
} else {
if (now - phaseStart < ADV_MS) return;
BLE.stopAdvertise(); // fin normale d'une annonce sans connexion
forwardIndex++;
if (forwardIndex < forwardCount) {
forward(forwardIndex);
} else {
startScan();
}
}
}
void draw() {
screen.clear();
screen.text(DEVICE_NAME, SteamiAt::N);
// 15 caractères : sur la ligne du milieu, où le cercle est le plus large
const char label[] = "Relay mesh node";
int y = (screen.height() - screen.textHeight()) / 2;
screen.text(label, (screen.width() - screen.textWidth(label)) / 2, y);
screen.show();
}
void setup() {
Serial.begin(115200);
screen.begin(); // en premier, comme pour SteamiDisplay
for (int i = 0; i < NODE_COUNT; i++) lastSeq[i] = -1;
self = nodeIndex(DEVICE_NAME);
if (!BLE.begin()) {
Serial.println("BLE init failed: check the radio stack of the board");
}
BLE.setConnectable(false);
BLE.setAdvertisingInterval(ADV_INTERVAL);
Serial.print("Relay ");
Serial.print(DEVICE_NAME);
Serial.println(" active");
startScan();
}
void loop() {
static uint32_t lastDisplay = 0;
BLE.poll();
bleTask();
if (millis() - lastDisplay >= DISPLAY_MS) {
lastDisplay = millis();
draw();
}
}