main.cpp 5.8 KB

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