main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. #define ANNOUNCE_DATA "repeater:v1"
  13. #define ADMIN_PASSWORD "h^(kl@#)"
  14. #if defined(HELTEC_LORA_V3)
  15. #include <helpers/HeltecV3Board.h>
  16. static HeltecV3Board board;
  17. #else
  18. #error "need to provide a 'board' object"
  19. #endif
  20. /* ------------------------------ Code -------------------------------- */
  21. #define CMD_GET_STATS 0x01
  22. #define CMD_SET_CLOCK 0x02
  23. #define CMD_SEND_ANNOUNCE 0x03
  24. #define CMD_SET_CONFIG 0x04
  25. struct RepeaterStats {
  26. uint16_t batt_milli_volts;
  27. uint16_t curr_tx_queue_len;
  28. uint16_t curr_free_queue_len;
  29. int16_t last_rssi;
  30. uint32_t n_packets_recv;
  31. uint32_t n_packets_sent;
  32. uint32_t total_air_time_secs;
  33. uint32_t total_up_time_secs;
  34. };
  35. struct ClientInfo {
  36. mesh::Identity id;
  37. uint32_t last_timestamp;
  38. uint8_t secret[PUB_KEY_SIZE];
  39. int out_path_len;
  40. uint8_t out_path[MAX_PATH_SIZE];
  41. };
  42. #define MAX_CLIENTS 4
  43. class MyMesh : public mesh::Mesh {
  44. RadioLibWrapper* my_radio;
  45. float airtime_factor;
  46. uint8_t reply_data[MAX_PACKET_PAYLOAD];
  47. int num_clients;
  48. ClientInfo known_clients[MAX_CLIENTS];
  49. ClientInfo* putClient(const mesh::Identity& id) {
  50. for (int i = 0; i < num_clients; i++) {
  51. if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
  52. }
  53. if (num_clients < MAX_CLIENTS) {
  54. auto newClient = &known_clients[num_clients++];
  55. newClient->id = id;
  56. newClient->out_path_len = -1; // initially out_path is unknown
  57. newClient->last_timestamp = 0;
  58. self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
  59. return newClient;
  60. }
  61. return NULL; // table is full
  62. }
  63. int handleRequest(ClientInfo* sender, uint8_t* payload, size_t payload_len) {
  64. uint32_t now = getRTCClock()->getCurrentTime();
  65. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  66. switch (payload[0]) {
  67. case CMD_GET_STATS: {
  68. uint32_t max_age_secs;
  69. if (payload_len >= 5) {
  70. memcpy(&max_age_secs, &payload[1], 4); // first param in request pkt
  71. } else {
  72. max_age_secs = 12*60*60; // default, 12 hours
  73. }
  74. RepeaterStats stats;
  75. stats.batt_milli_volts = board.getBattMilliVolts();
  76. stats.curr_tx_queue_len = _mgr->getOutboundCount();
  77. stats.curr_free_queue_len = _mgr->getFreeCount();
  78. stats.last_rssi = (int16_t) my_radio->getLastRSSI();
  79. stats.n_packets_recv = my_radio->getPacketsRecv();
  80. stats.n_packets_sent = my_radio->getPacketsSent();
  81. stats.total_air_time_secs = getTotalAirTime() / 1000;
  82. stats.total_up_time_secs = _ms->getMillis() / 1000;
  83. memcpy(&reply_data[4], &stats, sizeof(stats));
  84. return 4 + sizeof(stats); // reply_len
  85. }
  86. case CMD_SET_CLOCK: {
  87. if (payload_len >= 5) {
  88. uint32_t curr_epoch_secs;
  89. memcpy(&curr_epoch_secs, &payload[1], 4); // first param is current UNIX time
  90. if (curr_epoch_secs > now) { // time can only go forward!!
  91. getRTCClock()->setCurrentTime(curr_epoch_secs);
  92. memcpy(&reply_data[4], "OK", 2);
  93. } else {
  94. memcpy(&reply_data[4], "ER", 2);
  95. }
  96. return 4 + 2; // reply_len
  97. }
  98. return 0; // invalid request
  99. }
  100. case CMD_SEND_ANNOUNCE: {
  101. // broadcast another self Advertisement
  102. auto adv = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
  103. if (adv) sendFlood(adv, 1500); // send after slight delay
  104. memcpy(&reply_data[4], "OK", 2);
  105. return 4 + 2; // reply_len
  106. }
  107. case CMD_SET_CONFIG: {
  108. if (payload_len >= 4 && payload_len < 32 && memcmp(&payload[1], "AF", 2) == 0) {
  109. payload[payload_len] = 0; // make it a C string
  110. airtime_factor = atof((char *) &payload[3]);
  111. memcpy(&reply_data[4], "OK", 2);
  112. return 4 + 2; // reply_len
  113. }
  114. return 0; // unknown config var
  115. }
  116. }
  117. // unknown command
  118. return 0; // reply_len
  119. }
  120. protected:
  121. float getAirtimeBudgetFactor() const override {
  122. return airtime_factor;
  123. }
  124. bool allowPacketForward(const mesh::Packet* packet) override {
  125. return true; // Yes, allow packet to be forwarded
  126. }
  127. void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
  128. if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
  129. uint32_t timestamp;
  130. memcpy(&timestamp, data, 4);
  131. if (memcmp(&data[4], ADMIN_PASSWORD, 8) == 0) { // check for valid password
  132. auto client = putClient(sender); // add to known clients (if not already known)
  133. if (client == NULL || timestamp <= client->last_timestamp) {
  134. return; // FATAL: client table is full -OR- replay attack
  135. }
  136. client->last_timestamp = timestamp;
  137. uint32_t now = getRTCClock()->getCurrentTime();
  138. memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
  139. memcpy(&reply_data[4], "OK", 2);
  140. if (packet->isRouteFlood()) {
  141. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  142. mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
  143. PAYLOAD_TYPE_RESPONSE, reply_data, 4 + 2);
  144. if (path) sendFlood(path);
  145. } else {
  146. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 4 + 2);
  147. if (reply) {
  148. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  149. sendDirect(reply, client->out_path, client->out_path_len);
  150. } else {
  151. sendFlood(reply);
  152. }
  153. }
  154. }
  155. }
  156. }
  157. }
  158. int matching_peer_indexes[MAX_CLIENTS];
  159. int searchPeersByHash(const uint8_t* hash) override {
  160. int n = 0;
  161. for (int i = 0; i < num_clients; i++) {
  162. if (known_clients[i].id.isHashMatch(hash)) {
  163. matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
  164. }
  165. }
  166. return n;
  167. }
  168. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  169. int i = matching_peer_indexes[peer_idx];
  170. if (i >= 0 && i < num_clients) {
  171. // lookup pre-calculated shared_secret
  172. memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
  173. } else {
  174. MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
  175. }
  176. }
  177. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
  178. if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
  179. int i = matching_peer_indexes[sender_idx];
  180. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  181. auto client = &known_clients[i];
  182. uint32_t timestamp;
  183. memcpy(&timestamp, data, 4);
  184. if (timestamp > client->last_timestamp) { // prevent replay attacks
  185. int reply_len = handleRequest(client, &data[4], len - 4);
  186. if (reply_len == 0) return; // invalid command
  187. client->last_timestamp = timestamp;
  188. if (packet->isRouteFlood()) {
  189. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
  190. mesh::Packet* path = createPathReturn(client->id, client->secret, packet->path, packet->path_len,
  191. PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
  192. if (path) sendFlood(path);
  193. } else {
  194. mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, client->secret, reply_data, reply_len);
  195. if (reply) {
  196. if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
  197. sendDirect(reply, client->out_path, client->out_path_len);
  198. } else {
  199. sendFlood(reply);
  200. }
  201. }
  202. }
  203. }
  204. } else {
  205. MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
  206. }
  207. }
  208. }
  209. 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 {
  210. // TODO: prevent replay attacks
  211. int i = matching_peer_indexes[sender_idx];
  212. if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
  213. Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
  214. auto client = &known_clients[i];
  215. memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
  216. } else {
  217. MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
  218. }
  219. // NOTE: no reciprocal path send!!
  220. }
  221. public:
  222. MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
  223. : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables)
  224. {
  225. my_radio = &radio;
  226. airtime_factor = 5.0; // 1/6th
  227. num_clients = 0;
  228. }
  229. void sendSelfAdvertisement() {
  230. mesh::Packet* pkt = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
  231. if (pkt) {
  232. sendFlood(pkt);
  233. } else {
  234. MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
  235. }
  236. }
  237. };
  238. #if defined(P_LORA_SCLK)
  239. SPIClass spi;
  240. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  241. #else
  242. CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  243. #endif
  244. StdRNG fast_rng;
  245. SimpleMeshTables tables;
  246. MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
  247. void halt() {
  248. while (1) ;
  249. }
  250. void setup() {
  251. Serial.begin(115200);
  252. delay(5000);
  253. board.begin();
  254. #if defined(P_LORA_SCLK)
  255. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  256. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  257. #else
  258. int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
  259. #endif
  260. if (status != RADIOLIB_ERR_NONE) {
  261. Serial.print("ERROR: radio init failed: ");
  262. Serial.println(status);
  263. halt();
  264. }
  265. SPIFFS.begin(true);
  266. IdentityStore store(SPIFFS, "/identity");
  267. if (!store.load("_main", the_mesh.self_id)) {
  268. the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
  269. store.save("_main", the_mesh.self_id);
  270. }
  271. Serial.print("Repeater ID: ");
  272. mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
  273. the_mesh.begin();
  274. // send out initial Advertisement to the mesh
  275. the_mesh.sendSelfAdvertisement();
  276. }
  277. void loop() {
  278. the_mesh.loop();
  279. // TODO: periodically check for OLD/inactive entries in known_clients[], and evict
  280. }