main.cpp 52 KB

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