main.cpp 26 KB

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