main.cpp 54 KB

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