main.cpp 63 KB

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