main.cpp 61 KB

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