main.cpp 11 KB

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