main.cpp 45 KB

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