main.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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/RadioLibWrappers.h>
  7. #include <helpers/ArduinoHelpers.h>
  8. #include <helpers/StaticPoolPacketManager.h>
  9. #include <helpers/SimpleMeshTables.h>
  10. /* ------------------------------ Config -------------------------------- */
  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. #ifdef HELTEC_LORA_V3
  24. #include <helpers/HeltecV3Board.h>
  25. static HeltecV3Board board;
  26. #else
  27. #error "need to provide a 'board' object"
  28. #endif
  29. /* ------------------------------ Code -------------------------------- */
  30. struct ClientInfo {
  31. mesh::Identity id;
  32. uint32_t last_timestamp;
  33. uint8_t secret[PUB_KEY_SIZE];
  34. int out_path_len;
  35. uint8_t out_path[MAX_PATH_SIZE];
  36. };
  37. #define MAX_CLIENTS 4
  38. class MyMesh : public mesh::Mesh {
  39. int num_clients;
  40. ClientInfo known_clients[MAX_CLIENTS];
  41. ClientInfo* putClient(const mesh::Identity& id) {
  42. for (int i = 0; i < num_clients; i++) {
  43. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  44. }
  45. if (num_clients < MAX_CLIENTS) {
  46. auto newClient = &known_clients[num_clients++];
  47. newClient->id = id;
  48. newClient->out_path_len = -1; // initially out_path is unknown
  49. newClient->last_timestamp = 0;
  50. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  51. return newClient;
  52. }
  53. return NULL; // table is full
  54. }
  55. protected:
  56. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  57. if (type == PAYLOAD_TYPE_ANON_REQ) { // received a PING!
  58. uint32_t timestamp;
  59. memcpy(&timestamp, data, 4);
  60. auto client = putClient(sender); // add to known clients (if not already known)
  61. if (client == NULL || timestamp <= client->last_timestamp) {
  62. return; // FATAL: client table is full -OR- replay attack
  63. }
  64. client->last_timestamp = timestamp;
  65. uint32_t now = getRTCClock()->getCurrentTime(); // response packets always prefixed with timestamp
  66. if (packet->isRouteFlood()) {
  67. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the Ping response
  68. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  69. PAYLOAD_TYPE_RESPONSE, (uint8_t *) &now, sizeof(now));
  70. if (path) sendFlood(path);
  71. } else {
  72. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, (uint8_t *) &now, sizeof(now));
  73. if (reply) {
  74. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  75. sendDirect(reply, client->out_path, client->out_path_len);
  76. } else {
  77. sendFlood(reply);
  78. }
  79. }
  80. }
  81. }
  82. }
  83. int matching_peer_indexes[MAX_CLIENTS];
  84. int searchPeersByHash(const uint8_t* hash) override {
  85. int n = 0;
  86. for (int i = 0; i < num_clients; i++) {
  87. if (known_clients[i].id.isHashMatch(hash)) {
  88. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  89. }
  90. }
  91. return n;
  92. }
  93. // not needed for this example, but for sake of 'completeness' of Mesh impl
  94. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  95. if (peer_idx >= 0 && peer_idx < MAX_CLIENTS) {
  96. // lookup pre-calculated shared_secret
  97. int i = matching_peer_indexes[peer_idx];
  98. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  99. } else {
  100. MESH_DEBUG_PRINTLN("Invalid peer_idx: %d", peer_idx);
  101. }
  102. }
  103. 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 {
  104. if (sender_idx >= 0 && sender_idx < MAX_CLIENTS) {
  105. Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
  106. // TODO: prevent replay attacks
  107. int i = matching_peer_indexes[sender_idx];
  108. if (i >= 0 && i < num_clients) {
  109. auto client = &known_clients[i]; // get from our known_clients table (sender SHOULD already be known in this context)
  110. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  111. }
  112. } else {
  113. MESH_DEBUG_PRINTLN("Invalid sender_idx: %d", sender_idx);
  114. }
  115. // NOTE: no reciprocal path send!!
  116. return false;
  117. }
  118. public:
  119. MyMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  120. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(16), tables)
  121. {
  122. num_clients = 0;
  123. }
  124. };
  125. SPIClass spi;
  126. StdRNG fast_rng;
  127. SimpleMeshTables tables;
  128. SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  129. MyMesh the_mesh(*new RadioLibWrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
  130. unsigned long nextAnnounce;
  131. void halt() {
  132. while (1) ;
  133. }
  134. void setup() {
  135. Serial.begin(115200);
  136. board.begin();
  137. #if defined(P_LORA_SCLK)
  138. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  139. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
  140. #else
  141. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
  142. #endif
  143. if (status != RADIOLIB_ERR_NONE) {
  144. Serial.print("ERROR: radio init failed: ");
  145. Serial.println(status);
  146. halt();
  147. }
  148. fast_rng.begin(radio.random(0x7FFFFFFF));
  149. the_mesh.begin();
  150. RadioNoiseListener true_rng(radio);
  151. the_mesh.self_id = mesh::LocalIdentity(&true_rng); // create new random identity
  152. nextAnnounce = 0;
  153. }
  154. void loop() {
  155. if (the_mesh.millisHasNowPassed(nextAnnounce)) {
  156. mesh::Packet* pkt = the_mesh.createAdvert(the_mesh.self_id, (const uint8_t *)"PING", 4);
  157. if (pkt) the_mesh.sendFlood(pkt);
  158. nextAnnounce = the_mesh.futureMillis(30000); // announce every 30 seconds (test only, don't do in production!)
  159. }
  160. the_mesh.loop();
  161. // TODO: periodically check for OLD entries in known_clients[], and evict
  162. }