xerbot 0.1.0 : le contrat xerbot v1 pour Arduino / PlatformIO (USB, ESP-NOW, Bluetooth), 6 exemples dont RuView CSI, test natif 8/8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R75H65SynGwRG5vBSoYeZ1
This commit is contained in:
7
LICENSE
Normal file
7
LICENSE
Normal file
@@ -0,0 +1,7 @@
|
||||
MIT License — © 2026 chill-tekk
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
70
README.md
Normal file
70
README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# xerbot — un microcontrôleur devient un appareil du xerboxion
|
||||
|
||||
La librairie du **contrat xerbot v1** pour Arduino / PlatformIO : une ligne JSON par message, dans les deux sens. Ton montage apparaît dans le ploxion **xerbot › ⌁ trouver** du labo (et dans le Cube, RuView, le cubion) ; sa télémétrie arrive sur le bus, ses commandes repartent vers lui.
|
||||
|
||||
```
|
||||
appareil → {"dev":"cube-1","type":"capteur","telemetry":{"t":21.5}} {"dev":…,"state":{"online":true}} {"dev":…,"ack":{"id":"x1","ok":true}}
|
||||
labo → {"dev":"cube-1","cmd":"led","args":{"on":true},"id":"x1"}
|
||||
```
|
||||
|
||||
| transport | cartes | comment le labo l'ouvre |
|
||||
| --- | --- | --- |
|
||||
| **USB série** | toutes (Uno, Nano, ESP32, ESP8266, Pico, STM32, nRF52…) | xerbot › ⌁ trouver › ⎍ USB (Chrome / Edge) — ou un Raspberry Pi qui fait tourner `xb agent` |
|
||||
| **ESP-NOW** | ESP32 (toutes), ESP8266 | une **passerelle** (exemple 03) en USB relaie tous les nœuds, sans Wi-Fi ni Internet, ~200 m |
|
||||
| **Bluetooth** | ESP32 (pas S2) | xerbot › ⌁ trouver › ◈ Bluetooth (service Nordic UART) |
|
||||
|
||||
## L'installer
|
||||
|
||||
**PlatformIO** (`platformio.ini`) :
|
||||
|
||||
```ini
|
||||
[env:esp32]
|
||||
platform = espressif32
|
||||
board = esp32dev ; esp32-s3-devkitc-1, esp32-c3-devkitm-1, esp32-c6-devkitc-1, seeed_xiao_esp32c3…
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
lib_deps = https://git.j0bot.ch/admin_j0bot/xerbot-arduino.git
|
||||
```
|
||||
|
||||
**Arduino IDE** : Croquis › Inclure une bibliothèque › Ajouter la bibliothèque .ZIP (le zip de ce dépôt).
|
||||
|
||||
## Le minimum
|
||||
|
||||
```cpp
|
||||
#include <Xerbot.h>
|
||||
Xerbot xb("cube-1", "capteur"); // son nom sur le bus, son type
|
||||
void commande(Xerbot& x, const XerbotCommande& c) {
|
||||
if (!strcmp(c.cmd, "led")) { digitalWrite(LED_BUILTIN, c.booleen("on")); x.ack(c.id); }
|
||||
else x.ack(c.id, false, "commande inconnue");
|
||||
}
|
||||
void setup() { Serial.begin(115200); xb.begin(Serial); xb.onCommande(commande); }
|
||||
void loop() { xb.loop(); /* toutes les 2 s : */ xb.telemetrie().add("t", 21.5).add("lux", 320).envoyer(); }
|
||||
```
|
||||
|
||||
`c.texte("mode", buf, n)`, `c.nombre("w", 0)`, `c.booleen("on")` lisent les arguments ; `ping` et `hello` sont gérés tout seuls ; l'état part toutes les 10 s (`xb.battement(ms)`).
|
||||
|
||||
## Par carte
|
||||
|
||||
- **ESP32 / S3 / C3 / C6** — USB, ESP-NOW (`#include <XerbotEspNow.h>`, `xerbotEspNowNoeud(xb)`), Bluetooth (`#include <XerbotBLE.h>`, `xerbotBLE(xb, "nom")`), RuView (exemple 05). PlatformIO : `platform = espressif32`. Arduino IDE : gestionnaire de cartes « esp32 » (Espressif).
|
||||
- **ESP8266** (D1 mini, NodeMCU) — USB, ESP-NOW. `platform = espressif8266`.
|
||||
- **Arduino Uno / Nano / Mega** (AVR) — USB seulement ; lignes de 128 caractères (exemple 06). `platform = atmelavr`, `board = uno`.
|
||||
- **Raspberry Pi Pico / Pico W** (RP2040) — USB. `platform = raspberrypi`, `board = pico`.
|
||||
- **STM32, nRF52, SAMD** — USB série : même code, ton `board`.
|
||||
- **Raspberry Pi (Linux)** — pas cette librairie : `xb agent` ; le Pi peut servir d'hôte USB à une passerelle ESP-NOW.
|
||||
|
||||
## Les exemples
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| `01-usb-capteur` | n'importe quelle carte en USB : télémétrie + `led` |
|
||||
| `02-espnow-noeud` | un ESP sans Wi-Fi qui parle à la passerelle |
|
||||
| `03-espnow-passerelle` | l'ESP en USB qui relaie tous les nœuds |
|
||||
| `04-ble-capteur` | un ESP32 en Bluetooth (et USB) |
|
||||
| `05-ruview-csi` | RuView : la présence par le Wi-Fi (CSI), pour le ploxion ruview |
|
||||
| `06-uno-minimal` | le plus petit : un Uno |
|
||||
|
||||
## Tester sans carte
|
||||
|
||||
`g++ -std=c++17 -I test -o t test/test.cpp src/Xerbot.cpp && ./t` → `xerbot : 8/8`. ESP-NOW et Bluetooth (headers ESP) : pas encore compilés sur une vraie chaîne ESP32 — le premier test réel les valide.
|
||||
|
||||
© 2026 chill-tekk · MIT · ne pas nuire
|
||||
16
examples/01-usb-capteur/01-usb-capteur.ino
Normal file
16
examples/01-usb-capteur/01-usb-capteur.ino
Normal file
@@ -0,0 +1,16 @@
|
||||
// 01 · un capteur en USB (n'importe quelle carte Arduino : ESP32, ESP8266, Pico, Uno…)
|
||||
// Branche en USB, ouvre le ploxion xerbot › ⌁ trouver › ⎍ USB : « cube-capteur » apparaît, sa télémétrie arrive, « ◎ ping » répond.
|
||||
#include <Xerbot.h>
|
||||
Xerbot xb("cube-capteur", "capteur");
|
||||
const int LED = LED_BUILTIN;
|
||||
|
||||
void commande(Xerbot& x, const XerbotCommande& c) {
|
||||
if (strcmp(c.cmd, "led") == 0) { digitalWrite(LED, c.booleen("on") ? HIGH : LOW); x.ack(c.id, true); }
|
||||
else x.ack(c.id, false, "commande inconnue");
|
||||
}
|
||||
void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); xb.begin(Serial); xb.onCommande(commande); }
|
||||
void loop() {
|
||||
xb.loop();
|
||||
static unsigned long t = 0;
|
||||
if (millis() - t > 2000) { t = millis(); xb.telemetrie().add("a0", (long)analogRead(A0)).add("uptime_s", (long)(millis() / 1000)).envoyer(); }
|
||||
}
|
||||
23
examples/02-espnow-noeud/02-espnow-noeud.ino
Normal file
23
examples/02-espnow-noeud/02-espnow-noeud.ino
Normal file
@@ -0,0 +1,23 @@
|
||||
// 02 · un nœud ESP-NOW (ESP32 / ESP8266) : sans Wi-Fi ni Internet, il parle à la passerelle (exemple 03) jusqu'à ~200 m.
|
||||
// Il apparaît dans xerbot avec le badge ESPNOW ; « led » allume sa LED. Mets la MAC de ta passerelle pour ne pas diffuser.
|
||||
#include <Xerbot.h>
|
||||
#include <XerbotEspNow.h>
|
||||
Xerbot xb("noeud-1", "capteur");
|
||||
void commande(Xerbot& x, const XerbotCommande& c) {
|
||||
if (strcmp(c.cmd, "led") == 0) { digitalWrite(LED_BUILTIN, c.booleen("on") ? HIGH : LOW); x.ack(c.id, true); }
|
||||
else x.ack(c.id, false, "commande inconnue");
|
||||
}
|
||||
void setup() {
|
||||
Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT);
|
||||
xb.onCommande(commande);
|
||||
xerbotEspNowNoeud(xb /*, macPasserelle */);
|
||||
}
|
||||
void loop() {
|
||||
xb.loop();
|
||||
static unsigned long t = 0;
|
||||
#if defined(ESP32)
|
||||
if (millis() - t > 2000) { t = millis(); xb.telemetrie().add("t_puce", (double)temperatureRead(), 1).add("rssi", (long)WiFi.RSSI()).envoyer(); }
|
||||
#else
|
||||
if (millis() - t > 2000) { t = millis(); xb.telemetrie().add("a0", (long)analogRead(A0)).envoyer(); }
|
||||
#endif
|
||||
}
|
||||
6
examples/03-espnow-passerelle/03-espnow-passerelle.ino
Normal file
6
examples/03-espnow-passerelle/03-espnow-passerelle.ino
Normal file
@@ -0,0 +1,6 @@
|
||||
// 03 · la passerelle ESP-NOW (ESP32 / ESP8266) : branchée en USB (au PC, ou à un Raspberry Pi Zero 2 W), elle relaie tous les nœuds.
|
||||
// xerbot › ⌁ trouver › ⎍ USB : chaque nœud apparaît (badge ESPNOW) ; leurs commandes repartent par elle.
|
||||
#include <Xerbot.h>
|
||||
#include <XerbotEspNow.h>
|
||||
void setup() { Serial.begin(115200); xerbotEspNowPasserelle(Serial); }
|
||||
void loop() { xerbotEspNowLoop(); }
|
||||
14
examples/04-ble-capteur/04-ble-capteur.ino
Normal file
14
examples/04-ble-capteur/04-ble-capteur.ino
Normal file
@@ -0,0 +1,14 @@
|
||||
// 04 · un capteur en Bluetooth (ESP32) : xerbot › ⌁ trouver › ◈ Bluetooth (Chrome / Edge, aussi sur Android). L'USB marche en même temps.
|
||||
#include <Xerbot.h>
|
||||
#include <XerbotBLE.h>
|
||||
Xerbot xb("cube-ble", "capteur");
|
||||
void commande(Xerbot& x, const XerbotCommande& c) {
|
||||
if (strcmp(c.cmd, "led") == 0) { digitalWrite(LED_BUILTIN, c.booleen("on") ? HIGH : LOW); x.ack(c.id, true); }
|
||||
else x.ack(c.id, false, "commande inconnue");
|
||||
}
|
||||
void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); xb.begin(Serial); xb.onCommande(commande); xerbotBLE(xb, "cube-ble"); }
|
||||
void loop() {
|
||||
xb.loop();
|
||||
static unsigned long t = 0;
|
||||
if (millis() - t > 2000) { t = millis(); xb.telemetrie().add("t_puce", (double)temperatureRead(), 1).envoyer(); }
|
||||
}
|
||||
26
examples/05-ruview-csi/05-ruview-csi.ino
Normal file
26
examples/05-ruview-csi/05-ruview-csi.ino
Normal file
@@ -0,0 +1,26 @@
|
||||
// 05 · RuView : la présence par le Wi-Fi (ESP32, pas S2). Il écoute le canal (CSI) des paquets qu'envoie un AUTRE ESP32 (l'exemple 02, qui
|
||||
// diffuse toutes les 2 s ; mets son intervalle à 50 ms pour une belle cascade) et envoie {"csi":[amplitudes],"rssi":…} en USB.
|
||||
// Le ploxion ruview (bouton ⎍ brancher un ESP32) les dessine : calme / présence / mouvement. Deux ESP32 face à face, 2 à 5 m.
|
||||
#include <WiFi.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_now.h>
|
||||
static volatile bool pret = false; static int8_t buf[384]; static int len = 0, rssi = 0;
|
||||
static void csiCb(void*, wifi_csi_info_t* info) {
|
||||
if (pret || !info || !info->buf) return;
|
||||
len = info->len > 384 ? 384 : info->len; memcpy(buf, info->buf, len); rssi = info->rx_ctrl.rssi; pret = true;
|
||||
}
|
||||
void setup() {
|
||||
Serial.begin(921600); // le CSI est bavard : 921600 bauds (règle-le aussi dans le ploxion si besoin)
|
||||
WiFi.mode(WIFI_STA); esp_now_init(); // ESP-NOW ouvre la radio sur le canal 1, comme l'émetteur
|
||||
wifi_csi_config_t cfg = {}; cfg.lltf_en = true; cfg.htltf_en = true; cfg.stbc_htltf2_en = true; cfg.ltf_merge_en = true; cfg.channel_filter_en = false; cfg.manu_scale = false;
|
||||
esp_wifi_set_promiscuous(true); esp_wifi_set_csi_config(&cfg); esp_wifi_set_csi_rx_cb(csiCb, nullptr); esp_wifi_set_csi(true);
|
||||
}
|
||||
void loop() {
|
||||
if (!pret) return;
|
||||
// le tampon = des paires (imaginaire, réel) par sous-porteuse → l'amplitude
|
||||
Serial.print("{\"csi\":[");
|
||||
int n = len / 2; if (n > 64) n = 64;
|
||||
for (int k = 0; k < n; k++) { float im = buf[2 * k], re = buf[2 * k + 1]; Serial.print(sqrtf(im * im + re * re), 1); if (k + 1 < n) Serial.print(','); }
|
||||
Serial.print("],\"rssi\":"); Serial.print(rssi); Serial.print("}\n");
|
||||
pret = false;
|
||||
}
|
||||
8
examples/06-uno-minimal/06-uno-minimal.ino
Normal file
8
examples/06-uno-minimal/06-uno-minimal.ino
Normal file
@@ -0,0 +1,8 @@
|
||||
// 06 · le plus petit : un Arduino Uno / Nano (AVR, 2 Ko de RAM). USB seulement ; une ligne de 128 caractères max.
|
||||
#include <Xerbot.h>
|
||||
Xerbot xb("uno", "capteur");
|
||||
void commande(Xerbot& x, const XerbotCommande& c) {
|
||||
if (strcmp(c.cmd, "led") == 0) { digitalWrite(13, c.booleen("on") ? HIGH : LOW); x.ack(c.id, true); } else x.ack(c.id, false);
|
||||
}
|
||||
void setup() { Serial.begin(115200); pinMode(13, OUTPUT); xb.battement(30000); xb.begin(Serial); xb.onCommande(commande); }
|
||||
void loop() { xb.loop(); static unsigned long t = 0; if (millis() - t > 3000) { t = millis(); xb.telemetrie().add("a0", (long)analogRead(A0)).envoyer(); } }
|
||||
13
library.json
Normal file
13
library.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "xerbot",
|
||||
"version": "0.1.0",
|
||||
"description": "Le contrat xerbot v1 du xerboxion : un microcontrôleur parle au labo en lignes JSON — USB série, ESP-NOW (ESP32/ESP8266), Bluetooth (ESP32). Télémétrie, état, commandes, accusés.",
|
||||
"keywords": ["xerboxion", "xerbot", "esp-now", "esp32", "esp8266", "ble", "json", "telemetry", "iot"],
|
||||
"repository": { "type": "git", "url": "https://git.j0bot.ch/admin_j0bot/xerbot-arduino.git" },
|
||||
"authors": [{ "name": "chill-tekk" }],
|
||||
"license": "MIT",
|
||||
"frameworks": ["arduino"],
|
||||
"platforms": ["espressif32", "espressif8266", "atmelavr", "raspberrypi", "ststm32", "atmelsam", "nordicnrf52"],
|
||||
"headers": ["Xerbot.h"],
|
||||
"export": { "exclude": ["test"] }
|
||||
}
|
||||
10
library.properties
Normal file
10
library.properties
Normal file
@@ -0,0 +1,10 @@
|
||||
name=xerbot
|
||||
version=0.1.0
|
||||
author=chill-tekk
|
||||
maintainer=chill-tekk
|
||||
sentence=Le contrat xerbot v1 du xerboxion en lignes JSON (USB série, ESP-NOW, Bluetooth).
|
||||
paragraph=Télémétrie, état, commandes et accusés : un microcontrôleur devient un appareil du xerboxion (ploxion xerbot, le Cube, RuView).
|
||||
category=Communication
|
||||
url=https://git.j0bot.ch/admin_j0bot/xerbot-arduino
|
||||
architectures=*
|
||||
includes=Xerbot.h
|
||||
116
src/Xerbot.cpp
Normal file
116
src/Xerbot.cpp
Normal file
@@ -0,0 +1,116 @@
|
||||
// Xerbot.cpp — voir Xerbot.h. Mini-lecteur JSON volontairement simple (les lignes du contrat xerbot v1, pas du JSON arbitraire).
|
||||
#include "Xerbot.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// ---------------------------------------------------------------- les messages
|
||||
void XerbotMsg::ecrire(const char* s) {
|
||||
while (*s && _n + 1 < sizeof(_b)) _b[_n++] = *s++;
|
||||
_b[_n] = 0;
|
||||
}
|
||||
void XerbotMsg::cle(const char* k) { ecrire(_vide ? "\"" : ",\""); ecrire(k); ecrire("\":"); _vide = false; }
|
||||
XerbotMsg& XerbotMsg::add(const char* k, const char* v) {
|
||||
cle(k); ecrire("\"");
|
||||
char e[3] = {0, 0, 0};
|
||||
for (const char* p = v ? v : ""; *p; p++) {
|
||||
if (*p == '"' || *p == '\\') { e[0] = '\\'; e[1] = *p; ecrire(e); }
|
||||
else if (*p == '\n') ecrire("\\n");
|
||||
else if ((unsigned char)*p >= 0x20) { e[0] = *p; e[1] = 0; ecrire(e); }
|
||||
}
|
||||
ecrire("\"");
|
||||
return *this;
|
||||
}
|
||||
XerbotMsg& XerbotMsg::add(const char* k, double v, uint8_t d) {
|
||||
char t[24];
|
||||
#if defined(__AVR__)
|
||||
dtostrf(v, 1, d, t);
|
||||
#else
|
||||
snprintf(t, sizeof(t), "%.*f", (int)d, v);
|
||||
#endif
|
||||
if (v != v) strcpy(t, "null"); // NaN : JSON ne l'accepte pas
|
||||
cle(k); ecrire(t); return *this;
|
||||
}
|
||||
XerbotMsg& XerbotMsg::add(const char* k, long v) { char t[16]; snprintf(t, sizeof(t), "%ld", v); cle(k); ecrire(t); return *this; }
|
||||
XerbotMsg& XerbotMsg::add(const char* k, bool v) { cle(k); ecrire(v ? "true" : "false"); return *this; }
|
||||
XerbotMsg& XerbotMsg::brut(const char* k, const char* json) { cle(k); ecrire(json ? json : "null"); return *this; }
|
||||
bool XerbotMsg::envoyer() { return _x->emettre(_sec, _b); }
|
||||
|
||||
// ---------------------------------------------------------------- l'appareil
|
||||
bool Xerbot::ligne(const char* json) {
|
||||
if (_sortie) { _sortie(json, _ctx); return true; }
|
||||
if (!_s) return false;
|
||||
_s->print(json); _s->print('\n');
|
||||
return true;
|
||||
}
|
||||
bool Xerbot::emettre(const char* section, const char* corps) {
|
||||
static char t[XERBOT_LIGNE + 96];
|
||||
snprintf(t, sizeof(t), "{\"dev\":\"%s\",\"type\":\"%s\",\"%s\":{%s}}", _dev, _type, section, corps);
|
||||
return ligne(t);
|
||||
}
|
||||
bool Xerbot::ack(const char* id, bool ok, const char* err) {
|
||||
XerbotMsg m(this, "ack");
|
||||
m.add("id", id ? id : "").add("ok", ok);
|
||||
if (err) m.add("err", err);
|
||||
return m.envoyer();
|
||||
}
|
||||
void Xerbot::loop() {
|
||||
while (_s && _s->available()) {
|
||||
char c = (char)_s->read();
|
||||
if (c == '\r') continue;
|
||||
if (c == '\n') { _l[_ln] = 0; if (_ln) recevoir(_l); _ln = 0; continue; }
|
||||
if (_ln + 1 < sizeof(_l)) _l[_ln++] = c; else _ln = 0; // ligne trop longue : jetée
|
||||
}
|
||||
if (_bat && millis() - _dernier >= _bat) { _dernier = millis(); etat().add("online", true).add("uptime_s", (long)(millis() / 1000)).envoyer(); }
|
||||
}
|
||||
void Xerbot::recevoir(const char* ligne) {
|
||||
// {"hello":…} : le labo vient d'ouvrir le lien → on se présente
|
||||
if (strstr(ligne, "\"hello\"")) { etat().add("online", true).envoyer(); return; }
|
||||
XerbotCommande c; c.cmd[0] = 0; c.id[0] = 0;
|
||||
if (!jsonTexte(ligne, "cmd", c.cmd, sizeof(c.cmd))) return;
|
||||
char d[40];
|
||||
if (jsonTexte(ligne, "dev", d, sizeof(d)) && strcmp(d, _dev) != 0) return; // pour un autre appareil
|
||||
jsonTexte(ligne, "id", c.id, sizeof(c.id));
|
||||
c.args = jsonObjet(ligne, "args", &c.argsLen);
|
||||
if (!c.args) { c.args = "{}"; c.argsLen = 2; }
|
||||
if (strcmp(c.cmd, "ping") == 0) { ack(c.id, true); return; }
|
||||
if (_cb) _cb(*this, c); else ack(c.id, false, "pas de onCommande");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- le mini-lecteur JSON
|
||||
static const char* valeur(const char* src, size_t n, const char* cle) {
|
||||
// cherche "cle" suivi de « : » (au premier niveau ou pas : les lignes du contrat sont plates)
|
||||
size_t lc = strlen(cle);
|
||||
for (const char* p = src; p && (size_t)(p - src) < n; p++) {
|
||||
p = strchr(p, '"'); if (!p || (size_t)(p - src) >= n) return nullptr;
|
||||
if (strncmp(p + 1, cle, lc) == 0 && p[1 + lc] == '"') {
|
||||
const char* q = p + 2 + lc; while (*q == ' ') q++;
|
||||
if (*q == ':') { q++; while (*q == ' ') q++; return q; }
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
bool Xerbot::jsonTexte(const char* src, const char* cle, char* out, size_t n) {
|
||||
const char* v = valeur(src, strlen(src), cle); if (!v || *v != '"' || !n) return false;
|
||||
size_t i = 0; v++;
|
||||
while (*v && *v != '"' && i + 1 < n) { if (*v == '\\' && v[1]) v++; out[i++] = *v++; }
|
||||
out[i] = 0; return true;
|
||||
}
|
||||
bool Xerbot::jsonNombre(const char* src, const char* cle, double* out) {
|
||||
const char* v = valeur(src, strlen(src), cle); if (!v) return false;
|
||||
if (*v == 't') { *out = 1; return true; } if (*v == 'f') { *out = 0; return true; }
|
||||
char* fin; double d = strtod(v, &fin); if (fin == v) return false; *out = d; return true;
|
||||
}
|
||||
const char* Xerbot::jsonObjet(const char* src, const char* cle, size_t* len) {
|
||||
const char* v = valeur(src, strlen(src), cle); if (!v || *v != '{') return nullptr;
|
||||
int prof = 0; bool chaine = false;
|
||||
for (const char* p = v; *p; p++) {
|
||||
if (chaine) { if (*p == '\\' && p[1]) p++; else if (*p == '"') chaine = false; continue; }
|
||||
if (*p == '"') chaine = true; else if (*p == '{') prof++; else if (*p == '}' && --prof == 0) { if (len) *len = (size_t)(p - v + 1); return v; }
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
static char* copieArgs(const XerbotCommande& c, char* t, size_t n) { size_t k = c.argsLen < n - 1 ? c.argsLen : n - 1; memcpy(t, c.args, k); t[k] = 0; return t; }
|
||||
bool XerbotCommande::texte(const char* nom, char* out, size_t n) const { char t[XERBOT_LIGNE]; return Xerbot::jsonTexte(copieArgs(*this, t, sizeof(t)), nom, out, n); }
|
||||
double XerbotCommande::nombre(const char* nom, double defaut) const { char t[XERBOT_LIGNE]; double d; return Xerbot::jsonNombre(copieArgs(*this, t, sizeof(t)), nom, &d) ? d : defaut; }
|
||||
bool XerbotCommande::booleen(const char* nom, bool defaut) const { char t[XERBOT_LIGNE]; double d; return Xerbot::jsonNombre(copieArgs(*this, t, sizeof(t)), nom, &d) ? d != 0 : defaut; }
|
||||
79
src/Xerbot.h
Normal file
79
src/Xerbot.h
Normal file
@@ -0,0 +1,79 @@
|
||||
// Xerbot.h — le contrat xerbot v1 du xerboxion, pour tout microcontrôleur Arduino (04.11.2026).
|
||||
// Une ligne JSON par message, dans les deux sens :
|
||||
// appareil → {"dev":"cube-1","type":"capteur","telemetry":{"t":21.5}} {"dev":…,"state":{"online":true}} {"dev":…,"ack":{"id":"x1","ok":true}}
|
||||
// labo → {"dev":"cube-1","cmd":"led","args":{"on":true},"id":"x1"}
|
||||
// Le labo (ploxion xerbot › ⌁ trouver, jOSXerbotLien) lit ces lignes en USB (Web Serial), en Bluetooth (service Nordic UART) ou via une
|
||||
// passerelle ESP-NOW ; chaque appareil devient ploxion.xerbot.<dev>.* sur le bus. Aucune dépendance ; tient sur un Arduino Uno.
|
||||
// Xerbot xb("cube-1", "capteur");
|
||||
// void setup() { Serial.begin(115200); xb.begin(Serial); xb.onCommande(maCommande); }
|
||||
// void loop() { xb.loop(); if (toutesLes2s) xb.telemetrie().add("t", 21.5).envoyer(); }
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
#if defined(__AVR__)
|
||||
#define XERBOT_LIGNE 128
|
||||
#else
|
||||
#define XERBOT_LIGNE 512
|
||||
#endif
|
||||
|
||||
class Xerbot;
|
||||
|
||||
// Un message en construction : add(clé, valeur)…, puis envoyer(). Les valeurs texte sont échappées.
|
||||
class XerbotMsg {
|
||||
public:
|
||||
XerbotMsg(Xerbot* x, const char* section) : _x(x), _sec(section), _n(0), _vide(true) { _b[0] = 0; }
|
||||
XerbotMsg& add(const char* k, const char* v);
|
||||
XerbotMsg& add(const char* k, double v, uint8_t decimales = 2);
|
||||
XerbotMsg& add(const char* k, long v);
|
||||
XerbotMsg& add(const char* k, int v) { return add(k, (long)v); }
|
||||
XerbotMsg& add(const char* k, bool v);
|
||||
XerbotMsg& brut(const char* k, const char* json); // une valeur JSON déjà faite (tableau, objet)
|
||||
bool envoyer();
|
||||
const char* corps() const { return _b; }
|
||||
private:
|
||||
void cle(const char* k);
|
||||
void ecrire(const char* s);
|
||||
Xerbot* _x; const char* _sec; char _b[XERBOT_LIGNE]; size_t _n; bool _vide;
|
||||
};
|
||||
|
||||
// Une commande reçue. args = l'objet JSON brut des arguments ({…}, ou "{}").
|
||||
struct XerbotCommande {
|
||||
char cmd[24];
|
||||
char id[28];
|
||||
const char* args;
|
||||
size_t argsLen;
|
||||
bool texte(const char* nom, char* out, size_t n) const; // args.nom en texte
|
||||
double nombre(const char* nom, double defaut = 0) const; // args.nom en nombre
|
||||
bool booleen(const char* nom, bool defaut = false) const;
|
||||
};
|
||||
|
||||
// Où partent les lignes : par défaut le Stream de begin() ; ESP-NOW et Bluetooth en posent un autre.
|
||||
typedef void (*XerbotSortie)(const char* ligne, void* ctx);
|
||||
|
||||
class Xerbot {
|
||||
public:
|
||||
Xerbot(const char* dev, const char* type = "capteur") : _dev(dev), _type(type) {}
|
||||
void begin(Stream& s) { _s = &s; etat().add("online", true).envoyer(); }
|
||||
void sortie(XerbotSortie f, void* ctx) { _sortie = f; _ctx = ctx; }
|
||||
void onCommande(void (*cb)(Xerbot&, const XerbotCommande&)) { _cb = cb; }
|
||||
void battement(unsigned long ms) { _bat = ms; } // l'état toutes les ms (10 s par défaut ; 0 = jamais)
|
||||
void loop();
|
||||
void recevoir(const char* ligne); // une ligne reçue par n'importe quel transport
|
||||
XerbotMsg telemetrie() { return XerbotMsg(this, "telemetry"); }
|
||||
XerbotMsg etat() { return XerbotMsg(this, "state"); }
|
||||
bool ack(const char* id, bool ok = true, const char* err = nullptr);
|
||||
bool ligne(const char* json); // envoyer une ligne JSON brute (déjà complète)
|
||||
const char* dev() const { return _dev; }
|
||||
const char* type() const { return _type; }
|
||||
// les briques du mini-lecteur JSON (aussi utiles dans un croquis)
|
||||
static bool jsonTexte(const char* src, const char* cle, char* out, size_t n);
|
||||
static bool jsonNombre(const char* src, const char* cle, double* out);
|
||||
static const char* jsonObjet(const char* src, const char* cle, size_t* len);
|
||||
private:
|
||||
friend class XerbotMsg;
|
||||
bool emettre(const char* section, const char* corps);
|
||||
const char* _dev; const char* _type;
|
||||
Stream* _s = nullptr; XerbotSortie _sortie = nullptr; void* _ctx = nullptr;
|
||||
void (*_cb)(Xerbot&, const XerbotCommande&) = nullptr;
|
||||
char _l[XERBOT_LIGNE]; size_t _ln = 0; unsigned long _bat = 10000, _dernier = 0;
|
||||
};
|
||||
45
src/XerbotBLE.h
Normal file
45
src/XerbotBLE.h
Normal file
@@ -0,0 +1,45 @@
|
||||
// XerbotBLE.h — le contrat xerbot en Bluetooth (ESP32) : le service Nordic UART (6e400001-…), que le ploxion xerbot ouvre par Web Bluetooth
|
||||
// (Chrome / Edge, Android). RX = le labo écrit, TX = l'appareil notifie. Une ligne JSON par message, découpée en paquets.
|
||||
// xerbotBLE(xb, "cube-1") (dans setup, après xb.begin(Serial) si tu veux aussi l'USB : les deux marchent)
|
||||
#pragma once
|
||||
#include "Xerbot.h"
|
||||
#if !defined(ESP32)
|
||||
#error "XerbotBLE : ESP32 (NimBLE ou BLE intégré)"
|
||||
#endif
|
||||
#include <BLEDevice.h>
|
||||
#include <BLEServer.h>
|
||||
#include <BLE2902.h>
|
||||
|
||||
namespace xerbot_ble {
|
||||
static BLECharacteristic* tx = nullptr; static Xerbot* xb = nullptr; static bool connecte = false;
|
||||
static char ligne[XERBOT_LIGNE]; static size_t ln = 0;
|
||||
struct Rx : public BLECharacteristicCallbacks {
|
||||
void onWrite(BLECharacteristic* c) override {
|
||||
auto v = c->getValue();
|
||||
for (size_t i = 0; i < v.length(); i++) { char ch = v[i]; if (ch == '\r') continue; if (ch == '\n') { ligne[ln] = 0; if (ln && xb) xb->recevoir(ligne); ln = 0; } else if (ln + 1 < sizeof(ligne)) ligne[ln++] = ch; else ln = 0; }
|
||||
}
|
||||
};
|
||||
struct Srv : public BLEServerCallbacks {
|
||||
void onConnect(BLEServer*) override { connecte = true; }
|
||||
void onDisconnect(BLEServer* s) override { connecte = false; s->getAdvertising()->start(); }
|
||||
};
|
||||
static XerbotSortie usb = nullptr;
|
||||
static void sortie(const char* s, void*) {
|
||||
Serial.print(s); Serial.print('\n'); // l'USB garde la même ligne
|
||||
if (!connecte || !tx) return;
|
||||
size_t n = strlen(s); char buf[181];
|
||||
for (size_t i = 0; i <= n; i += 180) { size_t k = (n - i > 180) ? 180 : n - i; memcpy(buf, s + i, k); if (i + k >= n) buf[k++] = '\n'; tx->setValue((uint8_t*)buf, k); tx->notify(); delay(4); if (i + 180 > n) break; }
|
||||
}
|
||||
}
|
||||
inline void xerbotBLE(Xerbot& x, const char* nom) {
|
||||
using namespace xerbot_ble;
|
||||
xb = &x;
|
||||
BLEDevice::init(nom); BLEDevice::setMTU(185);
|
||||
BLEServer* s = BLEDevice::createServer(); s->setCallbacks(new Srv());
|
||||
BLEService* svc = s->createService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
|
||||
tx = svc->createCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e", BLECharacteristic::PROPERTY_NOTIFY); tx->addDescriptor(new BLE2902());
|
||||
BLECharacteristic* rx = svc->createCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
|
||||
rx->setCallbacks(new Rx()); svc->start();
|
||||
BLEAdvertising* a = s->getAdvertising(); a->addServiceUUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); a->start();
|
||||
x.sortie(sortie, nullptr);
|
||||
}
|
||||
86
src/XerbotEspNow.h
Normal file
86
src/XerbotEspNow.h
Normal file
@@ -0,0 +1,86 @@
|
||||
// XerbotEspNow.h — ESP-NOW pour le contrat xerbot (ESP32, ESP8266). Des ESP qui se parlent SANS Wi-Fi ni Internet, jusqu'à ~200 m.
|
||||
// NŒUD : xerbotEspNowNoeud(xb) → ses messages partent à la passerelle (diffusion par défaut, ou une MAC) ; ses commandes arrivent
|
||||
// PASSERELLE : xerbotEspNowPasserelle(Serial) → branchée en USB au labo (ou à un Pi) : relaie chaque pair en {"espnow":{"mac":…, …}} et renvoie
|
||||
// les commandes {"espnow":{"mac":…,"cmd":…}} au bon pair. Appeler xerbotEspNowLoop() dans loop().
|
||||
#pragma once
|
||||
#include "Xerbot.h"
|
||||
#if defined(ESP32)
|
||||
#include <WiFi.h>
|
||||
#include <esp_now.h>
|
||||
#include <esp_wifi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <espnow.h>
|
||||
#else
|
||||
#error "ESP-NOW : seulement ESP32 / ESP8266"
|
||||
#endif
|
||||
#include <string.h>
|
||||
|
||||
namespace xerbot_espnow {
|
||||
static Xerbot* noeud = nullptr; static Stream* passerelle = nullptr;
|
||||
static uint8_t cible[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
|
||||
static char ligne[XERBOT_LIGNE]; static size_t ln = 0;
|
||||
static void macTexte(const uint8_t* m, char* t) { snprintf(t, 18, "%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]); }
|
||||
static void ajouterPair(const uint8_t* m) {
|
||||
#if defined(ESP32)
|
||||
if (esp_now_is_peer_exist(m)) return; esp_now_peer_info_t p = {}; memcpy(p.peer_addr, m, 6); p.channel = 0; p.encrypt = false; esp_now_add_peer(&p);
|
||||
#else
|
||||
if (esp_now_is_peer_exist((uint8_t*)m)) return; esp_now_add_peer((uint8_t*)m, ESP_NOW_ROLE_COMBO, 1, NULL, 0);
|
||||
#endif
|
||||
}
|
||||
static void envoyer(const uint8_t* m, const char* s) { size_t n = strlen(s); if (n > 250) n = 250; esp_now_send((uint8_t*)m, (uint8_t*)s, n); }
|
||||
static void recu(const uint8_t* mac, const uint8_t* d, int n) {
|
||||
static char t[260]; if (n > 250) n = 250; memcpy(t, d, n); t[n] = 0;
|
||||
if (passerelle) { // la passerelle : {"dev":…} du pair → {"espnow":{"mac":"…","dev":…}}
|
||||
char m[18]; macTexte(mac, m); ajouterPair(mac);
|
||||
const char* corps = (t[0] == '{') ? t + 1 : t;
|
||||
passerelle->print("{\"espnow\":{\"mac\":\""); passerelle->print(m); passerelle->print("\","); passerelle->print(corps); if (t[0] != '{') passerelle->print('}'); passerelle->print("}\n");
|
||||
} else if (noeud) noeud->recevoir(t); // le nœud : une commande de la passerelle
|
||||
}
|
||||
#if defined(ESP32) && defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR >= 3
|
||||
static void recuCb(const esp_now_recv_info_t* i, const uint8_t* d, int n) { recu(i->src_addr, d, n); }
|
||||
#elif defined(ESP32)
|
||||
static void recuCb(const uint8_t* mac, const uint8_t* d, int n) { recu(mac, d, n); }
|
||||
#else
|
||||
static void recuCb(uint8_t* mac, uint8_t* d, uint8_t n) { recu(mac, d, n); } // ESP8266
|
||||
#endif
|
||||
static bool demarrer() {
|
||||
WiFi.mode(WIFI_STA); WiFi.disconnect();
|
||||
#if defined(ESP32)
|
||||
if (esp_now_init() != ESP_OK) return false;
|
||||
#else
|
||||
if (esp_now_init() != 0) return false; esp_now_set_self_role(ESP_NOW_ROLE_COMBO);
|
||||
#endif
|
||||
esp_now_register_recv_cb(recuCb); ajouterPair(cible); return true;
|
||||
}
|
||||
static void versPasserelle(const char* s, void*) { envoyer(cible, s); }
|
||||
}
|
||||
|
||||
// Un NŒUD : passe ses lignes en ESP-NOW. macPasserelle = nullptr → diffusion (toutes les passerelles à portée l'entendent).
|
||||
inline bool xerbotEspNowNoeud(Xerbot& xb, const uint8_t* macPasserelle = nullptr) {
|
||||
using namespace xerbot_espnow;
|
||||
if (macPasserelle) memcpy(cible, macPasserelle, 6);
|
||||
noeud = &xb; if (!demarrer()) return false;
|
||||
xb.sortie(versPasserelle, nullptr);
|
||||
xb.etat().add("online", true).add("via", "espnow").envoyer();
|
||||
return true;
|
||||
}
|
||||
// La PASSERELLE : ESP-NOW ⇄ le Stream (USB). Elle ne parle pas pour elle-même (elle est un fil).
|
||||
inline bool xerbotEspNowPasserelle(Stream& s) { xerbot_espnow::passerelle = &s; s.print("{\"dev\":\"passerelle-espnow\",\"type\":\"passerelle\",\"state\":{\"online\":true}}\n"); return xerbot_espnow::demarrer(); }
|
||||
inline void xerbotEspNowLoop() {
|
||||
using namespace xerbot_espnow;
|
||||
if (!passerelle) return;
|
||||
while (passerelle->available()) {
|
||||
char c = (char)passerelle->read(); if (c == '\r') continue;
|
||||
if (c != '\n') { if (ln + 1 < sizeof(ligne)) ligne[ln++] = c; else ln = 0; continue; }
|
||||
ligne[ln] = 0; ln = 0;
|
||||
// {"espnow":{"mac":"aa:bb:…","cmd":…}} → la commande part au pair
|
||||
char mac[20]; if (!Xerbot::jsonTexte(ligne, "mac", mac, sizeof(mac))) continue;
|
||||
uint8_t m[6]; unsigned int b[6];
|
||||
if (sscanf(mac, "%x:%x:%x:%x:%x:%x", &b[0], &b[1], &b[2], &b[3], &b[4], &b[5]) != 6) continue;
|
||||
for (int i = 0; i < 6; i++) m[i] = (uint8_t)b[i];
|
||||
size_t n; const char* o = Xerbot::jsonObjet(ligne, "espnow", &n); if (!o) continue;
|
||||
static char t[260]; if (n > 250) n = 250; memcpy(t, o, n); t[n] = 0;
|
||||
ajouterPair(m); envoyer(m, t);
|
||||
}
|
||||
}
|
||||
14
test/Arduino.h
Normal file
14
test/Arduino.h
Normal file
@@ -0,0 +1,14 @@
|
||||
// un faux Arduino.h pour tester le cœur sur la machine (g++)
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
inline unsigned long millis() { static unsigned long t = 0; return t += 1; }
|
||||
struct Stream {
|
||||
std::string in, out;
|
||||
int available() { return (int)in.size(); }
|
||||
int read() { char c = in[0]; in.erase(0, 1); return c; }
|
||||
void print(const char* s) { out += s; }
|
||||
void print(char c) { out += c; }
|
||||
};
|
||||
27
test/test.cpp
Normal file
27
test/test.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
#include "Arduino.h"
|
||||
#include "../src/Xerbot.h"
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
static int n = 0;
|
||||
#define OK(c, m) do { if (!(c)) { std::cout << "✗ " << m << "\n"; return 1; } n++; } while (0)
|
||||
static std::string vu;
|
||||
void cb(Xerbot& x, const XerbotCommande& c) { vu = c.cmd; char t[32]; c.texte("mode", t, sizeof t); vu += std::string("|") + t + "|" + std::to_string((int)c.nombre("w")); x.ack(c.id, true); }
|
||||
int main() {
|
||||
Stream s; Xerbot xb("cube-1", "capteur"); xb.battement(0); xb.begin(s);
|
||||
OK(s.out == "{\"dev\":\"cube-1\",\"type\":\"capteur\",\"state\":{\"online\":true}}\n", "begin annonce l'état");
|
||||
s.out.clear(); xb.onCommande(cb);
|
||||
xb.telemetrie().add("t", 21.5).add("n", 3).add("nom", "a\"b").add("ok", true).envoyer();
|
||||
OK(s.out == "{\"dev\":\"cube-1\",\"type\":\"capteur\",\"telemetry\":{\"t\":21.50,\"n\":3,\"nom\":\"a\\\"b\",\"ok\":true}}\n", "télémétrie (échappement)");
|
||||
s.out.clear(); s.in = "{\"dev\":\"cube-1\",\"cmd\":\"chauffe\",\"args\":{\"mode\":\"torse\",\"w\":15},\"id\":\"x1\"}\n"; xb.loop();
|
||||
OK(vu == "chauffe|torse|15", "commande + args : " + vu);
|
||||
OK(s.out == "{\"dev\":\"cube-1\",\"type\":\"capteur\",\"ack\":{\"id\":\"x1\",\"ok\":true}}\n", "ack corrélé par id");
|
||||
s.out.clear(); vu = ""; s.in = "{\"dev\":\"autre\",\"cmd\":\"x\",\"id\":\"y\"}\n"; xb.loop();
|
||||
OK(vu.empty() && s.out.empty(), "une commande pour un autre appareil est ignorée");
|
||||
s.in = "{\"cmd\":\"ping\",\"id\":\"p\"}\n"; xb.loop();
|
||||
OK(s.out.find("\"ack\":{\"id\":\"p\",\"ok\":true}") != std::string::npos, "ping répond tout seul");
|
||||
s.out.clear(); s.in = "{\"hello\":\"xerboxion\"}\n"; xb.loop();
|
||||
OK(s.out.find("\"state\":{\"online\":true}") != std::string::npos, "hello → l'état");
|
||||
s.out.clear(); std::string longue(5000, 'a'); s.in = longue + "\n{\"cmd\":\"ping\",\"id\":\"z\"}\n"; xb.loop();
|
||||
OK(s.out.find("\"id\":\"z\"") != std::string::npos, "une ligne trop longue est jetée, la suivante passe");
|
||||
std::cout << "xerbot : " << n << "/" << n << "\n"; return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user