main.cpp 10 KB

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