main.cpp 61 KB

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