main.cpp 62 KB

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