main.cpp 51 KB

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