main.cpp 54 KB

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