main.cpp 54 KB

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