main.cpp 14 KB

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