main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  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. //#define RUN_AS_ALICE true
  24. #if RUN_AS_ALICE
  25. const char* alice_private = "B8830658388B2DDF22C3A508F4386975970CDE1E2A2A495C8F3B5727957A97629255A1392F8BA4C26A023A0DAB78BFC64D261C8E51507496DD39AFE3707E7B42";
  26. #else
  27. const char *bob_private = "30BAA23CCB825D8020A59C936D0AB7773B07356020360FC77192813640BAD375E43BBF9A9A7537E4B9614610F1F2EF874AAB390BA9B0C2F01006B01FDDFEFF0C";
  28. #endif
  29. const char *alice_public = "106A5136EC0DD797650AD204C065CF9B66095F6ED772B0822187785D65E11B1F";
  30. const char *bob_public = "020BCEDAC07D709BD8507EC316EB5A7FF2F0939AF5057353DCE7E4436A1B9681";
  31. #ifdef HELTEC_LORA_V3
  32. #include <helpers/HeltecV3Board.h>
  33. static HeltecV3Board board;
  34. #else
  35. #error "need to provide a 'board' object"
  36. #endif
  37. #define SEND_TIMEOUT_BASE_MILLIS 300
  38. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  39. #define DIRECT_SEND_PERHOP_FACTOR 3.7213f
  40. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 100
  41. /* -------------------------------------------------------------------------------------- */
  42. static unsigned long txt_send_timeout;
  43. #define MAX_CONTACTS 1
  44. #define MAX_SEARCH_RESULTS 1
  45. #define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - 4 - CIPHER_MAC_SIZE - 1)
  46. struct ContactInfo {
  47. mesh::Identity id;
  48. const char* name;
  49. int out_path_len;
  50. uint8_t out_path[MAX_PATH_SIZE];
  51. uint32_t last_advert_timestamp;
  52. uint8_t shared_secret[PUB_KEY_SIZE];
  53. };
  54. class MyMesh : public mesh::Mesh {
  55. public:
  56. ContactInfo contacts[MAX_CONTACTS];
  57. int num_contacts;
  58. void addContact(const char* name, const mesh::Identity& id) {
  59. if (num_contacts < MAX_CONTACTS) {
  60. contacts[num_contacts].id = id;
  61. contacts[num_contacts].name = name;
  62. contacts[num_contacts].last_advert_timestamp = 0;
  63. contacts[num_contacts].out_path_len = -1;
  64. // only need to calculate the shared_secret once, for better performance
  65. self_id.calcSharedSecret(contacts[num_contacts].shared_secret, id);
  66. num_contacts++;
  67. }
  68. }
  69. protected:
  70. int matching_peer_indexes[MAX_SEARCH_RESULTS];
  71. int searchPeersByHash(const uint8_t* hash) override {
  72. int n = 0;
  73. for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
  74. if (contacts[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. void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
  81. Serial.print("Valid Advertisement -> ");
  82. mesh::Utils::printHex(Serial, id.pub_key, PUB_KEY_SIZE);
  83. Serial.println();
  84. for (int i = 0; i < num_contacts; i++) {
  85. ContactInfo& from = contacts[i];
  86. // check for replay attacks
  87. if (id.matches(from.id) && timestamp > from.last_advert_timestamp) { // is from one of our contacts
  88. from.last_advert_timestamp = timestamp;
  89. Serial.printf(" From contact: %s\n", from.name);
  90. }
  91. }
  92. }
  93. void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
  94. int i = matching_peer_indexes[peer_idx];
  95. if (i >= 0 && i < num_contacts) {
  96. // lookup pre-calculated shared_secret
  97. memcpy(dest_secret, contacts[i].shared_secret, PUB_KEY_SIZE);
  98. } else {
  99. MESH_DEBUG_PRINTLN("getPeerSHharedSecret: Invalid peer idx: %d", i);
  100. }
  101. }
  102. void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
  103. if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) {
  104. int i = matching_peer_indexes[sender_idx];
  105. if (i < 0 || i >= num_contacts) {
  106. MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
  107. return;
  108. }
  109. ContactInfo& from = contacts[i];
  110. uint32_t timestamp;
  111. memcpy(&timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
  112. uint flags = data[4]; // message attempt number, and other flags
  113. // len can be > original length, but 'text' will be padded with zeroes
  114. data[len] = 0; // need to make a C string again, with null terminator
  115. //if ( ! alreadyReceived timestamp ) {
  116. Serial.printf("(%s) MSG -> from %s\n", packet->isRouteFlood() ? "FLOOD" : "DIRECT", from.name);
  117. Serial.printf(" %s\n", (const char *) &data[5]);
  118. //}
  119. uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
  120. mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), from.id.pub_key, PUB_KEY_SIZE);
  121. if (packet->isRouteFlood()) {
  122. // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK
  123. mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len,
  124. PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4);
  125. if (path) sendFlood(path);
  126. } else {
  127. mesh::Packet* ack = createAck(ack_hash);
  128. if (ack) {
  129. if (from.out_path_len < 0) {
  130. sendFlood(ack);
  131. } else {
  132. sendDirect(ack, from.out_path, from.out_path_len);
  133. }
  134. }
  135. }
  136. }
  137. }
  138. 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 {
  139. int i = matching_peer_indexes[sender_idx];
  140. if (i < 0 || i >= num_contacts) {
  141. MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
  142. return;
  143. }
  144. ContactInfo& from = contacts[i];
  145. Serial.printf("PATH to: %s, path_len=%d\n", from.name, (uint32_t) path_len);
  146. // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
  147. // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
  148. memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
  149. if (packet->isRouteFlood()) {
  150. // send a reciprocal return path to sender, but send DIRECTLY!
  151. mesh::Packet* rpath = createPathReturn(from.id, secret, packet->path, packet->path_len, 0, NULL, 0);
  152. if (rpath) sendDirect(rpath, path, path_len);
  153. }
  154. if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
  155. // also got an encoded ACK!
  156. processAck(extra);
  157. }
  158. }
  159. void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override {
  160. processAck((uint8_t *)&ack_crc);
  161. }
  162. void processAck(const uint8_t *data) {
  163. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  164. Serial.printf(" Got ACK! (round trip: %d millis)\n", _ms->getMillis() - last_msg_sent);
  165. // NOTE: the same ACK can be received multiple times!
  166. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  167. txt_send_timeout = 0;
  168. } else {
  169. uint32_t crc;
  170. memcpy(&crc, data, 4);
  171. MESH_DEBUG_PRINTLN(" unknown ACK received: %08X (expected: %08X)", crc, expected_ack_crc);
  172. }
  173. }
  174. public:
  175. uint32_t expected_ack_crc;
  176. unsigned long last_msg_sent;
  177. MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  178. : mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
  179. {
  180. num_contacts = 0;
  181. }
  182. mesh::Packet* composeMsgPacket(ContactInfo& recipient, uint8_t attempt, const char *text) {
  183. int text_len = strlen(text);
  184. if (text_len > MAX_TEXT_LEN) return NULL;
  185. uint8_t temp[5+MAX_TEXT_LEN+1];
  186. uint32_t timestamp = getRTCClock()->getCurrentTime();
  187. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  188. temp[4] = attempt;
  189. memcpy(&temp[5], text, text_len + 1);
  190. // calc expected ACK reply
  191. mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE);
  192. last_msg_sent = _ms->getMillis();
  193. return createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id, recipient.shared_secret, temp, 5 + text_len);
  194. }
  195. void sendSelfAdvert() {
  196. mesh::Packet* adv = createAdvert(self_id);
  197. if (adv) {
  198. sendFlood(adv);
  199. Serial.println(" (advert sent).");
  200. } else {
  201. Serial.println(" ERROR: unable to create packet.");
  202. }
  203. }
  204. };
  205. SPIClass spi;
  206. StdRNG fast_rng;
  207. SimpleMeshTables tables;
  208. SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  209. MyMesh the_mesh(*new RadioLibWrapper(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  210. void halt() {
  211. while (1) ;
  212. }
  213. static char command[MAX_TEXT_LEN+1];
  214. void setup() {
  215. Serial.begin(115200);
  216. board.begin();
  217. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  218. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  219. #else
  220. float tcxo = 1.6f;
  221. #endif
  222. #if defined(P_LORA_SCLK)
  223. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  224. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8, tcxo);
  225. #else
  226. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8, tcxo);
  227. #endif
  228. if (status != RADIOLIB_ERR_NONE) {
  229. Serial.print("ERROR: radio init failed: ");
  230. Serial.println(status);
  231. halt();
  232. }
  233. radio.setCRC(0);
  234. #ifdef SX126X_CURRENT_LIMIT
  235. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  236. #endif
  237. #ifdef SX126X_DIO2_AS_RF_SWITCH
  238. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  239. #endif
  240. fast_rng.begin(radio.random(0x7FFFFFFF));
  241. #if RUN_AS_ALICE
  242. Serial.println(" --- user: Alice ---");
  243. the_mesh.self_id = mesh::LocalIdentity(alice_private, alice_public);
  244. the_mesh.addContact("Bob", mesh::Identity(bob_public));
  245. #else
  246. Serial.println(" --- user: Bob ---");
  247. the_mesh.self_id = mesh::LocalIdentity(bob_private, bob_public);
  248. the_mesh.addContact("Alice", mesh::Identity(alice_public));
  249. #endif
  250. Serial.println("Help:");
  251. Serial.println(" enter 'adv' to advertise presence to mesh");
  252. Serial.println(" enter 'send {message text}' to send a message");
  253. the_mesh.begin();
  254. command[0] = 0;
  255. txt_send_timeout = 0;
  256. // send out initial Advertisement to the mesh
  257. the_mesh.sendSelfAdvert();
  258. }
  259. void loop() {
  260. int len = strlen(command);
  261. while (Serial.available() && len < sizeof(command)-1) {
  262. char c = Serial.read();
  263. if (c != '\n') {
  264. command[len++] = c;
  265. command[len] = 0;
  266. }
  267. Serial.print(c);
  268. }
  269. if (len == sizeof(command)-1) { // command buffer full
  270. command[sizeof(command)-1] = '\r';
  271. }
  272. if (len > 0 && command[len - 1] == '\r') { // received complete line
  273. command[len - 1] = 0; // replace newline with C string null terminator
  274. if (memcmp(command, "send ", 5) == 0) {
  275. // TODO: some way to select recipient??
  276. ContactInfo& recipient = the_mesh.contacts[0]; // just send to first contact for now
  277. const char *text = &command[5];
  278. mesh::Packet* pkt = the_mesh.composeMsgPacket(recipient, 0, text);
  279. if (pkt) {
  280. uint32_t t = radio.getTimeOnAir(pkt->payload_len + pkt->path_len + 2) / 1000;
  281. if (recipient.out_path_len < 0) {
  282. the_mesh.sendFlood(pkt);
  283. txt_send_timeout = the_mesh.futureMillis(SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * t));
  284. Serial.printf(" (message sent - FLOOD, t=%d)\n", t);
  285. } else {
  286. the_mesh.sendDirect(pkt, recipient.out_path, recipient.out_path_len);
  287. txt_send_timeout = the_mesh.futureMillis(SEND_TIMEOUT_BASE_MILLIS +
  288. ( (t*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (recipient.out_path_len + 1)));
  289. Serial.printf(" (message sent - DIRECT, t=%d)\n", t);
  290. }
  291. } else {
  292. Serial.println(" ERROR: unable to create packet.");
  293. }
  294. } else if (strcmp(command, "adv") == 0) {
  295. the_mesh.sendSelfAdvert();
  296. } else if (strcmp(command, "key") == 0) {
  297. mesh::LocalIdentity new_id(the_mesh.getRNG());
  298. new_id.printTo(Serial);
  299. } else {
  300. Serial.print(" ERROR: unknown command: "); Serial.println(command);
  301. }
  302. command[0] = 0; // reset command buffer
  303. }
  304. if (txt_send_timeout && the_mesh.millisHasNowPassed(txt_send_timeout)) {
  305. // failed to get an ACK
  306. ContactInfo& recipient = the_mesh.contacts[0]; // just the one contact for now
  307. Serial.println(" ERROR: timed out, no ACK.");
  308. // path to our contact is now possibly broken, fallback to Flood mode
  309. recipient.out_path_len = -1;
  310. txt_send_timeout = 0;
  311. }
  312. the_mesh.loop();
  313. }