main.cpp 14 KB

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