main.cpp 53 KB

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