main.cpp 49 KB

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