main.cpp 13 KB

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