main.cpp 50 KB

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