main.cpp 13 KB

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