main.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. #include <Arduino.h> // needed for PlatformIO
  2. #include <Mesh.h>
  3. #if defined(NRF52_PLATFORM)
  4. #include <InternalFileSystem.h>
  5. #elif defined(ESP32)
  6. #include <SPIFFS.h>
  7. #endif
  8. #define RADIOLIB_STATIC_ONLY 1
  9. #include <RadioLib.h>
  10. #include <helpers/RadioLibWrappers.h>
  11. #include <helpers/ArduinoHelpers.h>
  12. #include <helpers/StaticPoolPacketManager.h>
  13. #include <helpers/SimpleMeshTables.h>
  14. #include <helpers/IdentityStore.h>
  15. #include <helpers/BaseSerialInterface.h>
  16. #include <RTClib.h>
  17. /* ---------------------------------- CONFIGURATION ------------------------------------- */
  18. #ifndef LORA_FREQ
  19. #define LORA_FREQ 915.0
  20. #endif
  21. #ifndef LORA_BW
  22. #define LORA_BW 250
  23. #endif
  24. #ifndef LORA_SF
  25. #define LORA_SF 10
  26. #endif
  27. #ifndef LORA_CR
  28. #define LORA_CR 5
  29. #endif
  30. #ifndef LORA_TX_POWER
  31. #define LORA_TX_POWER 20
  32. #endif
  33. #ifndef MAX_LORA_TX_POWER
  34. #define MAX_LORA_TX_POWER LORA_TX_POWER
  35. #endif
  36. #ifndef MAX_CONTACTS
  37. #define MAX_CONTACTS 100
  38. #endif
  39. #ifndef OFFLINE_QUEUE_SIZE
  40. #define OFFLINE_QUEUE_SIZE 16
  41. #endif
  42. #include <helpers/BaseChatMesh.h>
  43. #define SEND_TIMEOUT_BASE_MILLIS 500
  44. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  45. #define DIRECT_SEND_PERHOP_FACTOR 6.0f
  46. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
  47. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  48. #if defined(HELTEC_LORA_V3)
  49. #include <helpers/HeltecV3Board.h>
  50. #include <helpers/CustomSX1262Wrapper.h>
  51. static HeltecV3Board board;
  52. #elif defined(HELTEC_LORA_V2)
  53. #include <helpers/HeltecV2Board.h>
  54. #include <helpers/CustomSX1276Wrapper.h>
  55. static HeltecV2Board board;
  56. #elif defined(ARDUINO_XIAO_ESP32C3)
  57. #include <helpers/XiaoC3Board.h>
  58. #include <helpers/CustomSX1262Wrapper.h>
  59. #include <helpers/CustomSX1268Wrapper.h>
  60. static XiaoC3Board board;
  61. #elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
  62. #include <helpers/ESP32Board.h>
  63. #include <helpers/CustomSX1262Wrapper.h>
  64. static ESP32Board board;
  65. #elif defined(RAK_4631)
  66. #include <helpers/nrf52/RAK4631Board.h>
  67. #include <helpers/CustomSX1262Wrapper.h>
  68. static RAK4631Board board;
  69. #elif defined(T1000_E)
  70. #include <helpers/nrf52/T1000eBoard.h>
  71. #include <helpers/CustomLR1110Wrapper.h>
  72. static T1000eBoard board;
  73. #else
  74. #error "need to provide a 'board' object"
  75. #endif
  76. // Believe it or not, this std C function is busted on some platforms!
  77. static uint32_t _atoi(const char* sp) {
  78. uint32_t n = 0;
  79. while (*sp && *sp >= '0' && *sp <= '9') {
  80. n *= 10;
  81. n += (*sp++ - '0');
  82. }
  83. return n;
  84. }
  85. /*------------ Frame Protocol --------------*/
  86. #define FIRMWARE_VER_CODE 2
  87. #ifndef FIRMWARE_BUILD_DATE
  88. #define FIRMWARE_BUILD_DATE "3 Mar 2025"
  89. #endif
  90. #ifndef FIRMWARE_VERSION
  91. #define FIRMWARE_VERSION "v1.0.0"
  92. #endif
  93. #define CMD_APP_START 1
  94. #define CMD_SEND_TXT_MSG 2
  95. #define CMD_SEND_CHANNEL_TXT_MSG 3
  96. #define CMD_GET_CONTACTS 4 // with optional 'since' (for efficient sync)
  97. #define CMD_GET_DEVICE_TIME 5
  98. #define CMD_SET_DEVICE_TIME 6
  99. #define CMD_SEND_SELF_ADVERT 7
  100. #define CMD_SET_ADVERT_NAME 8
  101. #define CMD_ADD_UPDATE_CONTACT 9
  102. #define CMD_SYNC_NEXT_MESSAGE 10
  103. #define CMD_SET_RADIO_PARAMS 11
  104. #define CMD_SET_RADIO_TX_POWER 12
  105. #define CMD_RESET_PATH 13
  106. #define CMD_SET_ADVERT_LATLON 14
  107. #define CMD_REMOVE_CONTACT 15
  108. #define CMD_SHARE_CONTACT 16
  109. #define CMD_EXPORT_CONTACT 17
  110. #define CMD_IMPORT_CONTACT 18
  111. #define CMD_REBOOT 19
  112. #define CMD_GET_BATTERY_VOLTAGE 20
  113. #define CMD_SET_TUNING_PARAMS 21
  114. #define CMD_DEVICE_QEURY 22
  115. #define CMD_EXPORT_PRIVATE_KEY 23
  116. #define CMD_IMPORT_PRIVATE_KEY 24
  117. #define CMD_SEND_RAW_DATA 25
  118. #define CMD_SEND_LOGIN 26
  119. #define CMD_SEND_STATUS_REQ 27
  120. #define CMD_HAS_CONNECTION 28
  121. #define CMD_LOGOUT 29 // 'Disconnect'
  122. #define RESP_CODE_OK 0
  123. #define RESP_CODE_ERR 1
  124. #define RESP_CODE_CONTACTS_START 2 // first reply to CMD_GET_CONTACTS
  125. #define RESP_CODE_CONTACT 3 // multiple of these (after CMD_GET_CONTACTS)
  126. #define RESP_CODE_END_OF_CONTACTS 4 // last reply to CMD_GET_CONTACTS
  127. #define RESP_CODE_SELF_INFO 5 // reply to CMD_APP_START
  128. #define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG
  129. #define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE
  130. #define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE
  131. #define RESP_CODE_CURR_TIME 9 // a reply to CMD_GET_DEVICE_TIME
  132. #define RESP_CODE_NO_MORE_MESSAGES 10 // a reply to CMD_SYNC_NEXT_MESSAGE
  133. #define RESP_CODE_EXPORT_CONTACT 11
  134. #define RESP_CODE_BATTERY_VOLTAGE 12 // a reply to a CMD_GET_BATTERY_VOLTAGE
  135. #define RESP_CODE_DEVICE_INFO 13 // a reply to CMD_DEVICE_QEURY
  136. #define RESP_CODE_PRIVATE_KEY 14 // a reply to CMD_EXPORT_PRIVATE_KEY
  137. #define RESP_CODE_DISABLED 15
  138. // these are _pushed_ to client app at any time
  139. #define PUSH_CODE_ADVERT 0x80
  140. #define PUSH_CODE_PATH_UPDATED 0x81
  141. #define PUSH_CODE_SEND_CONFIRMED 0x82
  142. #define PUSH_CODE_MSG_WAITING 0x83
  143. #define PUSH_CODE_RAW_DATA 0x84
  144. #define PUSH_CODE_LOGIN_SUCCESS 0x85
  145. #define PUSH_CODE_LOGIN_FAIL 0x86
  146. #define PUSH_CODE_STATUS_RESPONSE 0x87
  147. /* -------------------------------------------------------------------------------------- */
  148. struct NodePrefs { // persisted to file
  149. float airtime_factor;
  150. char node_name[32];
  151. double node_lat, node_lon;
  152. float freq;
  153. uint8_t sf;
  154. uint8_t cr;
  155. uint8_t reserved1;
  156. uint8_t reserved2;
  157. float bw;
  158. uint8_t tx_power_dbm;
  159. uint8_t unused[3];
  160. float rx_delay_base;
  161. };
  162. class MyMesh : public BaseChatMesh {
  163. FILESYSTEM* _fs;
  164. RADIO_CLASS* _phy;
  165. IdentityStore* _identity_store;
  166. NodePrefs _prefs;
  167. uint32_t expected_ack_crc; // TODO: keep table of expected ACKs
  168. uint32_t pending_login;
  169. uint32_t pending_status;
  170. mesh::GroupChannel* _public;
  171. BaseSerialInterface* _serial;
  172. unsigned long last_msg_sent;
  173. ContactsIterator _iter;
  174. uint32_t _iter_filter_since;
  175. uint32_t _most_recent_lastmod;
  176. bool _iter_started;
  177. uint8_t app_target_ver;
  178. uint8_t cmd_frame[MAX_FRAME_SIZE+1];
  179. uint8_t out_frame[MAX_FRAME_SIZE+1];
  180. struct Frame {
  181. uint8_t len;
  182. uint8_t buf[MAX_FRAME_SIZE];
  183. };
  184. int offline_queue_len;
  185. Frame offline_queue[OFFLINE_QUEUE_SIZE];
  186. void loadMainIdentity(mesh::RNG& trng) {
  187. if (!_identity_store->load("_main", self_id)) {
  188. self_id = mesh::LocalIdentity(&trng); // create new random identity
  189. saveMainIdentity(self_id);
  190. }
  191. }
  192. bool saveMainIdentity(const mesh::LocalIdentity& identity) {
  193. return _identity_store->save("_main", identity);
  194. }
  195. void loadContacts() {
  196. if (_fs->exists("/contacts3")) {
  197. File file = _fs->open("/contacts3");
  198. if (file) {
  199. bool full = false;
  200. while (!full) {
  201. ContactInfo c;
  202. uint8_t pub_key[32];
  203. uint8_t unused;
  204. bool success = (file.read(pub_key, 32) == 32);
  205. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  206. success = success && (file.read(&c.type, 1) == 1);
  207. success = success && (file.read(&c.flags, 1) == 1);
  208. success = success && (file.read(&unused, 1) == 1);
  209. success = success && (file.read((uint8_t *) &c.sync_since, 4) == 4); // was 'reserved'
  210. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  211. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  212. success = success && (file.read(c.out_path, 64) == 64);
  213. success = success && (file.read((uint8_t *) &c.lastmod, 4) == 4);
  214. success = success && (file.read((uint8_t *) &c.gps_lat, 4) == 4);
  215. success = success && (file.read((uint8_t *) &c.gps_lon, 4) == 4);
  216. if (!success) break; // EOF
  217. c.id = mesh::Identity(pub_key);
  218. if (!addContact(c)) full = true;
  219. }
  220. file.close();
  221. }
  222. }
  223. }
  224. void saveContacts() {
  225. #if defined(NRF52_PLATFORM)
  226. File file = _fs->open("/contacts3", FILE_O_WRITE);
  227. if (file) { file.seek(0); file.truncate(); }
  228. #else
  229. File file = _fs->open("/contacts3", "w", true);
  230. #endif
  231. if (file) {
  232. ContactsIterator iter;
  233. ContactInfo c;
  234. uint8_t unused = 0;
  235. while (iter.hasNext(this, c)) {
  236. bool success = (file.write(c.id.pub_key, 32) == 32);
  237. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  238. success = success && (file.write(&c.type, 1) == 1);
  239. success = success && (file.write(&c.flags, 1) == 1);
  240. success = success && (file.write(&unused, 1) == 1);
  241. success = success && (file.write((uint8_t *) &c.sync_since, 4) == 4);
  242. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  243. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  244. success = success && (file.write(c.out_path, 64) == 64);
  245. success = success && (file.write((uint8_t *) &c.lastmod, 4) == 4);
  246. success = success && (file.write((uint8_t *) &c.gps_lat, 4) == 4);
  247. success = success && (file.write((uint8_t *) &c.gps_lon, 4) == 4);
  248. if (!success) break; // write failed
  249. }
  250. file.close();
  251. }
  252. }
  253. int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) override {
  254. char path[64];
  255. char fname[18];
  256. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  257. mesh::Utils::toHex(fname, key, key_len);
  258. sprintf(path, "/bl/%s", fname);
  259. if (_fs->exists(path)) {
  260. File f = _fs->open(path);
  261. if (f) {
  262. int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
  263. f.close();
  264. return len;
  265. }
  266. }
  267. return 0; // not found
  268. }
  269. bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) override {
  270. char path[64];
  271. char fname[18];
  272. if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
  273. mesh::Utils::toHex(fname, key, key_len);
  274. sprintf(path, "/bl/%s", fname);
  275. #if defined(NRF52_PLATFORM)
  276. File f = _fs->open(path, FILE_O_WRITE);
  277. if (f) { f.seek(0); f.truncate(); }
  278. #else
  279. File f = _fs->open(path, "w", true);
  280. #endif
  281. if (f) {
  282. int n = f.write(src_buf, len);
  283. f.close();
  284. if (n == len) return true; // success!
  285. _fs->remove(path); // blob was only partially written!
  286. }
  287. return false; // error
  288. }
  289. void writeOKFrame() {
  290. uint8_t buf[1];
  291. buf[0] = RESP_CODE_OK;
  292. _serial->writeFrame(buf, 1);
  293. }
  294. void writeErrFrame() {
  295. uint8_t buf[1];
  296. buf[0] = RESP_CODE_ERR;
  297. _serial->writeFrame(buf, 1);
  298. }
  299. void writeDisabledFrame() {
  300. uint8_t buf[1];
  301. buf[0] = RESP_CODE_DISABLED;
  302. _serial->writeFrame(buf, 1);
  303. }
  304. void writeContactRespFrame(uint8_t code, const ContactInfo& contact) {
  305. int i = 0;
  306. out_frame[i++] = code;
  307. memcpy(&out_frame[i], contact.id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  308. out_frame[i++] = contact.type;
  309. out_frame[i++] = contact.flags;
  310. out_frame[i++] = contact.out_path_len;
  311. memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  312. StrHelper::strzcpy((char *) &out_frame[i], contact.name, 32); i += 32;
  313. memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); i += 4;
  314. memcpy(&out_frame[i], &contact.gps_lat, 4); i += 4;
  315. memcpy(&out_frame[i], &contact.gps_lon, 4); i += 4;
  316. memcpy(&out_frame[i], &contact.lastmod, 4); i += 4;
  317. _serial->writeFrame(out_frame, i);
  318. }
  319. void updateContactFromFrame(ContactInfo& contact, const uint8_t* frame, int len) {
  320. int i = 0;
  321. uint8_t code = frame[i++]; // eg. CMD_ADD_UPDATE_CONTACT
  322. memcpy(contact.id.pub_key, &frame[i], PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  323. contact.type = frame[i++];
  324. contact.flags = frame[i++];
  325. contact.out_path_len = frame[i++];
  326. memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  327. memcpy(contact.name, &frame[i], 32); i += 32;
  328. memcpy(&contact.last_advert_timestamp, &frame[i], 4); i += 4;
  329. if (i + 8 >= len) { // optional fields
  330. memcpy(&contact.gps_lat, &frame[i], 4); i += 4;
  331. memcpy(&contact.gps_lon, &frame[i], 4); i += 4;
  332. }
  333. }
  334. void addToOfflineQueue(const uint8_t frame[], int len) {
  335. if (offline_queue_len >= OFFLINE_QUEUE_SIZE) {
  336. MESH_DEBUG_PRINTLN("ERROR: offline_queue is full!");
  337. } else {
  338. offline_queue[offline_queue_len].len = len;
  339. memcpy(offline_queue[offline_queue_len].buf, frame, len);
  340. offline_queue_len++;
  341. }
  342. }
  343. int getFromOfflineQueue(uint8_t frame[]) {
  344. if (offline_queue_len > 0) { // check offline queue
  345. size_t len = offline_queue[0].len; // take from top of queue
  346. memcpy(frame, offline_queue[0].buf, len);
  347. offline_queue_len--;
  348. for (int i = 0; i < offline_queue_len; i++) { // delete top item from queue
  349. offline_queue[i] = offline_queue[i + 1];
  350. }
  351. return len;
  352. }
  353. return 0; // queue is empty
  354. }
  355. void soundBuzzer() {
  356. // TODO
  357. }
  358. protected:
  359. float getAirtimeBudgetFactor() const override {
  360. return _prefs.airtime_factor;
  361. }
  362. int calcRxDelay(float score, uint32_t air_time) const override {
  363. if (_prefs.rx_delay_base <= 0.0f) return 0;
  364. return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
  365. }
  366. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  367. if (_serial->isConnected()) {
  368. out_frame[0] = PUSH_CODE_ADVERT;
  369. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  370. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE);
  371. } else {
  372. soundBuzzer();
  373. }
  374. saveContacts();
  375. }
  376. void onContactPathUpdated(const ContactInfo& contact) override {
  377. out_frame[0] = PUSH_CODE_PATH_UPDATED;
  378. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  379. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); // NOTE: app may not be connected
  380. saveContacts();
  381. }
  382. bool processAck(const uint8_t *data) override {
  383. // TODO: see if matches any in a table
  384. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  385. out_frame[0] = PUSH_CODE_SEND_CONFIRMED;
  386. memcpy(&out_frame[1], data, 4);
  387. uint32_t trip_time = _ms->getMillis() - last_msg_sent;
  388. memcpy(&out_frame[5], &trip_time, 4);
  389. _serial->writeFrame(out_frame, 9);
  390. // NOTE: the same ACK can be received multiple times!
  391. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  392. return true;
  393. }
  394. return checkConnectionsAck(data);
  395. }
  396. void queueMessage(const ContactInfo& from, uint8_t txt_type, uint8_t path_len, uint32_t sender_timestamp, const uint8_t* extra, int extra_len, const char *text) {
  397. int i = 0;
  398. out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV;
  399. memcpy(&out_frame[i], from.id.pub_key, 6); i += 6; // just 6-byte prefix
  400. out_frame[i++] = path_len;
  401. out_frame[i++] = txt_type;
  402. memcpy(&out_frame[i], &sender_timestamp, 4); i += 4;
  403. if (extra_len > 0) {
  404. memcpy(&out_frame[i], extra, extra_len); i += extra_len;
  405. }
  406. int tlen = strlen(text); // TODO: UTF-8 ??
  407. if (i + tlen > MAX_FRAME_SIZE) {
  408. tlen = MAX_FRAME_SIZE - i;
  409. }
  410. memcpy(&out_frame[i], text, tlen); i += tlen;
  411. addToOfflineQueue(out_frame, i);
  412. if (_serial->isConnected()) {
  413. uint8_t frame[1];
  414. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  415. _serial->writeFrame(frame, 1);
  416. } else {
  417. soundBuzzer();
  418. }
  419. }
  420. void onMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  421. markConnectionActive(from); // in case this is from a server, and we have a connection
  422. queueMessage(from, TXT_TYPE_PLAIN, path_len, sender_timestamp, NULL, 0, text);
  423. }
  424. void onCommandDataRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  425. markConnectionActive(from); // in case this is from a server, and we have a connection
  426. queueMessage(from, TXT_TYPE_CLI_DATA, path_len, sender_timestamp, NULL, 0, text);
  427. }
  428. void onSignedMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override {
  429. markConnectionActive(from);
  430. saveContacts(); // from.sync_since change needs to be persisted
  431. queueMessage(from, TXT_TYPE_SIGNED_PLAIN, path_len, sender_timestamp, sender_prefix, 4, text);
  432. }
  433. void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
  434. int i = 0;
  435. out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV;
  436. out_frame[i++] = 0; // FUTURE: channel_idx (will just be 'public' for now)
  437. out_frame[i++] = in_path_len < 0 ? 0xFF : in_path_len;
  438. out_frame[i++] = TXT_TYPE_PLAIN;
  439. memcpy(&out_frame[i], &timestamp, 4); i += 4;
  440. int tlen = strlen(text); // TODO: UTF-8 ??
  441. if (i + tlen > MAX_FRAME_SIZE) {
  442. tlen = MAX_FRAME_SIZE - i;
  443. }
  444. memcpy(&out_frame[i], text, tlen); i += tlen;
  445. addToOfflineQueue(out_frame, i);
  446. if (_serial->isConnected()) {
  447. uint8_t frame[1];
  448. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  449. _serial->writeFrame(frame, 1);
  450. } else {
  451. soundBuzzer();
  452. }
  453. }
  454. void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
  455. uint32_t sender_timestamp;
  456. memcpy(&sender_timestamp, data, 4);
  457. if (pending_login && memcmp(&pending_login, contact.id.pub_key, 4) == 0) { // check for login response
  458. // yes, is response to pending sendLogin()
  459. pending_login = 0;
  460. int i = 0;
  461. if (memcmp(&data[4], "OK", 2) == 0) { // legacy Repeater login OK response
  462. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  463. out_frame[i++] = 0; // legacy: is_admin = false
  464. } else if (data[4] == RESP_SERVER_LOGIN_OK) { // new login response
  465. uint16_t keep_alive_secs = ((uint16_t)data[5]) * 16;
  466. if (keep_alive_secs > 0) {
  467. startConnection(contact, keep_alive_secs);
  468. }
  469. out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
  470. out_frame[i++] = data[6]; // permissions (eg. is_admin)
  471. } else {
  472. out_frame[i++] = PUSH_CODE_LOGIN_FAIL;
  473. out_frame[i++] = 0; // reserved
  474. }
  475. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  476. _serial->writeFrame(out_frame, i);
  477. } else if (len > 4 && pending_status && memcmp(&pending_status, contact.id.pub_key, 4) == 0) { // check for status response
  478. // yes, is response to pending sendStatusRequest()
  479. pending_status = 0;
  480. int i = 0;
  481. out_frame[i++] = PUSH_CODE_STATUS_RESPONSE;
  482. out_frame[i++] = 0; // reserved
  483. memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
  484. memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4);
  485. _serial->writeFrame(out_frame, i);
  486. }
  487. }
  488. void onRawDataRecv(mesh::Packet* packet) override {
  489. int i = 0;
  490. out_frame[i++] = PUSH_CODE_RAW_DATA;
  491. out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4);
  492. out_frame[i++] = (int8_t)(_radio->getLastRSSI());
  493. out_frame[i++] = 0xFF; // reserved (possibly path_len in future)
  494. memcpy(&out_frame[i], packet->payload, packet->payload_len); i += packet->payload_len;
  495. if (_serial->isConnected()) {
  496. _serial->writeFrame(out_frame, i);
  497. } else {
  498. MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline");
  499. }
  500. }
  501. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  502. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  503. }
  504. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  505. return SEND_TIMEOUT_BASE_MILLIS +
  506. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  507. }
  508. void onSendTimeout() override {
  509. }
  510. public:
  511. MyMesh(RADIO_CLASS& phy, RadioLibWrapper& rw, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  512. : BaseChatMesh(rw, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL), _phy(&phy)
  513. {
  514. _iter_started = false;
  515. offline_queue_len = 0;
  516. app_target_ver = 0;
  517. _identity_store = NULL;
  518. pending_login = pending_status = 0;
  519. // defaults
  520. memset(&_prefs, 0, sizeof(_prefs));
  521. _prefs.airtime_factor = 1.0; // one half
  522. strcpy(_prefs.node_name, "NONAME");
  523. _prefs.freq = LORA_FREQ;
  524. _prefs.sf = LORA_SF;
  525. _prefs.bw = LORA_BW;
  526. _prefs.cr = LORA_CR;
  527. _prefs.tx_power_dbm = LORA_TX_POWER;
  528. //_prefs.rx_delay_base = 10.0f; enable once new algo fixed
  529. }
  530. void begin(FILESYSTEM& fs, mesh::RNG& trng) {
  531. _fs = &fs;
  532. BaseChatMesh::begin();
  533. #if defined(NRF52_PLATFORM)
  534. _identity_store = new IdentityStore(fs, "");
  535. #else
  536. _identity_store = new IdentityStore(fs, "/identity");
  537. #endif
  538. loadMainIdentity(trng);
  539. // load persisted prefs
  540. if (_fs->exists("/node_prefs")) {
  541. File file = _fs->open("/node_prefs");
  542. if (file) {
  543. file.read((uint8_t *) &_prefs, sizeof(_prefs));
  544. file.close();
  545. }
  546. }
  547. // init 'blob store' support
  548. _fs->mkdir("/bl");
  549. loadContacts();
  550. _public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  551. _phy->setFrequency(_prefs.freq);
  552. _phy->setSpreadingFactor(_prefs.sf);
  553. _phy->setBandwidth(_prefs.bw);
  554. _phy->setCodingRate(_prefs.cr);
  555. _phy->setOutputPower(_prefs.tx_power_dbm);
  556. }
  557. const char* getNodeName() { return _prefs.node_name; }
  558. void startInterface(BaseSerialInterface& serial) {
  559. _serial = &serial;
  560. serial.enable();
  561. }
  562. void savePrefs() {
  563. #if defined(NRF52_PLATFORM)
  564. File file = _fs->open("/node_prefs", FILE_O_WRITE);
  565. if (file) { file.seek(0); file.truncate(); }
  566. #else
  567. File file = _fs->open("/node_prefs", "w", true);
  568. #endif
  569. if (file) {
  570. file.write((const uint8_t *)&_prefs, sizeof(_prefs));
  571. file.close();
  572. }
  573. }
  574. void handleCmdFrame(size_t len) {
  575. if (cmd_frame[0] == CMD_DEVICE_QEURY && len >= 2) { // sent when app establishes connection
  576. app_target_ver = cmd_frame[1]; // which version of protocol does app understand
  577. int i = 0;
  578. out_frame[i++] = RESP_CODE_DEVICE_INFO;
  579. out_frame[i++] = FIRMWARE_VER_CODE;
  580. memset(&out_frame[i], 0, 6); i += 6; // reserved
  581. memset(&out_frame[i], 0, 12);
  582. strcpy((char *) &out_frame[i], FIRMWARE_BUILD_DATE); i += 12;
  583. StrHelper::strzcpy((char *) &out_frame[i], board.getManufacturerName(), 40); i += 40;
  584. StrHelper::strzcpy((char *) &out_frame[i], FIRMWARE_VERSION, 20); i += 20;
  585. _serial->writeFrame(out_frame, i);
  586. } else if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
  587. // cmd_frame[1..7] reserved future
  588. char* app_name = (char *) &cmd_frame[8];
  589. cmd_frame[len] = 0; // make app_name null terminated
  590. MESH_DEBUG_PRINTLN("App %s connected", app_name);
  591. _iter_started = false; // stop any left-over ContactsIterator
  592. int i = 0;
  593. out_frame[i++] = RESP_CODE_SELF_INFO;
  594. out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-)
  595. out_frame[i++] = _prefs.tx_power_dbm;
  596. out_frame[i++] = MAX_LORA_TX_POWER;
  597. memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  598. int32_t lat, lon, alt = 0;
  599. lat = (_prefs.node_lat * 1000000.0);
  600. lon = (_prefs.node_lon * 1000000.0);
  601. memcpy(&out_frame[i], &lat, 4); i += 4;
  602. memcpy(&out_frame[i], &lon, 4); i += 4;
  603. memcpy(&out_frame[i], &alt, 4); i += 4;
  604. uint32_t freq = _prefs.freq * 1000;
  605. memcpy(&out_frame[i], &freq, 4); i += 4;
  606. uint32_t bw = _prefs.bw*1000;
  607. memcpy(&out_frame[i], &bw, 4); i += 4;
  608. out_frame[i++] = _prefs.sf;
  609. out_frame[i++] = _prefs.cr;
  610. int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ??
  611. memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen;
  612. _serial->writeFrame(out_frame, i);
  613. } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) {
  614. int i = 1;
  615. uint8_t txt_type = cmd_frame[i++];
  616. uint8_t attempt = cmd_frame[i++];
  617. uint32_t msg_timestamp;
  618. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  619. uint8_t* pub_key_prefix = &cmd_frame[i]; i += 6;
  620. ContactInfo* recipient = lookupContactByPubKey(pub_key_prefix, 6);
  621. if (recipient && attempt < 4 && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA)) {
  622. char *text = (char *) &cmd_frame[i];
  623. int tlen = len - i;
  624. uint32_t est_timeout;
  625. text[tlen] = 0; // ensure null
  626. int result;
  627. if (txt_type == TXT_TYPE_CLI_DATA) {
  628. result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout);
  629. expected_ack_crc = 0; // no Ack expected
  630. } else {
  631. result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack_crc, est_timeout);
  632. }
  633. // TODO: add expected ACK to table
  634. if (result == MSG_SEND_FAILED) {
  635. writeErrFrame();
  636. } else {
  637. last_msg_sent = _ms->getMillis();
  638. out_frame[0] = RESP_CODE_SENT;
  639. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  640. memcpy(&out_frame[2], &expected_ack_crc, 4);
  641. memcpy(&out_frame[6], &est_timeout, 4);
  642. _serial->writeFrame(out_frame, 10);
  643. }
  644. } else {
  645. writeErrFrame(); // unknown recipient, or unsuported TXT_TYPE_*
  646. }
  647. } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg
  648. int i = 1;
  649. uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN
  650. uint8_t channel_idx = cmd_frame[i++]; // reserved future
  651. uint32_t msg_timestamp;
  652. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  653. const char *text = (char *) &cmd_frame[i];
  654. if (txt_type == TXT_TYPE_PLAIN && sendGroupMessage(msg_timestamp, *_public, _prefs.node_name, text, len - i)) { // hard-coded to 'public' channel for now
  655. writeOKFrame();
  656. } else {
  657. writeErrFrame();
  658. }
  659. } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list
  660. if (_iter_started) {
  661. writeErrFrame(); // iterator is currently busy
  662. } else {
  663. if (len >= 5) { // has optional 'since' param
  664. memcpy(&_iter_filter_since, &cmd_frame[1], 4);
  665. } else {
  666. _iter_filter_since = 0;
  667. }
  668. uint8_t reply[5];
  669. reply[0] = RESP_CODE_CONTACTS_START;
  670. uint32_t count = getNumContacts(); // total, NOT filtered count
  671. memcpy(&reply[1], &count, 4);
  672. _serial->writeFrame(reply, 5);
  673. // start iterator
  674. _iter = startContactsIterator();
  675. _iter_started = true;
  676. _most_recent_lastmod = 0;
  677. }
  678. } else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) {
  679. int nlen = len - 1;
  680. if (nlen > sizeof(_prefs.node_name)-1) nlen = sizeof(_prefs.node_name)-1; // max len
  681. memcpy(_prefs.node_name, &cmd_frame[1], nlen);
  682. _prefs.node_name[nlen] = 0; // null terminator
  683. savePrefs();
  684. writeOKFrame();
  685. } else if (cmd_frame[0] == CMD_SET_ADVERT_LATLON && len >= 9) {
  686. int32_t lat, lon, alt = 0;
  687. memcpy(&lat, &cmd_frame[1], 4);
  688. memcpy(&lon, &cmd_frame[5], 4);
  689. if (len >= 13) {
  690. memcpy(&alt, &cmd_frame[9], 4); // for FUTURE support
  691. }
  692. if (lat <= 90*1E6 && lat >= -90*1E6 && lon <= 180*1E6 && lon >= -180*1E6) {
  693. _prefs.node_lat = ((double)lat) / 1000000.0;
  694. _prefs.node_lon = ((double)lon) / 1000000.0;
  695. savePrefs();
  696. writeOKFrame();
  697. } else {
  698. writeErrFrame(); // invalid geo coordinate
  699. }
  700. } else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) {
  701. uint8_t reply[5];
  702. reply[0] = RESP_CODE_CURR_TIME;
  703. uint32_t now = getRTCClock()->getCurrentTime();
  704. memcpy(&reply[1], &now, 4);
  705. _serial->writeFrame(reply, 5);
  706. } else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
  707. uint32_t secs;
  708. memcpy(&secs, &cmd_frame[1], 4);
  709. uint32_t curr = getRTCClock()->getCurrentTime();
  710. if (secs >= curr) {
  711. getRTCClock()->setCurrentTime(secs);
  712. writeOKFrame();
  713. } else {
  714. writeErrFrame();
  715. }
  716. } else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
  717. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  718. if (pkt) {
  719. if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop)
  720. sendFlood(pkt);
  721. } else {
  722. sendZeroHop(pkt);
  723. }
  724. writeOKFrame();
  725. } else {
  726. writeErrFrame();
  727. }
  728. } else if (cmd_frame[0] == CMD_RESET_PATH && len >= 1+32) {
  729. uint8_t* pub_key = &cmd_frame[1];
  730. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  731. if (recipient) {
  732. recipient->out_path_len = -1;
  733. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  734. saveContacts();
  735. writeOKFrame();
  736. } else {
  737. writeErrFrame(); // unknown contact
  738. }
  739. } else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1+32+2+1) {
  740. uint8_t* pub_key = &cmd_frame[1];
  741. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  742. if (recipient) {
  743. updateContactFromFrame(*recipient, cmd_frame, len);
  744. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  745. saveContacts();
  746. writeOKFrame();
  747. } else {
  748. ContactInfo contact;
  749. updateContactFromFrame(contact, cmd_frame, len);
  750. contact.lastmod = getRTCClock()->getCurrentTime();
  751. contact.sync_since = 0;
  752. if (addContact(contact)) {
  753. saveContacts();
  754. writeOKFrame();
  755. } else {
  756. writeErrFrame(); // table is full!
  757. }
  758. }
  759. } else if (cmd_frame[0] == CMD_REMOVE_CONTACT) {
  760. uint8_t* pub_key = &cmd_frame[1];
  761. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  762. if (recipient && removeContact(*recipient)) {
  763. saveContacts();
  764. writeOKFrame();
  765. } else {
  766. writeErrFrame(); // not found, or unable to remove
  767. }
  768. } else if (cmd_frame[0] == CMD_SHARE_CONTACT) {
  769. uint8_t* pub_key = &cmd_frame[1];
  770. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  771. if (recipient && shareContactZeroHop(*recipient)) {
  772. writeOKFrame();
  773. } else {
  774. writeErrFrame(); // not found, or unable to send
  775. }
  776. } else if (cmd_frame[0] == CMD_EXPORT_CONTACT) {
  777. if (len < 1 + PUB_KEY_SIZE) {
  778. // export SELF
  779. auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
  780. if (pkt) {
  781. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  782. uint8_t out_len = pkt->writeTo(&out_frame[1]);
  783. releasePacket(pkt); // undo the obtainNewPacket()
  784. _serial->writeFrame(out_frame, out_len + 1);
  785. } else {
  786. writeErrFrame(); // Error
  787. }
  788. } else {
  789. uint8_t* pub_key = &cmd_frame[1];
  790. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  791. uint8_t out_len;
  792. if (recipient && (out_len = exportContact(*recipient, &out_frame[1])) > 0) {
  793. out_frame[0] = RESP_CODE_EXPORT_CONTACT;
  794. _serial->writeFrame(out_frame, out_len + 1);
  795. } else {
  796. writeErrFrame(); // not found
  797. }
  798. }
  799. } else if (cmd_frame[0] == CMD_IMPORT_CONTACT && len > 2+32+64) {
  800. if (importContact(&cmd_frame[1], len - 1)) {
  801. writeOKFrame();
  802. } else {
  803. writeErrFrame();
  804. }
  805. } else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) {
  806. int out_len;
  807. if ((out_len = getFromOfflineQueue(out_frame)) > 0) {
  808. _serial->writeFrame(out_frame, out_len);
  809. } else {
  810. out_frame[0] = RESP_CODE_NO_MORE_MESSAGES;
  811. _serial->writeFrame(out_frame, 1);
  812. }
  813. } else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) {
  814. int i = 1;
  815. uint32_t freq;
  816. memcpy(&freq, &cmd_frame[i], 4); i += 4;
  817. uint32_t bw;
  818. memcpy(&bw, &cmd_frame[i], 4); i += 4;
  819. uint8_t sf = cmd_frame[i++];
  820. uint8_t cr = cmd_frame[i++];
  821. if (freq >= 300000 && freq <= 2500000 && sf >= 7 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && bw <= 500000) {
  822. _prefs.sf = sf;
  823. _prefs.cr = cr;
  824. _prefs.freq = (float)freq / 1000.0;
  825. _prefs.bw = (float)bw / 1000.0;
  826. savePrefs();
  827. _phy->setFrequency(_prefs.freq);
  828. _phy->setSpreadingFactor(_prefs.sf);
  829. _phy->setBandwidth(_prefs.bw);
  830. _phy->setCodingRate(_prefs.cr);
  831. MESH_DEBUG_PRINTLN("OK: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  832. writeOKFrame();
  833. } else {
  834. MESH_DEBUG_PRINTLN("Error: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
  835. writeErrFrame();
  836. }
  837. } else if (cmd_frame[0] == CMD_SET_RADIO_TX_POWER) {
  838. if (cmd_frame[1] > MAX_LORA_TX_POWER) {
  839. writeErrFrame();
  840. } else {
  841. _prefs.tx_power_dbm = cmd_frame[1];
  842. savePrefs();
  843. _phy->setOutputPower(_prefs.tx_power_dbm);
  844. writeOKFrame();
  845. }
  846. } else if (cmd_frame[0] == CMD_SET_TUNING_PARAMS) {
  847. int i = 1;
  848. uint32_t rx, af;
  849. memcpy(&rx, &cmd_frame[i], 4); i += 4;
  850. memcpy(&af, &cmd_frame[i], 4); i += 4;
  851. _prefs.rx_delay_base = ((float)rx) / 1000.0f;
  852. _prefs.airtime_factor = ((float)af) / 1000.0f;
  853. savePrefs();
  854. writeOKFrame();
  855. } else if (cmd_frame[0] == CMD_REBOOT && memcmp(&cmd_frame[1], "reboot", 6) == 0) {
  856. board.reboot();
  857. } else if (cmd_frame[0] == CMD_GET_BATTERY_VOLTAGE) {
  858. uint8_t reply[3];
  859. reply[0] = RESP_CODE_BATTERY_VOLTAGE;
  860. uint16_t battery_millivolts = board.getBattMilliVolts();
  861. memcpy(&reply[1], &battery_millivolts, 2);
  862. _serial->writeFrame(reply, 3);
  863. } else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) {
  864. #if ENABLE_PRIVATE_KEY_EXPORT
  865. uint8_t reply[65];
  866. reply[0] = RESP_CODE_PRIVATE_KEY;
  867. self_id.writeTo(&reply[1], 64);
  868. _serial->writeFrame(reply, 65);
  869. #else
  870. writeDisabledFrame();
  871. #endif
  872. } else if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65) {
  873. #if ENABLE_PRIVATE_KEY_IMPORT
  874. mesh::LocalIdentity identity;
  875. identity.readFrom(&cmd_frame[1], 64);
  876. if (saveMainIdentity(identity)) {
  877. self_id = identity;
  878. writeOKFrame();
  879. } else {
  880. writeErrFrame();
  881. }
  882. #else
  883. writeDisabledFrame();
  884. #endif
  885. } else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) {
  886. int i = 1;
  887. int8_t path_len = cmd_frame[i++];
  888. if (path_len >= 0 && i + path_len + 4 <= len) { // minimum 4 byte payload
  889. uint8_t* path = &cmd_frame[i]; i += path_len;
  890. auto pkt = createRawData(&cmd_frame[i], len - i);
  891. if (pkt) {
  892. sendDirect(pkt, path, path_len);
  893. writeOKFrame();
  894. } else {
  895. writeErrFrame();
  896. }
  897. } else {
  898. writeErrFrame(); // flood, not supported (yet)
  899. }
  900. } else if (cmd_frame[0] == CMD_SEND_LOGIN && len >= 1+PUB_KEY_SIZE) {
  901. uint8_t* pub_key = &cmd_frame[1];
  902. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  903. char *password = (char *) &cmd_frame[1+PUB_KEY_SIZE];
  904. cmd_frame[len] = 0; // ensure null terminator in password
  905. if (recipient) {
  906. uint32_t est_timeout;
  907. int result = sendLogin(*recipient, password, est_timeout);
  908. if (result == MSG_SEND_FAILED) {
  909. writeErrFrame();
  910. } else {
  911. pending_status = 0;
  912. memcpy(&pending_login, recipient->id.pub_key, 4); // match this to onContactResponse()
  913. out_frame[0] = RESP_CODE_SENT;
  914. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  915. memcpy(&out_frame[2], &pending_login, 4);
  916. memcpy(&out_frame[6], &est_timeout, 4);
  917. _serial->writeFrame(out_frame, 10);
  918. }
  919. } else {
  920. writeErrFrame(); // contact not found
  921. }
  922. } else if (cmd_frame[0] == CMD_SEND_STATUS_REQ && len >= 1+PUB_KEY_SIZE) {
  923. uint8_t* pub_key = &cmd_frame[1];
  924. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  925. if (recipient) {
  926. uint32_t est_timeout;
  927. int result = sendStatusRequest(*recipient, est_timeout);
  928. if (result == MSG_SEND_FAILED) {
  929. writeErrFrame();
  930. } else {
  931. pending_login = 0;
  932. memcpy(&pending_status, recipient->id.pub_key, 4); // match this to onContactResponse()
  933. out_frame[0] = RESP_CODE_SENT;
  934. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  935. memcpy(&out_frame[2], &pending_status, 4);
  936. memcpy(&out_frame[6], &est_timeout, 4);
  937. _serial->writeFrame(out_frame, 10);
  938. }
  939. } else {
  940. writeErrFrame(); // contact not found
  941. }
  942. } else if (cmd_frame[0] == CMD_HAS_CONNECTION && len >= 1+PUB_KEY_SIZE) {
  943. uint8_t* pub_key = &cmd_frame[1];
  944. if (hasConnectionTo(pub_key)) {
  945. writeOKFrame();
  946. } else {
  947. writeErrFrame();
  948. }
  949. } else if (cmd_frame[0] == CMD_LOGOUT && len >= 1+PUB_KEY_SIZE) {
  950. uint8_t* pub_key = &cmd_frame[1];
  951. stopConnection(pub_key);
  952. writeOKFrame();
  953. } else {
  954. writeErrFrame();
  955. MESH_DEBUG_PRINTLN("ERROR: unknown command: %02X", cmd_frame[0]);
  956. }
  957. }
  958. void loop() {
  959. BaseChatMesh::loop();
  960. size_t len = _serial->checkRecvFrame(cmd_frame);
  961. if (len > 0) {
  962. handleCmdFrame(len);
  963. } else if (_iter_started // check if our ContactsIterator is 'running'
  964. && !_serial->isWriteBusy() // don't spam the Serial Interface too quickly!
  965. ) {
  966. ContactInfo contact;
  967. if (_iter.hasNext(this, contact)) {
  968. if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter
  969. writeContactRespFrame(RESP_CODE_CONTACT, contact);
  970. if (contact.lastmod > _most_recent_lastmod) {
  971. _most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame
  972. }
  973. }
  974. } else { // EOF
  975. out_frame[0] = RESP_CODE_END_OF_CONTACTS;
  976. memcpy(&out_frame[1], &_most_recent_lastmod, 4); // include the most recent lastmod, so app can update their 'since'
  977. _serial->writeFrame(out_frame, 5);
  978. _iter_started = false;
  979. }
  980. } else if (!_serial->isWriteBusy()) {
  981. checkConnections();
  982. }
  983. }
  984. };
  985. #ifdef ESP32
  986. #ifdef BLE_PIN_CODE
  987. #include <helpers/esp32/SerialBLEInterface.h>
  988. SerialBLEInterface serial_interface;
  989. #else
  990. #include <helpers/ArduinoSerialInterface.h>
  991. ArduinoSerialInterface serial_interface;
  992. #endif
  993. #elif defined(NRF52_PLATFORM)
  994. #ifdef BLE_PIN_CODE
  995. #include <helpers/nrf52/SerialBLEInterface.h>
  996. SerialBLEInterface serial_interface;
  997. #else
  998. #include <helpers/ArduinoSerialInterface.h>
  999. ArduinoSerialInterface serial_interface;
  1000. #endif
  1001. #else
  1002. #error "need to define a serial interface"
  1003. #endif
  1004. #if defined(NRF52_PLATFORM)
  1005. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  1006. #elif defined(P_LORA_SCLK)
  1007. SPIClass spi;
  1008. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  1009. #else
  1010. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  1011. #endif
  1012. StdRNG fast_rng;
  1013. SimpleMeshTables tables;
  1014. MyMesh the_mesh(radio, *new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  1015. void halt() {
  1016. while (1) ;
  1017. }
  1018. void setup() {
  1019. Serial.begin(115200);
  1020. board.begin();
  1021. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  1022. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  1023. #else
  1024. float tcxo = 1.6f;
  1025. #endif
  1026. #if defined(NRF52_PLATFORM)
  1027. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  1028. SPI.begin();
  1029. #elif defined(P_LORA_SCLK)
  1030. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  1031. #endif
  1032. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  1033. if (status != RADIOLIB_ERR_NONE) {
  1034. Serial.print("ERROR: radio init failed: ");
  1035. Serial.println(status);
  1036. halt();
  1037. }
  1038. radio.setCRC(0);
  1039. #ifdef SX126X_CURRENT_LIMIT
  1040. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  1041. #endif
  1042. #ifdef SX126X_DIO2_AS_RF_SWITCH
  1043. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  1044. #endif
  1045. fast_rng.begin(radio.random(0x7FFFFFFF));
  1046. RadioNoiseListener trng(radio);
  1047. #if defined(NRF52_PLATFORM)
  1048. InternalFS.begin();
  1049. the_mesh.begin(InternalFS, trng);
  1050. #ifdef BLE_PIN_CODE
  1051. char dev_name[32+10];
  1052. sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
  1053. serial_interface.begin(dev_name, BLE_PIN_CODE);
  1054. #else
  1055. pinMode(WB_IO2, OUTPUT);
  1056. serial_interface.begin(Serial);
  1057. #endif
  1058. the_mesh.startInterface(serial_interface);
  1059. #elif defined(ESP32)
  1060. SPIFFS.begin(true);
  1061. the_mesh.begin(SPIFFS, trng);
  1062. #ifdef BLE_PIN_CODE
  1063. char dev_name[32+10];
  1064. sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
  1065. serial_interface.begin(dev_name, BLE_PIN_CODE);
  1066. #else
  1067. serial_interface.begin(Serial);
  1068. #endif
  1069. the_mesh.startInterface(serial_interface);
  1070. #else
  1071. #error "need to define filesystem"
  1072. #endif
  1073. }
  1074. void loop() {
  1075. the_mesh.loop();
  1076. }