main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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/SimpleSeenTable.h>
  9. #include <helpers/StaticPoolPacketManager.h>
  10. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  11. #define ADMIN_PASSWORD "h^(kl@#)"
  12. #ifdef HELTEC_LORA_V3
  13. #include <helpers/HeltecV3Board.h>
  14. static HeltecV3Board board;
  15. #else
  16. #error "need to provide a 'board' object"
  17. #endif
  18. /* -------------------------------------------------------------------------------------- */
  19. #define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - FROM_HASH_LEN - CIPHER_MAC_SIZE - 1)
  20. #define CMD_GET_STATS 0x01
  21. #define CMD_SET_CLOCK 0x02
  22. #define CMD_SEND_ANNOUNCE 0x03
  23. #define CMD_SET_CONFIG 0x04
  24. struct RepeaterStats {
  25. uint16_t batt_milli_volts;
  26. uint16_t curr_tx_queue_len;
  27. uint16_t curr_free_queue_len;
  28. int16_t last_rssi;
  29. uint32_t n_packets_recv;
  30. uint32_t n_packets_sent;
  31. uint32_t total_air_time_secs;
  32. uint32_t total_up_time_secs;
  33. };
  34. class MyMesh : public mesh::Mesh {
  35. SimpleSeenTable* _table;
  36. uint32_t last_advert_timestamp = 0;
  37. mesh::Identity server_id;
  38. uint8_t server_secret[PUB_KEY_SIZE];
  39. int server_path_len = -1;
  40. uint8_t server_path[MAX_PATH_SIZE];
  41. bool got_adv = false;
  42. protected:
  43. int searchPeersByHash(const uint8_t* hash) override {
  44. if (got_adv && server_id.isHashMatch(hash)) {
  45. return 1;
  46. }
  47. return 0; // not found
  48. }
  49. void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
  50. if (memcmp(app_data, "repeater:", 9) == 0) {
  51. Serial.println("Received advertisement from a repeater!");
  52. // check for replay attacks
  53. if (timestamp > last_advert_timestamp) {
  54. last_advert_timestamp = timestamp;
  55. server_id = id;
  56. self_id.calcSharedSecret(server_secret, id); // calc ECDH shared secret
  57. got_adv = true;
  58. // 'login' to repeater. (mainly lets it know our public key)
  59. uint32_t now = getRTCClock()->getCurrentTime(); // important, need timestamp in packet, so that packet_hash will be unique
  60. uint8_t temp[4 + 8];
  61. memcpy(temp, &now, 4);
  62. memcpy(&temp[4], ADMIN_PASSWORD, 8);
  63. mesh::Packet* login = createDatagram(PAYLOAD_TYPE_ANON_REQ, server_id, server_secret, temp, sizeof(temp));
  64. if (login) sendFlood(login); // server_path won't be known yet
  65. }
  66. }
  67. }
  68. void handleResponse(const uint8_t* reply, size_t reply_len) {
  69. if (reply_len >= 4 + sizeof(RepeaterStats)) { // got an GET_STATS reply from repeater
  70. RepeaterStats stats;
  71. memcpy(&stats, &reply[4], sizeof(stats));
  72. Serial.println("Repeater Stats:");
  73. Serial.printf(" battery: %d mV\n", (uint32_t) stats.batt_milli_volts);
  74. Serial.printf(" tx queue: %d\n", (uint32_t) stats.curr_tx_queue_len);
  75. Serial.printf(" free queue: %d\n", (uint32_t) stats.curr_free_queue_len);
  76. Serial.printf(" last RSSI: %d\n", (int) stats.last_rssi);
  77. Serial.printf(" num recv: %d\n", stats.n_packets_recv);
  78. Serial.printf(" num sent: %d\n", stats.n_packets_sent);
  79. Serial.printf(" air time (secs): %d\n", stats.total_air_time_secs);
  80. Serial.printf(" up time (secs): %d\n", stats.total_up_time_secs);
  81. } else if (reply_len > 4) { // got an SET_* reply from repeater
  82. char tmp[MAX_PACKET_PAYLOAD];
  83. memcpy(tmp, &reply[4], reply_len - 4);
  84. tmp[reply_len - 4] = 0; // make a C string of reply
  85. Serial.print("Reply: "); Serial.println(tmp);
  86. }
  87. }
  88. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
  89. if (type == PAYLOAD_TYPE_RESPONSE) {
  90. if (_table->hasSeenPacket(packet)) return;
  91. handleResponse(data, len);
  92. if (packet->isRouteFlood()) {
  93. // let server know path TO here, so they can use sendDirect() for future ping responses
  94. mesh::Packet* path = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
  95. if (path) sendFlood(path);
  96. }
  97. }
  98. }
  99. void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
  100. if (_table->hasSeenPacket(packet)) return;
  101. // must be from server_id
  102. Serial.printf("PATH to repeater, path_len=%d\n", (uint32_t) path_len);
  103. memcpy(server_path, path, server_path_len = path_len); // store a copy of path, for sendDirect()
  104. if (packet->isRouteFlood()) {
  105. // send a reciprocal return path to sender, but send DIRECTLY!
  106. mesh::Packet* rpath = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
  107. if (rpath) sendDirect(rpath, path, path_len);
  108. }
  109. if (extra_type == PAYLOAD_TYPE_RESPONSE) {
  110. handleResponse(extra, extra_len);
  111. }
  112. }
  113. public:
  114. MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleSeenTable& table)
  115. : mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16)), _table(&table)
  116. {
  117. }
  118. mesh::Packet* createStatsRequest(uint32_t max_age) {
  119. uint8_t payload[9];
  120. uint32_t now = getRTCClock()->getCurrentTime();
  121. memcpy(payload, &now, 4);
  122. payload[4] = CMD_GET_STATS;
  123. memcpy(&payload[5], &max_age, 4);
  124. return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
  125. }
  126. mesh::Packet* createSetClockRequest(uint32_t timestamp) {
  127. uint8_t payload[9];
  128. uint32_t now = getRTCClock()->getCurrentTime();
  129. memcpy(payload, &now, 4);
  130. payload[4] = CMD_SET_CLOCK;
  131. memcpy(&payload[5], &now, 4); // repeated :-(
  132. return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
  133. }
  134. mesh::Packet* createSetAirtimeFactorRequest(float airtime_factor) {
  135. uint8_t payload[16];
  136. uint32_t now = getRTCClock()->getCurrentTime();
  137. memcpy(payload, &now, 4);
  138. payload[4] = CMD_SET_CONFIG;
  139. sprintf((char *) &payload[5], "AF%f", airtime_factor);
  140. return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
  141. }
  142. mesh::Packet* createAnnounceRequest() {
  143. uint8_t payload[5];
  144. uint32_t now = getRTCClock()->getCurrentTime();
  145. memcpy(payload, &now, 4);
  146. payload[4] = CMD_SEND_ANNOUNCE;
  147. return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
  148. }
  149. mesh::Packet* parseCommand(char* command) {
  150. if (strcmp(command, "stats") == 0) {
  151. return createStatsRequest(60*60); // max_age = one hour
  152. } else if (memcmp(command, "setclock ", 9) == 0) {
  153. uint32_t timestamp = atol(&command[9]);
  154. return createSetClockRequest(timestamp);
  155. } else if (memcmp(command, "set AF=", 7) == 0) {
  156. float factor = atof(&command[7]);
  157. return createSetAirtimeFactorRequest(factor);
  158. } else if (strcmp(command, "ann") == 0) {
  159. return createAnnounceRequest();
  160. }
  161. return NULL; // unknown command
  162. }
  163. void sendCommand(mesh::Packet* pkt) {
  164. if (server_path_len < 0) {
  165. sendFlood(pkt);
  166. } else {
  167. sendDirect(pkt, server_path, server_path_len);
  168. }
  169. }
  170. };
  171. StdRNG fast_rng;
  172. SimpleSeenTable table;
  173. #if defined(P_LORA_SCLK)
  174. SPIClass spi;
  175. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  176. #else
  177. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  178. #endif
  179. MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), fast_rng, *new VolatileRTCClock(), table);
  180. void halt() {
  181. while (1) ;
  182. }
  183. static char command[MAX_TEXT_LEN+1];
  184. #include <SHA256.h>
  185. void setup() {
  186. Serial.begin(115200);
  187. delay(5000);
  188. board.begin();
  189. #if defined(P_LORA_SCLK)
  190. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  191. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  192. #else
  193. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  194. #endif
  195. if (status != RADIOLIB_ERR_NONE) {
  196. Serial.print("ERROR: radio init failed: ");
  197. Serial.println(status);
  198. halt();
  199. }
  200. fast_rng.begin(radio.random(0x7FFFFFFF));
  201. /* add this to tests
  202. uint8_t mac_encrypted[CIPHER_MAC_SIZE+CIPHER_BLOCK_SIZE];
  203. const char *orig_msg = "original";
  204. int enc_len = mesh::Utils::encryptThenMAC(mesh.admin_secret, mac_encrypted, (const uint8_t *) orig_msg, strlen(orig_msg));
  205. char decrypted[CIPHER_BLOCK_SIZE*2];
  206. int len = mesh::Utils::MACThenDecrypt(mesh.admin_secret, (uint8_t *)decrypted, mac_encrypted, enc_len);
  207. if (len > 0) {
  208. decrypted[len] = 0;
  209. Serial.print("decrypted text: "); Serial.println(decrypted);
  210. } else {
  211. Serial.println("MACs DONT match!");
  212. }
  213. */
  214. Serial.println("Help:");
  215. Serial.println(" enter 'key' to generate new keypair");
  216. Serial.println(" enter 'stats' to request repeater stats");
  217. Serial.println(" enter 'setclock {unix-epoch-seconds}' to set repeater's clock");
  218. Serial.println(" enter 'set AF={factor}' to set airtime budget factor");
  219. Serial.println(" enter 'ann' to make repeater re-announce to mesh");
  220. the_mesh.begin();
  221. command[0] = 0;
  222. }
  223. void loop() {
  224. int len = strlen(command);
  225. while (Serial.available() && len < sizeof(command)-1) {
  226. char c = Serial.read();
  227. if (c != '\n') {
  228. command[len++] = c;
  229. command[len] = 0;
  230. }
  231. Serial.print(c);
  232. }
  233. if (len == sizeof(command)-1) { // command buffer full
  234. command[sizeof(command)-1] = '\r';
  235. }
  236. if (len > 0 && command[len - 1] == '\r') { // received complete line
  237. command[len - 1] = 0; // replace newline with C string null terminator
  238. if (strcmp(command, "key") == 0) {
  239. mesh::LocalIdentity new_id(the_mesh.getRNG());
  240. new_id.printTo(Serial);
  241. } else {
  242. mesh::Packet* pkt = the_mesh.parseCommand(command);
  243. if (pkt) {
  244. the_mesh.sendCommand(pkt);
  245. Serial.println(" (request sent)");
  246. } else {
  247. Serial.print(" ERROR: unknown command: "); Serial.println(command);
  248. }
  249. }
  250. command[0] = 0; // reset command buffer
  251. }
  252. the_mesh.loop();
  253. }