main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #if defined(NRF52_PLATFORM)
  4. #include <InternalFileSystem.h>
  5. #elif defined(ESP32)
  6. #include <SPIFFS.h>
  7. #endif
  8. #define RADIOLIB_STATIC_ONLY 1
  9. #include <RadioLib.h>
  10. #include <helpers/CustomSX1262Wrapper.h>
  11. #include <helpers/ArduinoHelpers.h>
  12. #include <helpers/StaticPoolPacketManager.h>
  13. #include <helpers/SimpleMeshTables.h>
  14. #include <helpers/IdentityStore.h>
  15. /* ------------------------------ Config -------------------------------- */
  16. #ifndef LORA_FREQ
  17. #define LORA_FREQ 915.0
  18. #endif
  19. #ifndef LORA_BW
  20. #define LORA_BW 250
  21. #endif
  22. #ifndef LORA_SF
  23. #define LORA_SF 10
  24. #endif
  25. #ifndef LORA_CR
  26. #define LORA_CR 5
  27. #endif
  28. #ifndef LORA_TX_POWER
  29. #defne LORA_TX_POWER 20
  30. #endif
  31. #ifndef ADVERT_NAME
  32. #define ADVERT_NAME "repeater"
  33. #endif
  34. #ifndef ADVERT_LAT
  35. #define ADVERT_LAT 0.0
  36. #endif
  37. #ifndef ADVERT_LON
  38. #define ADVERT_LON 0.0
  39. #endif
  40. #ifndef ADMIN_PASSWORD
  41. #define ADMIN_PASSWORD "h^(kl@#)"
  42. #endif
  43. #if defined(HELTEC_LORA_V3)
  44. #include <helpers/HeltecV3Board.h>
  45. static HeltecV3Board board;
  46. #elif defined(ARDUINO_XIAO_ESP32C3)
  47. #include <helpers/XiaoC3Board.h>
  48. #include <helpers/CustomSX1262Wrapper.h>
  49. #include <helpers/CustomSX1268Wrapper.h>
  50. static XiaoC3Board board;
  51. #elif defined(SEEED_XIAO_S3)
  52. #include <helpers/ESP32Board.h>
  53. #include <helpers/CustomSX1262Wrapper.h>
  54. static ESP32Board board;
  55. #elif defined(RAK_4631)
  56. #include <helpers/RAK4631Board.h>
  57. #include <helpers/CustomSX1262Wrapper.h>
  58. static RAK4631Board board;
  59. #else
  60. #error "need to provide a 'board' object"
  61. #endif
  62. /* ------------------------------ Code -------------------------------- */
  63. #define CMD_GET_STATS 0x01
  64. #define CMD_SET_CLOCK 0x02
  65. #define CMD_SEND_ANNOUNCE 0x03
  66. #define CMD_SET_CONFIG 0x04
  67. struct RepeaterStats {
  68. uint16_t batt_milli_volts;
  69. uint16_t curr_tx_queue_len;
  70. uint16_t curr_free_queue_len;
  71. int16_t last_rssi;
  72. uint32_t n_packets_recv;
  73. uint32_t n_packets_sent;
  74. uint32_t total_air_time_secs;
  75. uint32_t total_up_time_secs;
  76. uint32_t n_sent_flood, n_sent_direct;
  77. uint32_t n_recv_flood, n_recv_direct;
  78. uint32_t n_full_events;
  79. };
  80. struct ClientInfo {
  81. mesh::Identity id;
  82. uint32_t last_timestamp;
  83. uint8_t secret[PUB_KEY_SIZE];
  84. int out_path_len;
  85. uint8_t out_path[MAX_PATH_SIZE];
  86. };
  87. #define MAX_CLIENTS 4
  88. class MyMesh : public mesh::Mesh {
  89. RadioLibWrapper* my_radio;
  90. float airtime_factor;
  91. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  92. int num_clients;
  93. ClientInfo known_clients[MAX_CLIENTS];
  94. ClientInfo* putClient(const mesh::Identity& id) {
  95. for (int i = 0; i < num_clients; i++) {
  96. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  97. }
  98. if (num_clients < MAX_CLIENTS) {
  99. auto newClient = &known_clients[num_clients++];
  100. newClient->id = id;
  101. newClient->out_path_len = -1; // initially out_path is unknown
  102. newClient->last_timestamp = 0;
  103. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  104. return newClient;
  105. }
  106. return NULL; // table is full
  107. }
  108. int handleRequest(ClientInfo* sender, uint8_t* payload, size_t payload_len) {
  109. uint32_t now = getRTCClock()->getCurrentTime();
  110. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  111. switch (payload[0]) {
  112. case CMD_GET_STATS: {
  113. uint32_t max_age_secs;
  114. if (payload_len >= 5) {
  115. memcpy(&max_age_secs, &payload[1], 4); // first param in request pkt
  116. } else {
  117. max_age_secs = 12*60*60; // default, 12 hours
  118. }
  119. RepeaterStats stats;
  120. stats.batt_milli_volts = board.getBattMilliVolts();
  121. stats.curr_tx_queue_len = _mgr->getOutboundCount();
  122. stats.curr_free_queue_len = _mgr->getFreeCount();
  123. stats.last_rssi = (int16_t) my_radio->getLastRSSI();
  124. stats.n_packets_recv = my_radio->getPacketsRecv();
  125. stats.n_packets_sent = my_radio->getPacketsSent();
  126. stats.total_air_time_secs = getTotalAirTime() / 1000;
  127. stats.total_up_time_secs = _ms->getMillis() / 1000;
  128. stats.n_sent_flood = getNumSentFlood();
  129. stats.n_sent_direct = getNumSentDirect();
  130. stats.n_recv_flood = getNumRecvFlood();
  131. stats.n_recv_direct = getNumRecvDirect();
  132. stats.n_full_events = getNumFullEvents();
  133. memcpy(&reply_data[4], &stats, sizeof(stats));
  134. return 4 + sizeof(stats); // reply_len
  135. }
  136. case CMD_SET_CLOCK: {
  137. if (payload_len >= 5) {
  138. uint32_t curr_epoch_secs;
  139. memcpy(&curr_epoch_secs, &payload[1], 4); // first param is current UNIX time
  140. if (curr_epoch_secs > now) { // time can only go forward!!
  141. getRTCClock()->setCurrentTime(curr_epoch_secs);
  142. memcpy(&reply_data[4], "OK", 2);
  143. } else {
  144. memcpy(&reply_data[4], "ER", 2);
  145. }
  146. return 4 + 2; // reply_len
  147. }
  148. return 0; // invalid request
  149. }
  150. case CMD_SEND_ANNOUNCE: {
  151. // broadcast another self Advertisement
  152. sendSelfAdvertisement();
  153. memcpy(&reply_data[4], "OK", 2);
  154. return 4 + 2; // reply_len
  155. }
  156. case CMD_SET_CONFIG: {
  157. if (payload_len >= 4 && payload_len < 32 && memcmp(&payload[1], "AF", 2) == 0) {
  158. payload[payload_len] = 0; // make it a C string
  159. airtime_factor = atof((char *) &payload[3]);
  160. memcpy(&reply_data[4], "OK", 2);
  161. return 4 + 2; // reply_len
  162. }
  163. return 0; // unknown config var
  164. }
  165. }
  166. // unknown command
  167. return 0; // reply_len
  168. }
  169. protected:
  170. float getAirtimeBudgetFactor() const override {
  171. return airtime_factor;
  172. }
  173. bool allowPacketForward(const mesh::Packet* packet) override {
  174. return true; // Yes, allow packet to be forwarded
  175. }
  176. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  177. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  178. uint32_t timestamp;
  179. memcpy(&timestamp, data, 4);
  180. if (memcmp(&data[4], ADMIN_PASSWORD, 8) == 0) { // check for valid password
  181. auto client = putClient(sender); // add to known clients (if not already known)
  182. if (client == NULL || timestamp <= client->last_timestamp) {
  183. MESH_DEBUG_PRINTLN("Client table full, or replay attack!");
  184. return; // FATAL: client table is full -OR- replay attack
  185. }
  186. MESH_DEBUG_PRINTLN("Login success!");
  187. client->last_timestamp = timestamp;
  188. uint32_t now = getRTCClock()->getCurrentTime();
  189. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  190. memcpy(&reply_data[4], "OK", 2);
  191. if (packet->isRouteFlood()) {
  192. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  193. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  194. PAYLOAD_TYPE_RESPONSE, reply_data, 4 + 2);
  195. if (path) sendFlood(path);
  196. } else {
  197. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 4 + 2);
  198. if (reply) {
  199. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  200. sendDirect(reply, client->out_path, client->out_path_len);
  201. } else {
  202. sendFlood(reply);
  203. }
  204. }
  205. }
  206. } else {
  207. data[4+8] = 0; // ensure null terminator
  208. MESH_DEBUG_PRINTLN("Incorrect password: %s", &data[4]);
  209. }
  210. }
  211. }
  212. int matching_peer_indexes[MAX_CLIENTS];
  213. int searchPeersByHash(const uint8_t* hash) override {
  214. int n = 0;
  215. for (int i = 0; i < num_clients; i++) {
  216. if (known_clients[i].id.isHashMatch(hash)) {
  217. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  218. }
  219. }
  220. return n;
  221. }
  222. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  223. int i = matching_peer_indexes[peer_idx];
  224. if (i >= 0 && i < num_clients) {
  225. // lookup pre-calculated shared_secret
  226. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  227. } else {
  228. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  229. }
  230. }
  231. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  232. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  233. int i = matching_peer_indexes[sender_idx];
  234. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  235. auto client = &known_clients[i];
  236. uint32_t timestamp;
  237. memcpy(&timestamp, data, 4);
  238. if (timestamp > client->last_timestamp) { // prevent replay attacks
  239. int reply_len = handleRequest(client, &data[4], len - 4);
  240. if (reply_len == 0) return; // invalid command
  241. client->last_timestamp = timestamp;
  242. if (packet->isRouteFlood()) {
  243. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  244. mesh::Packet* path = createPathReturn(client->id, secret, packet->path, packet->path_len,
  245. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  246. if (path) sendFlood(path);
  247. } else {
  248. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
  249. if (reply) {
  250. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  251. sendDirect(reply, client->out_path, client->out_path_len);
  252. } else {
  253. sendFlood(reply);
  254. }
  255. }
  256. }
  257. }
  258. } else {
  259. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  260. }
  261. }
  262. }
  263. bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
  264. // TODO: prevent replay attacks
  265. int i = matching_peer_indexes[sender_idx];
  266. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  267. MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
  268. auto client = &known_clients[i];
  269. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  270. } else {
  271. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  272. }
  273. // NOTE: no reciprocal path send!!
  274. return false;
  275. }
  276. public:
  277. MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  278. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables)
  279. {
  280. my_radio = &radio;
  281. airtime_factor = 1.0; // one half
  282. num_clients = 0;
  283. }
  284. #define ADV_TYPE_NONE 0 // unknown
  285. #define ADV_TYPE_CHAT 1
  286. #define ADV_TYPE_REPEATER 2
  287. //FUTURE: 3..15
  288. #define ADV_LATLON_MASK 0x10
  289. #define ADV_BATTERY_MASK 0x20
  290. #define ADV_TEMPERATURE_MASK 0x40
  291. #define ADV_NAME_MASK 0x80
  292. void sendSelfAdvertisement() {
  293. uint8_t app_data[MAX_ADVERT_DATA_SIZE+32];
  294. app_data[0] = ADV_TYPE_REPEATER | ADV_NAME_MASK;
  295. int i = 1;
  296. int32_t lat = ADVERT_LAT * 1E6;
  297. int32_t lon = ADVERT_LON * 1E6;
  298. if (!(lat == 0 && lon == 0)) {
  299. app_data[0] |= ADV_LATLON_MASK;
  300. memcpy(&app_data[i], &lat, 4); i += 4;
  301. memcpy(&app_data[i], &lon, 4); i += 4;
  302. }
  303. strcpy((char *)&app_data[i], ADVERT_NAME);
  304. int app_data_len = i + strlen(ADVERT_NAME);
  305. if (app_data_len > MAX_ADVERT_DATA_SIZE) {
  306. app_data_len = MAX_ADVERT_DATA_SIZE;
  307. app_data[MAX_ADVERT_DATA_SIZE - 1] = 0; // truncate the ADVERT_NAME
  308. }
  309. mesh::Packet* pkt = createAdvert(self_id, app_data, app_data_len);
  310. if (pkt) {
  311. sendFlood(pkt, 800); // add slight delay
  312. } else {
  313. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  314. }
  315. }
  316. };
  317. #if defined(NRF52_PLATFORM)
  318. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  319. #elif defined(P_LORA_SCLK)
  320. SPIClass spi;
  321. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  322. #else
  323. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  324. #endif
  325. StdRNG fast_rng;
  326. SimpleMeshTables tables;
  327. MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
  328. void halt() {
  329. while (1) ;
  330. }
  331. static char command[80];
  332. void setup() {
  333. Serial.begin(115200);
  334. delay(1000);
  335. board.begin();
  336. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  337. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  338. #else
  339. float tcxo = 1.6f;
  340. #endif
  341. #if defined(NRF52_PLATFORM)
  342. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  343. SPI.begin();
  344. #elif defined(P_LORA_SCLK)
  345. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  346. #endif
  347. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  348. if (status != RADIOLIB_ERR_NONE) {
  349. delay(5000);
  350. Serial.print("ERROR: radio init failed: ");
  351. Serial.println(status);
  352. halt();
  353. }
  354. radio.setCRC(0);
  355. #ifdef SX126X_CURRENT_LIMIT
  356. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  357. #endif
  358. #ifdef SX126X_DIO2_AS_RF_SWITCH
  359. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  360. #endif
  361. #if defined(NRF52_PLATFORM)
  362. InternalFS.begin();
  363. IdentityStore store(InternalFS, "/identity");
  364. #elif defined(ESP32)
  365. SPIFFS.begin(true);
  366. IdentityStore store(SPIFFS, "/identity");
  367. #else
  368. #error "need to define filesystem"
  369. #endif
  370. if (!store.load("_main", the_mesh.self_id)) {
  371. the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
  372. store.save("_main", the_mesh.self_id);
  373. }
  374. Serial.print("Repeater ID: ");
  375. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  376. command[0] = 0;
  377. the_mesh.begin();
  378. // send out initial Advertisement to the mesh
  379. the_mesh.sendSelfAdvertisement();
  380. }
  381. void loop() {
  382. int len = strlen(command);
  383. while (Serial.available() && len < sizeof(command)-1) {
  384. char c = Serial.read();
  385. if (c != '\n') {
  386. command[len++] = c;
  387. command[len] = 0;
  388. }
  389. Serial.print(c);
  390. }
  391. if (len == sizeof(command)-1) { // command buffer full
  392. command[sizeof(command)-1] = '\r';
  393. }
  394. if (len > 0 && command[len - 1] == '\r') { // received complete line
  395. command[len - 1] = 0; // replace newline with C string null terminator
  396. if (strcmp(command, "reboot") == 0) {
  397. board.reboot(); // doesn't return
  398. } else if (strcmp(command, "advert") == 0) {
  399. the_mesh.sendSelfAdvertisement();
  400. } else {
  401. Serial.print(" ERROR: unknown command: "); Serial.println(command);
  402. Serial.println(" (commands: reboot, advert)");
  403. }
  404. command[0] = 0; // reset command buffer
  405. }
  406. the_mesh.loop();
  407. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  408. }