main.cpp 53 KB

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