main.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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_CONTACTS
  34. #define MAX_CONTACTS 100
  35. #endif
  36. #include <helpers/BaseChatMesh.h>
  37. #define SEND_TIMEOUT_BASE_MILLIS 300
  38. #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
  39. #define DIRECT_SEND_PERHOP_FACTOR 4.0f
  40. #define DIRECT_SEND_PERHOP_EXTRA_MILLIS 200
  41. #define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
  42. #if defined(HELTEC_LORA_V3)
  43. #include <helpers/HeltecV3Board.h>
  44. #include <helpers/CustomSX1262Wrapper.h>
  45. static HeltecV3Board board;
  46. #elif defined(ARDUINO_XIAO_ESP32C3)
  47. #include <helpers/XiaoC3Board.h>
  48. #include <helpers/CustomSX1262Wrapper.h>
  49. #include <helpers/CustomSX1268Wrapper.h>
  50. static XiaoC3Board board;
  51. #elif defined(SEEED_XIAO_S3)
  52. #include <helpers/ESP32Board.h>
  53. #include <helpers/CustomSX1262Wrapper.h>
  54. static ESP32Board board;
  55. #elif defined(RAK_4631)
  56. #include <helpers/nrf52/RAK4631Board.h>
  57. #include <helpers/CustomSX1262Wrapper.h>
  58. static RAK4631Board board;
  59. #else
  60. #error "need to provide a 'board' object"
  61. #endif
  62. // Believe it or not, this std C function is busted on some platforms!
  63. static uint32_t _atoi(const char* sp) {
  64. uint32_t n = 0;
  65. while (*sp && *sp >= '0' && *sp <= '9') {
  66. n *= 10;
  67. n += (*sp++ - '0');
  68. }
  69. return n;
  70. }
  71. /*------------ Frame Protocol --------------*/
  72. #define CMD_APP_START 1
  73. #define CMD_SEND_TXT_MSG 2
  74. #define CMD_SEND_CHANNEL_TXT_MSG 3
  75. #define CMD_GET_CONTACTS 4 // with optional 'since' (for efficient sync)
  76. #define CMD_GET_DEVICE_TIME 5
  77. #define CMD_SET_DEVICE_TIME 6
  78. #define CMD_SEND_SELF_ADVERT 7
  79. #define CMD_SET_ADVERT_NAME 8
  80. #define CMD_ADD_UPDATE_CONTACT 9
  81. #define CMD_SYNC_NEXT_MESSAGE 10
  82. #define CMD_SET_RADIO_PARAMS 11
  83. #define RESP_CODE_OK 0
  84. #define RESP_CODE_ERR 1
  85. #define RESP_CODE_CONTACTS_START 2 // first reply to CMD_GET_CONTACTS
  86. #define RESP_CODE_CONTACT 3 // multiple of these (after CMD_GET_CONTACTS)
  87. #define RESP_CODE_END_OF_CONTACTS 4 // last reply to CMD_GET_CONTACTS
  88. #define RESP_CODE_SELF_INFO 5 // reply to CMD_APP_START
  89. #define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG
  90. #define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE
  91. #define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE
  92. // these are _pushed_ to client app at any time
  93. #define PUSH_CODE_ADVERT 0x80
  94. #define PUSH_CODE_PATH_UPDATED 0x81
  95. #define PUSH_CODE_SEND_CONFIRMED 0x82
  96. #define PUSH_CODE_MSG_WAITING 0x83
  97. /* -------------------------------------------------------------------------------------- */
  98. struct NodePrefs { // persisted to file
  99. float airtime_factor;
  100. char node_name[32];
  101. double node_lat, node_lon;
  102. float freq;
  103. uint8_t sf;
  104. uint8_t cr;
  105. uint8_t reserved1;
  106. uint8_t reserved2;
  107. float bw;
  108. };
  109. class MyMesh : public BaseChatMesh {
  110. FILESYSTEM* _fs;
  111. NodePrefs _prefs;
  112. uint32_t expected_ack_crc; // TODO: keep table of expected ACKs
  113. mesh::GroupChannel* _public;
  114. BaseSerialInterface* _serial;
  115. unsigned long last_msg_sent;
  116. ContactsIterator _iter;
  117. uint32_t _iter_filter_since;
  118. uint32_t _most_recent_lastmod;
  119. bool _iter_started;
  120. uint8_t cmd_frame[MAX_FRAME_SIZE+1];
  121. uint8_t out_frame[MAX_FRAME_SIZE+1];
  122. void loadContacts() {
  123. if (_fs->exists("/contacts3")) {
  124. File file = _fs->open("/contacts3");
  125. if (file) {
  126. bool full = false;
  127. while (!full) {
  128. ContactInfo c;
  129. uint8_t pub_key[32];
  130. uint8_t unused;
  131. uint32_t reserved;
  132. bool success = (file.read(pub_key, 32) == 32);
  133. success = success && (file.read((uint8_t *) &c.name, 32) == 32);
  134. success = success && (file.read(&c.type, 1) == 1);
  135. success = success && (file.read(&c.flags, 1) == 1);
  136. success = success && (file.read(&unused, 1) == 1);
  137. success = success && (file.read((uint8_t *) &reserved, 4) == 4);
  138. success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
  139. success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  140. success = success && (file.read(c.out_path, 64) == 64);
  141. success = success && (file.read((uint8_t *) c.lastmod, 4) == 4);
  142. success = success && (file.read((uint8_t *) c.gps_lat, 4) == 4);
  143. success = success && (file.read((uint8_t *) c.gps_lon, 4) == 4);
  144. if (!success) break; // EOF
  145. c.id = mesh::Identity(pub_key);
  146. if (!addContact(c)) full = true;
  147. }
  148. file.close();
  149. }
  150. }
  151. }
  152. void saveContacts() {
  153. #if defined(NRF52_PLATFORM)
  154. File file = _fs->open("/contacts3", FILE_O_WRITE);
  155. if (file) { file.seek(0); file.truncate(); }
  156. #else
  157. File file = _fs->open("/contacts3", "w", true);
  158. #endif
  159. if (file) {
  160. ContactsIterator iter;
  161. ContactInfo c;
  162. uint8_t unused = 0;
  163. uint32_t reserved = 0;
  164. while (iter.hasNext(this, c)) {
  165. bool success = (file.write(c.id.pub_key, 32) == 32);
  166. success = success && (file.write((uint8_t *) &c.name, 32) == 32);
  167. success = success && (file.write(&c.type, 1) == 1);
  168. success = success && (file.write(&c.flags, 1) == 1);
  169. success = success && (file.write(&unused, 1) == 1);
  170. success = success && (file.write((uint8_t *) &reserved, 4) == 4);
  171. success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
  172. success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
  173. success = success && (file.write(c.out_path, 64) == 64);
  174. success = success && (file.write((uint8_t *) &c.lastmod, 4) == 4);
  175. success = success && (file.write((uint8_t *) &c.gps_lat, 4) == 4);
  176. success = success && (file.write((uint8_t *) &c.gps_lon, 4) == 4);
  177. if (!success) break; // write failed
  178. }
  179. file.close();
  180. }
  181. }
  182. void writeOKFrame() {
  183. uint8_t buf[1];
  184. buf[0] = RESP_CODE_OK;
  185. _serial->writeFrame(buf, 1);
  186. }
  187. void writeErrFrame() {
  188. uint8_t buf[1];
  189. buf[0] = RESP_CODE_ERR;
  190. _serial->writeFrame(buf, 1);
  191. }
  192. void writeContactRespFrame(uint8_t code, const ContactInfo& contact) {
  193. int i = 0;
  194. out_frame[i++] = code;
  195. memcpy(&out_frame[i], contact.id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  196. out_frame[i++] = contact.type;
  197. out_frame[i++] = contact.flags;
  198. out_frame[i++] = contact.out_path_len;
  199. memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  200. memcpy(&out_frame[i], contact.name, 32); i += 32;
  201. memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); i += 4;
  202. memcpy(&out_frame[i], &contact.gps_lat, 4); i += 4;
  203. memcpy(&out_frame[i], &contact.gps_lon, 4); i += 4;
  204. memcpy(&out_frame[i], &contact.lastmod, 4); i += 4;
  205. _serial->writeFrame(out_frame, i);
  206. }
  207. void updateContactFromFrame(ContactInfo& contact, const uint8_t* frame, int len) {
  208. int i = 0;
  209. uint8_t code = frame[i++]; // eg. CMD_ADD_UPDATE_CONTACT
  210. memcpy(contact.id.pub_key, &frame[i], PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  211. contact.type = frame[i++];
  212. contact.flags = frame[i++];
  213. contact.out_path_len = frame[i++];
  214. memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE); i += MAX_PATH_SIZE;
  215. memcpy(contact.name, &frame[i], 32); i += 32;
  216. memcpy(&contact.last_advert_timestamp, &frame[i], 4); i += 4;
  217. if (i + 8 >= len) { // optional fields
  218. memcpy(&contact.gps_lat, &frame[i], 4); i += 4;
  219. memcpy(&contact.gps_lon, &frame[i], 4); i += 4;
  220. }
  221. }
  222. void addToOfflineQueue(const uint8_t frame[], int len) {
  223. // TODO
  224. }
  225. int getFromOfflineQueue(uint8_t frame[]) {
  226. return 0; // queue is empty
  227. }
  228. void soundBuzzer() {
  229. // TODO
  230. }
  231. protected:
  232. void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
  233. if (_serial->isConnected()) {
  234. out_frame[0] = PUSH_CODE_ADVERT;
  235. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  236. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE);
  237. } else {
  238. soundBuzzer();
  239. }
  240. saveContacts();
  241. }
  242. void onContactPathUpdated(const ContactInfo& contact) override {
  243. out_frame[0] = PUSH_CODE_PATH_UPDATED;
  244. memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE);
  245. _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); // NOTE: app may not be connected
  246. saveContacts();
  247. }
  248. bool processAck(const uint8_t *data) override {
  249. // TODO: see if matches any in a table
  250. if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
  251. out_frame[0] = PUSH_CODE_SEND_CONFIRMED;
  252. memcpy(&out_frame[1], data, 4);
  253. uint32_t trip_time = _ms->getMillis() - last_msg_sent;
  254. memcpy(&out_frame[5], &trip_time, 4);
  255. _serial->writeFrame(out_frame, 9);
  256. // NOTE: the same ACK can be received multiple times!
  257. expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
  258. return true;
  259. }
  260. return false;
  261. }
  262. void onMessageRecv(const ContactInfo& from, uint8_t path_len, uint32_t sender_timestamp, const char *text) override {
  263. int i = 0;
  264. out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV;
  265. memcpy(&out_frame[i], from.id.pub_key, 6); i += 6; // just 6-byte prefix
  266. out_frame[i++] = path_len;
  267. out_frame[i++] = TXT_TYPE_PLAIN;
  268. memcpy(&out_frame[i], &sender_timestamp, 4); i += 4;
  269. int tlen = strlen(text); // TODO: UTF-8 ??
  270. if (i + tlen > MAX_FRAME_SIZE) {
  271. tlen = MAX_FRAME_SIZE - i;
  272. }
  273. memcpy(&out_frame[i], text, tlen); i += tlen;
  274. addToOfflineQueue(out_frame, i);
  275. if (_serial->isConnected()) {
  276. uint8_t frame[1];
  277. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  278. _serial->writeFrame(frame, 1);
  279. } else {
  280. soundBuzzer();
  281. }
  282. }
  283. void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
  284. int i = 0;
  285. out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV;
  286. out_frame[i++] = in_path_len < 0 ? 0xFF : in_path_len;
  287. out_frame[i++] = TXT_TYPE_PLAIN;
  288. memcpy(&out_frame[i], &timestamp, 4); i += 4;
  289. int tlen = strlen(text); // TODO: UTF-8 ??
  290. if (i + tlen > MAX_FRAME_SIZE) {
  291. tlen = MAX_FRAME_SIZE - i;
  292. }
  293. memcpy(&out_frame[i], text, tlen); i += tlen;
  294. addToOfflineQueue(out_frame, i);
  295. if (_serial->isConnected()) {
  296. uint8_t frame[1];
  297. frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
  298. _serial->writeFrame(frame, 1);
  299. } else {
  300. soundBuzzer();
  301. }
  302. }
  303. uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
  304. return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
  305. }
  306. uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override {
  307. return SEND_TIMEOUT_BASE_MILLIS +
  308. ( (pkt_airtime_millis*DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * (path_len + 1));
  309. }
  310. void onSendTimeout() override {
  311. Serial.println(" ERROR: timed out, no ACK.");
  312. }
  313. public:
  314. MyMesh(RadioLibWrapper& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
  315. : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL)
  316. {
  317. _iter_started = false;
  318. // defaults
  319. _prefs.airtime_factor = 1.0; // one half
  320. strcpy(_prefs.node_name, "NONAME");
  321. _prefs.node_lat = 0;
  322. _prefs.node_lon = 0;
  323. _prefs.freq = LORA_FREQ;
  324. _prefs.sf = LORA_SF;
  325. _prefs.bw = LORA_BW;
  326. _prefs.cr = LORA_CR;
  327. _prefs.reserved1 = 0;
  328. _prefs.reserved2 = 0;
  329. }
  330. float getFreqPref() const { return _prefs.freq; }
  331. uint8_t getSFPref() const { return _prefs.sf; }
  332. uint8_t getCRPref() const { return _prefs.cr; }
  333. float getBWPref() const { return _prefs.bw; }
  334. void begin(FILESYSTEM& fs, BaseSerialInterface& serial, mesh::RNG& trng) {
  335. _fs = &fs;
  336. _serial = &serial;
  337. BaseChatMesh::begin();
  338. IdentityStore store(fs, "/identity");
  339. if (!store.load("_main", self_id)) {
  340. self_id = mesh::LocalIdentity(&trng); // create new random identity
  341. store.save("_main", self_id);
  342. }
  343. // load persisted prefs
  344. if (_fs->exists("/node_prefs")) {
  345. File file = _fs->open("/node_prefs");
  346. if (file) {
  347. file.read((uint8_t *) &_prefs, sizeof(_prefs));
  348. file.close();
  349. }
  350. }
  351. loadContacts();
  352. _public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
  353. }
  354. void savePrefs() {
  355. #if defined(NRF52_PLATFORM)
  356. File file = _fs->open("/node_prefs", FILE_O_WRITE);
  357. if (file) { file.seek(0); file.truncate(); }
  358. #else
  359. File file = _fs->open("/node_prefs", "w", true);
  360. #endif
  361. if (file) {
  362. file.write((const uint8_t *)&_prefs, sizeof(_prefs));
  363. file.close();
  364. }
  365. }
  366. void handleCmdFrame(size_t len) {
  367. if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
  368. uint8_t app_ver = cmd_frame[1];
  369. // cmd_frame[2..7] reserved future
  370. char* app_name = (char *) &cmd_frame[8];
  371. cmd_frame[len] = 0; // make app_name null terminated
  372. MESH_DEBUG_PRINTLN("App %s connected, ver: %d", app_name, (uint32_t)app_ver);
  373. _iter_started = false; // stop any left-over ContactsIterator
  374. int i = 0;
  375. out_frame[i++] = RESP_CODE_SELF_INFO;
  376. out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-)
  377. out_frame[i++] = 0; // reserved
  378. out_frame[i++] = 0; // reserved
  379. memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
  380. int32_t latlonsats = 0;
  381. memcpy(&out_frame[i], &latlonsats, 4); i += 4; // reserved future, for companion radios with GPS (like T-Beam, T1000)
  382. memcpy(&out_frame[i], &latlonsats, 4); i += 4;
  383. memcpy(&out_frame[i], &latlonsats, 4); i += 4;
  384. uint32_t freq = _prefs.freq * 1000;
  385. memcpy(&out_frame[i], &freq, 4); i += 4;
  386. uint32_t bw = _prefs.bw*1000;
  387. memcpy(&out_frame[i], &bw, 4); i += 4;
  388. out_frame[i++] = _prefs.sf;
  389. out_frame[i++] = _prefs.cr;
  390. int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ??
  391. memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen;
  392. _serial->writeFrame(out_frame, i);
  393. } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) {
  394. int i = 1;
  395. uint8_t txt_type = cmd_frame[i++];
  396. uint8_t attempt = cmd_frame[i++];
  397. uint32_t msg_timestamp;
  398. memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
  399. uint8_t* pub_key_prefix = &cmd_frame[i]; i += 6;
  400. ContactInfo* recipient = lookupContactByPubKey(pub_key_prefix, 6);
  401. if (recipient && attempt < 4 && txt_type == TXT_TYPE_PLAIN) {
  402. char *text = (char *) &cmd_frame[i];
  403. int tlen = len - i;
  404. uint32_t est_timeout;
  405. text[tlen] = 0; // ensure null
  406. int result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack_crc, est_timeout);
  407. // TODO: add expected ACK to table
  408. if (result == MSG_SEND_FAILED) {
  409. writeErrFrame();
  410. } else {
  411. last_msg_sent = _ms->getMillis();
  412. out_frame[0] = RESP_CODE_SENT;
  413. out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
  414. memcpy(&out_frame[2], &expected_ack_crc, 4);
  415. memcpy(&out_frame[6], &est_timeout, 4);
  416. _serial->writeFrame(out_frame, 10);
  417. }
  418. } else {
  419. writeErrFrame(); // unknown recipient, or unsuported TXT_TYPE_*
  420. }
  421. } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg
  422. #if 0 //TODO
  423. uint8_t temp[5+MAX_TEXT_LEN+32];
  424. uint32_t timestamp = getRTCClock()->getCurrentTime();
  425. memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
  426. temp[4] = 0; // attempt and flags
  427. sprintf((char *) &temp[5], "%s: %s", self_name, &command[7]); // <sender>: <msg>
  428. temp[5 + MAX_TEXT_LEN] = 0; // truncate if too long
  429. int len = strlen((char *) &temp[5]);
  430. auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, *_public, temp, 5 + len);
  431. if (pkt) {
  432. sendFlood(pkt);
  433. Serial.println(" Sent.");
  434. } else {
  435. Serial.println(" ERROR: unable to send");
  436. }
  437. #else
  438. writeErrFrame();
  439. #endif
  440. } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list
  441. if (_iter_started) {
  442. writeErrFrame(); // iterator is currently busy
  443. } else {
  444. if (len >= 5) { // has optional 'since' param
  445. memcpy(&_iter_filter_since, &cmd_frame[1], 4);
  446. } else {
  447. _iter_filter_since = 0;
  448. }
  449. uint8_t reply[5];
  450. reply[0] = RESP_CODE_CONTACTS_START;
  451. uint32_t count = getNumContacts(); // total, NOT filtered count
  452. memcpy(&reply[1], &count, 4);
  453. _serial->writeFrame(reply, 5);
  454. // start iterator
  455. _iter = startContactsIterator();
  456. _iter_started = true;
  457. _most_recent_lastmod = 0;
  458. }
  459. } else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) {
  460. int nlen = len - 1;
  461. if (nlen > sizeof(_prefs.node_name)-1) nlen = sizeof(_prefs.node_name)-1; // max len
  462. memcpy(_prefs.node_name, &cmd_frame[1], nlen);
  463. _prefs.node_name[nlen] = 0; // null terminator
  464. savePrefs();
  465. writeOKFrame();
  466. } else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) {
  467. uint8_t reply[5];
  468. reply[0] = RESP_CODE_OK;
  469. uint32_t now = getRTCClock()->getCurrentTime();
  470. memcpy(&reply[1], &now, 4);
  471. _serial->writeFrame(reply, 5);
  472. } else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
  473. uint32_t secs;
  474. memcpy(&secs, &cmd_frame[1], 4);
  475. uint32_t curr = getRTCClock()->getCurrentTime();
  476. if (secs > curr) {
  477. getRTCClock()->setCurrentTime(secs);
  478. writeOKFrame();
  479. } else {
  480. writeErrFrame();
  481. }
  482. } else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
  483. auto pkt = createSelfAdvert(_prefs.node_name);
  484. if (pkt) {
  485. if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop)
  486. sendFlood(pkt);
  487. } else {
  488. sendZeroHop(pkt);
  489. }
  490. writeOKFrame();
  491. } else {
  492. writeErrFrame();
  493. }
  494. } else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1+32+2+1) {
  495. uint8_t* pub_key = &cmd_frame[1];
  496. ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
  497. if (recipient) {
  498. updateContactFromFrame(*recipient, cmd_frame, len);
  499. //recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
  500. saveContacts();
  501. writeOKFrame();
  502. } else {
  503. ContactInfo contact;
  504. updateContactFromFrame(contact, cmd_frame, len);
  505. contact.lastmod = getRTCClock()->getCurrentTime();
  506. if (addContact(contact)) {
  507. saveContacts();
  508. writeOKFrame();
  509. } else {
  510. writeErrFrame(); // table is full!
  511. }
  512. }
  513. } else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) {
  514. int out_len;
  515. if ((out_len = getFromOfflineQueue(out_frame)) > 0) {
  516. _serial->writeFrame(out_frame, out_len);
  517. }
  518. } else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) {
  519. int i = 1;
  520. uint32_t freq;
  521. memcpy(&freq, &cmd_frame[i], 4); i += 4;
  522. uint32_t bw;
  523. memcpy(&bw, &cmd_frame[i], 4); i += 4;
  524. uint8_t sf = out_frame[i++];
  525. uint8_t cr = out_frame[i++];
  526. if (freq >= 300000 && freq <= 2500000 && sf >= 7 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && bw <= 500000) {
  527. _prefs.sf = sf;
  528. _prefs.cr = cr;
  529. _prefs.freq = (float)freq / 1000.0;
  530. _prefs.bw = (float)bw / 1000.0;
  531. savePrefs();
  532. writeOKFrame(); // reboot now required!
  533. } else {
  534. writeErrFrame();
  535. }
  536. } else {
  537. writeErrFrame();
  538. MESH_DEBUG_PRINTLN("ERROR: unknown command: %02X", cmd_frame[0]);
  539. }
  540. }
  541. void loop() {
  542. BaseChatMesh::loop();
  543. size_t len = _serial->checkRecvFrame(cmd_frame);
  544. if (len > 0) {
  545. handleCmdFrame(len);
  546. } else if (_iter_started // check if our ContactsIterator is 'running'
  547. && !_serial->isWriteBusy() // don't spam the Serial Interface too quickly!
  548. ) {
  549. ContactInfo contact;
  550. if (_iter.hasNext(this, contact)) {
  551. if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter
  552. writeContactRespFrame(RESP_CODE_CONTACT, contact);
  553. if (contact.lastmod > _most_recent_lastmod) {
  554. _most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame
  555. }
  556. }
  557. } else { // EOF
  558. out_frame[0] = RESP_CODE_END_OF_CONTACTS;
  559. memcpy(&out_frame[1], &_most_recent_lastmod, 4); // include the most recent lastmod, so app can update their 'since'
  560. _serial->writeFrame(out_frame, 5);
  561. _iter_started = false;
  562. }
  563. }
  564. }
  565. };
  566. #ifdef ESP32
  567. #ifdef BLE_PIN_CODE
  568. #include <helpers/esp32/SerialBLEInterface.h>
  569. SerialBLEInterface serial_interface;
  570. #else
  571. #include <helpers/ArduinoSerialInterface.h>
  572. ArduinoSerialInterface serial_interface;
  573. #endif
  574. #elif defined(NRF52_PLATFORM)
  575. #ifdef BLE_PIN_CODE
  576. #error "BLE not defined yet"
  577. #else
  578. #include <helpers/ArduinoSerialInterface.h>
  579. ArduinoSerialInterface serial_interface;
  580. #endif
  581. #else
  582. #error "need to define a serial interface"
  583. #endif
  584. #if defined(NRF52_PLATFORM)
  585. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI);
  586. #elif defined(P_LORA_SCLK)
  587. SPIClass spi;
  588. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
  589. #else
  590. RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
  591. #endif
  592. StdRNG fast_rng;
  593. SimpleMeshTables tables;
  594. MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
  595. void halt() {
  596. while (1) ;
  597. }
  598. void setup() {
  599. Serial.begin(115200);
  600. board.begin();
  601. #ifdef SX126X_DIO3_TCXO_VOLTAGE
  602. float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
  603. #else
  604. float tcxo = 1.6f;
  605. #endif
  606. #if defined(NRF52_PLATFORM)
  607. SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
  608. SPI.begin();
  609. #elif defined(P_LORA_SCLK)
  610. spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
  611. #endif
  612. int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 8, tcxo);
  613. if (status != RADIOLIB_ERR_NONE) {
  614. Serial.print("ERROR: radio init failed: ");
  615. Serial.println(status);
  616. halt();
  617. }
  618. radio.setCRC(0);
  619. #ifdef SX126X_CURRENT_LIMIT
  620. radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
  621. #endif
  622. #ifdef SX126X_DIO2_AS_RF_SWITCH
  623. radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
  624. #endif
  625. fast_rng.begin(radio.random(0x7FFFFFFF));
  626. RadioNoiseListener trng(radio);
  627. #if defined(NRF52_PLATFORM)
  628. InternalFS.begin();
  629. the_mesh.begin(InternalFS, serial_interface, trng);
  630. #elif defined(ESP32)
  631. SPIFFS.begin(true);
  632. #ifdef BLE_PIN_CODE
  633. serial_interface.begin("MeshCore", BLE_PIN_CODE);
  634. #else
  635. serial_interface.begin(Serial);
  636. #endif
  637. serial_interface.enable();
  638. the_mesh.begin(SPIFFS, serial_interface, trng);
  639. #else
  640. #error "need to define filesystem"
  641. #endif
  642. if (LORA_FREQ != the_mesh.getFreqPref()) {
  643. radio.setFrequency(the_mesh.getFreqPref());
  644. }
  645. if (LORA_SF != the_mesh.getSFPref()) {
  646. radio.setSpreadingFactor(the_mesh.getSFPref());
  647. }
  648. if (LORA_BW != the_mesh.getBWPref()) {
  649. radio.setBandwidth(the_mesh.getBWPref());
  650. }
  651. if (LORA_CR != the_mesh.getCRPref()) {
  652. radio.setCodingRate(the_mesh.getCRPref());
  653. }
  654. }
  655. void loop() {
  656. the_mesh.loop();
  657. }