app.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
  2. * See the LICENSE file for information about the license. */
  3. #include <furi.h>
  4. #include <furi_hal.h>
  5. #include <lib/flipper_format/flipper_format.h>
  6. #include <input/input.h>
  7. #include <gui/gui.h>
  8. #include <stdlib.h>
  9. #include "app.h"
  10. #include "app_buffer.h"
  11. RawSamplesBuffer *RawSamples, *DetectedSamples;
  12. extern const SubGhzProtocolRegistry protoview_protocol_registry;
  13. /* Render the received signal.
  14. *
  15. * The screen of the flipper is 128 x 64. Even using 4 pixels per line
  16. * (where low level signal is one pixel high, high level is 4 pixels
  17. * high) and 4 pixels of spacing between the different lines, we can
  18. * plot comfortably 8 lines.
  19. *
  20. * The 'idx' argument is the first sample to render in the circular
  21. * buffer. */
  22. void render_signal(ProtoViewApp *app, Canvas *const canvas, RawSamplesBuffer *buf, uint32_t idx) {
  23. canvas_set_color(canvas, ColorBlack);
  24. int rows = 8;
  25. uint32_t time_per_pixel = app->us_scale;
  26. bool level = 0;
  27. uint32_t dur = 0, sample_num = 0;
  28. for (int row = 0; row < rows ; row++) {
  29. for (int x = 0; x < 128; x++) {
  30. int y = 3 + row*8;
  31. if (dur < time_per_pixel/2) {
  32. /* Get more data. */
  33. raw_samples_get(buf, idx++, &level, &dur);
  34. sample_num++;
  35. }
  36. canvas_draw_line(canvas, x,y,x,y-(level*3));
  37. /* Write a small triangle under the last sample detected. */
  38. if (app->signal_bestlen != 0 &&
  39. sample_num == app->signal_bestlen+1)
  40. {
  41. canvas_draw_dot(canvas,x,y+2);
  42. canvas_draw_dot(canvas,x-1,y+3);
  43. canvas_draw_dot(canvas,x,y+3);
  44. canvas_draw_dot(canvas,x+1,y+3);
  45. sample_num++; /* Make sure we don't mark the next, too. */
  46. }
  47. /* Remove from the current level duration the time we
  48. * just plot. */
  49. if (dur > time_per_pixel)
  50. dur -= time_per_pixel;
  51. else
  52. dur = 0;
  53. }
  54. }
  55. }
  56. /* Return the time difference between a and b, always >= 0 since
  57. * the absolute value is returned. */
  58. uint32_t duration_delta(uint32_t a, uint32_t b) {
  59. return a > b ? a - b : b -a;
  60. }
  61. /* This function starts scanning samples at offset idx looking for the
  62. * longest run of pulses, either high or low, that are among 10%
  63. * of each other, for a maximum of three classes. The classes are
  64. * counted separtely for high and low signals (RF on / off) because
  65. * many devices tend to have different pulse lenghts depending on
  66. * the level of the pulse.
  67. *
  68. * For instance Oregon2 sensors, in the case of protocol 2.1 will send
  69. * pulses of ~400us (RF on) VS ~580us (RF off). */
  70. #define SEARCH_CLASSES 3
  71. uint32_t search_coherent_signal(RawSamplesBuffer *s, uint32_t idx) {
  72. struct {
  73. uint32_t dur[2]; /* dur[0] = low, dur[1] = high */
  74. uint32_t count[2]; /* Associated observed frequency. */
  75. } classes[SEARCH_CLASSES];
  76. memset(classes,0,sizeof(classes));
  77. uint32_t minlen = 40, maxlen = 4000; /* Depends on data rate, here we
  78. allow for high and low. */
  79. uint32_t len = 0; /* Observed len of coherent samples. */
  80. s->short_pulse_dur = 0;
  81. for (uint32_t j = idx; j < idx+500; j++) {
  82. bool level;
  83. uint32_t dur;
  84. raw_samples_get(s, j, &level, &dur);
  85. if (dur < minlen || dur > maxlen) break; /* return. */
  86. /* Let's see if it matches a class we already have or if we
  87. * can populate a new (yet empty) class. */
  88. uint32_t k;
  89. for (k = 0; k < SEARCH_CLASSES; k++) {
  90. if (classes[k].count[level] == 0) {
  91. classes[k].dur[level] = dur;
  92. classes[k].count[level] = 1;
  93. break; /* Sample accepted. */
  94. } else {
  95. uint32_t classavg = classes[k].dur[level];
  96. uint32_t count = classes[k].count[level];
  97. uint32_t delta = duration_delta(dur,classavg);
  98. if (delta < classavg/10) {
  99. /* It is useful to compute the average of the class
  100. * we are observing. We know how many samples we got so
  101. * far, so we can recompute the average easily.
  102. * By always having a better estimate of the pulse len
  103. * we can avoid missing next samples in case the first
  104. * observed samples are too off. */
  105. classavg = ((classavg * count) + dur) / (count+1);
  106. classes[k].dur[level] = classavg;
  107. classes[k].count[level]++;
  108. break; /* Sample accepted. */
  109. }
  110. }
  111. }
  112. if (k == SEARCH_CLASSES) break; /* No match, return. */
  113. /* If we are here, we accepted this sample. Try with the next
  114. * one. */
  115. len++;
  116. }
  117. /* Update the buffer setting the shortest pulse we found
  118. * among the three classes. This will be used when scaling
  119. * for visualization. */
  120. for (int j = 0; j < SEARCH_CLASSES; j++) {
  121. for (int level = 0; level < 2; level++) {
  122. if (classes[j].dur[level] == 0) continue;
  123. if (classes[j].count[level] < 3) continue;
  124. if (s->short_pulse_dur == 0 ||
  125. s->short_pulse_dur > classes[j].dur[level])
  126. {
  127. s->short_pulse_dur = classes[j].dur[level];
  128. }
  129. }
  130. }
  131. return len;
  132. }
  133. /* Search the buffer with the stored signal (last N samples received)
  134. * in order to find a coherent signal. If a signal that does not appear to
  135. * be just noise is found, it is set in DetectedSamples global signal
  136. * buffer, that is what is rendered on the screen. */
  137. void scan_for_signal(ProtoViewApp *app) {
  138. /* We need to work on a copy: the RawSamples buffer is populated
  139. * by the background thread receiving data. */
  140. RawSamplesBuffer *copy = raw_samples_alloc();
  141. raw_samples_copy(copy,RawSamples);
  142. /* Try to seek on data that looks to have a regular high low high low
  143. * pattern. */
  144. uint32_t minlen = 13; /* Min run of coherent samples. Up to
  145. 12 samples it's very easy to mistake
  146. noise for signal. */
  147. for (uint32_t i = 0; i < copy->total-1; i++) {
  148. uint32_t thislen = search_coherent_signal(copy,i);
  149. if (thislen > minlen && thislen > app->signal_bestlen) {
  150. app->signal_bestlen = thislen;
  151. raw_samples_copy(DetectedSamples,copy);
  152. DetectedSamples->idx = (DetectedSamples->idx+i)%
  153. DetectedSamples->total;
  154. FURI_LOG_E(TAG, "Displayed sample updated (%d samples)",
  155. (int)thislen);
  156. }
  157. }
  158. raw_samples_free(copy);
  159. }
  160. /* Draw some text with a border. If the outside color is black and the inside
  161. * color is white, it just writes the border of the text, but the function can
  162. * also be used to write a bold variation of the font setting both the
  163. * colors to black, or alternatively to write a black text with a white
  164. * border so that it is visible if there are black stuff on the background. */
  165. void canvas_draw_str_with_border(Canvas* canvas, uint8_t x, uint8_t y, const char* str, Color text_color, Color border_color)
  166. {
  167. struct {
  168. uint8_t x; uint8_t y;
  169. } dir[8] = {
  170. {-1,-1},
  171. {0,-1},
  172. {1,-1},
  173. {1,0},
  174. {1,1},
  175. {0,1},
  176. {-1,1},
  177. {-1,0}
  178. };
  179. /* Rotate in all the directions writing the same string to create a
  180. * border, then write the actual string in the other color in the
  181. * middle. */
  182. canvas_set_color(canvas, border_color);
  183. for (int j = 0; j < 8; j++)
  184. canvas_draw_str(canvas,x+dir[j].x,y+dir[j].y,str);
  185. canvas_set_color(canvas, text_color);
  186. canvas_draw_str(canvas,x,y,str);
  187. canvas_set_color(canvas, ColorBlack);
  188. }
  189. /* Raw pulses rendering. This is our default view. */
  190. void render_view_raw_pulses(Canvas *const canvas, ProtoViewApp *app) {
  191. /* Show signal. */
  192. render_signal(app, canvas, DetectedSamples, 0);
  193. /* Show signal information. */
  194. char buf[64];
  195. snprintf(buf,sizeof(buf),"%luus",
  196. (unsigned long)DetectedSamples->short_pulse_dur);
  197. canvas_set_font(canvas, FontSecondary);
  198. canvas_draw_str_with_border(canvas, 97, 63, buf, ColorWhite, ColorBlack);
  199. }
  200. /* Renders a single view with frequency and modulation setting. However
  201. * this are logically two different views, and only one of the settings
  202. * will be highlighted. */
  203. void render_view_settings(Canvas *const canvas, ProtoViewApp *app) {
  204. UNUSED(app);
  205. canvas_set_font(canvas, FontPrimary);
  206. if (app->current_view == ViewFrequencySettings)
  207. canvas_draw_str_with_border(canvas,1,10,"Frequency",ColorWhite,ColorBlack);
  208. else
  209. canvas_draw_str(canvas,1,10,"Frequency");
  210. if (app->current_view == ViewModulationSettings)
  211. canvas_draw_str_with_border(canvas,70,10,"Modulation",ColorWhite,ColorBlack);
  212. else
  213. canvas_draw_str(canvas,70,10,"Modulation");
  214. canvas_set_font(canvas, FontSecondary);
  215. canvas_draw_str(canvas,10,61,"Use up and down to modify");
  216. /* Show frequency. We can use big numbers font since it's just a number. */
  217. if (app->current_view == ViewFrequencySettings) {
  218. char buf[16];
  219. snprintf(buf,sizeof(buf),"%.2f",(double)app->frequency/1000000);
  220. canvas_set_font(canvas, FontBigNumbers);
  221. canvas_draw_str(canvas, 30, 40, buf);
  222. } else if (app->current_view == ViewModulationSettings) {
  223. int current = app->modulation;
  224. canvas_set_font(canvas, FontPrimary);
  225. canvas_draw_str(canvas, 33, 39, ProtoViewModulations[current].name);
  226. }
  227. }
  228. /* The callback actually just passes the control to the actual active
  229. * view callback, after setting up basic stuff like cleaning the screen
  230. * and setting color to black. */
  231. static void render_callback(Canvas *const canvas, void *ctx) {
  232. ProtoViewApp *app = ctx;
  233. /* Clear screen. */
  234. canvas_set_color(canvas, ColorWhite);
  235. canvas_draw_box(canvas, 0, 0, 127, 63);
  236. canvas_set_color(canvas, ColorBlack);
  237. canvas_set_font(canvas, FontPrimary);
  238. /* Call who is in charge right now. */
  239. switch(app->current_view) {
  240. case ViewRawPulses: render_view_raw_pulses(canvas,app); break;
  241. case ViewFrequencySettings:
  242. case ViewModulationSettings:
  243. render_view_settings(canvas,app); break;
  244. case ViewLast: furi_crash(TAG " ViewLast selected"); break;
  245. }
  246. }
  247. /* Here all we do is putting the events into the queue that will be handled
  248. * in the while() loop of the app entry point function. */
  249. static void input_callback(InputEvent* input_event, void* ctx)
  250. {
  251. ProtoViewApp *app = ctx;
  252. if (input_event->type == InputTypePress) {
  253. furi_message_queue_put(app->event_queue,input_event,FuriWaitForever);
  254. FURI_LOG_E(TAG, "INPUT CALLBACK %d", (int)input_event->key);
  255. }
  256. }
  257. /* Allocate the application state and initialize a number of stuff.
  258. * This is called in the entry point to create the application state. */
  259. ProtoViewApp* protoview_app_alloc() {
  260. ProtoViewApp *app = malloc(sizeof(ProtoViewApp));
  261. // Init shared data structures
  262. RawSamples = raw_samples_alloc();
  263. DetectedSamples = raw_samples_alloc();
  264. //init setting
  265. app->setting = subghz_setting_alloc();
  266. subghz_setting_load(app->setting, EXT_PATH("protoview/settings.txt"));
  267. // GUI
  268. app->gui = furi_record_open(RECORD_GUI);
  269. app->view_port = view_port_alloc();
  270. view_port_draw_callback_set(app->view_port, render_callback, app);
  271. view_port_input_callback_set(app->view_port, input_callback, app);
  272. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  273. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  274. app->current_view = ViewRawPulses;
  275. // Signal found and visualization defaults
  276. app->signal_bestlen = 0;
  277. app->us_scale = 100;
  278. //init Worker & Protocol
  279. app->txrx = malloc(sizeof(ProtoViewTxRx));
  280. /* Setup rx worker and environment. */
  281. app->txrx->worker = subghz_worker_alloc();
  282. app->txrx->environment = subghz_environment_alloc();
  283. subghz_environment_set_protocol_registry(
  284. app->txrx->environment, (void*)&protoview_protocol_registry);
  285. app->txrx->receiver = subghz_receiver_alloc_init(app->txrx->environment);
  286. subghz_receiver_set_filter(app->txrx->receiver, SubGhzProtocolFlag_Decodable);
  287. subghz_worker_set_overrun_callback(
  288. app->txrx->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset);
  289. subghz_worker_set_pair_callback(
  290. app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode);
  291. subghz_worker_set_context(app->txrx->worker, app->txrx->receiver);
  292. app->frequency = subghz_setting_get_default_frequency(app->setting);
  293. app->modulation = 0; /* Defaults to ProtoViewModulations[0]. */
  294. furi_hal_power_suppress_charge_enter();
  295. app->running = 1;
  296. return app;
  297. }
  298. /* Free what the application allocated. It is not clear to me if the
  299. * Flipper OS, once the application exits, will be able to reclaim space
  300. * even if we forget to free something here. */
  301. void protoview_app_free(ProtoViewApp *app) {
  302. furi_assert(app);
  303. // Put CC1101 on sleep.
  304. radio_sleep(app);
  305. // View related.
  306. view_port_enabled_set(app->view_port, false);
  307. gui_remove_view_port(app->gui, app->view_port);
  308. view_port_free(app->view_port);
  309. furi_record_close(RECORD_GUI);
  310. furi_message_queue_free(app->event_queue);
  311. app->gui = NULL;
  312. // Frequency setting.
  313. subghz_setting_free(app->setting);
  314. // Worker stuff.
  315. subghz_receiver_free(app->txrx->receiver);
  316. subghz_environment_free(app->txrx->environment);
  317. subghz_worker_free(app->txrx->worker);
  318. free(app->txrx);
  319. // Raw samples buffers.
  320. raw_samples_free(RawSamples);
  321. raw_samples_free(DetectedSamples);
  322. furi_hal_power_suppress_charge_exit();
  323. free(app);
  324. }
  325. /* Called 10 times per second. Do signal processing here. Data we process here
  326. * will be later displayed by the render callback. The side effect of this
  327. * function is to scan for signals and set DetectedSamples. */
  328. static void timer_callback(void *ctx) {
  329. ProtoViewApp *app = ctx;
  330. scan_for_signal(app);
  331. }
  332. /* Handle input for the raw pulses view. */
  333. void process_input_raw_pulses(ProtoViewApp *app, InputEvent input) {
  334. if (input.key == InputKeyOk) {
  335. /* Reset the current sample to capture the next. */
  336. app->signal_bestlen = 0;
  337. raw_samples_reset(DetectedSamples);
  338. raw_samples_reset(RawSamples);
  339. } else if (input.key == InputKeyDown) {
  340. /* Rescaling. The set becomes finer under 50us per pixel. */
  341. uint32_t scale_step = app->us_scale >= 50 ? 50 : 10;
  342. if (app->us_scale < 500) app->us_scale += scale_step;
  343. } else if (input.key == InputKeyUp) {
  344. uint32_t scale_step = app->us_scale > 50 ? 50 : 10;
  345. if (app->us_scale > 10) app->us_scale -= scale_step;
  346. }
  347. }
  348. /* Handle input for the settings view. */
  349. void process_input_settings(ProtoViewApp *app, InputEvent input) {
  350. /* Here we handle only up and down. Avoid any work if the user
  351. * pressed something else. */
  352. if (input.key != InputKeyDown && input.key != InputKeyUp) return;
  353. if (app->current_view == ViewFrequencySettings) {
  354. size_t curidx = 0, i;
  355. size_t count = subghz_setting_get_frequency_count(app->setting);
  356. /* Scan the list of frequencies to check for the index of the
  357. * currently set frequency. */
  358. for(i = 0; i < count; i++) {
  359. uint32_t freq = subghz_setting_get_frequency(app->setting,i);
  360. if (freq == app->frequency) {
  361. curidx = i;
  362. break;
  363. }
  364. }
  365. if (i == count) return; /* Should never happen. */
  366. if (input.key == InputKeyUp) {
  367. curidx = (curidx+1) % count;
  368. } else if (input.key == InputKeyDown) {
  369. curidx = curidx == 0 ? count-1 : curidx-1;
  370. }
  371. app->frequency = subghz_setting_get_frequency(app->setting,curidx);
  372. } else if (app->current_view == ViewModulationSettings) {
  373. uint32_t count = 0;
  374. uint32_t modid = app->modulation;
  375. while(ProtoViewModulations[count].name != NULL) count++;
  376. if (input.key == InputKeyUp) {
  377. modid = (modid+1) % count;
  378. } else if (input.key == InputKeyDown) {
  379. modid = modid == 0 ? count-1 : modid-1;
  380. }
  381. app->modulation = modid;
  382. }
  383. /* Apply changes. */
  384. FURI_LOG_E(TAG, "Setting view, setting frequency/modulation to %lu %s", app->frequency, ProtoViewModulations[app->modulation].name);
  385. radio_rx_end(app);
  386. radio_begin(app);
  387. radio_rx(app);
  388. }
  389. int32_t protoview_app_entry(void* p) {
  390. UNUSED(p);
  391. ProtoViewApp *app = protoview_app_alloc();
  392. /* Create a timer. We do data analysis in the callback. */
  393. FuriTimer *timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app);
  394. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
  395. /* Start listening to signals immediately. */
  396. radio_begin(app);
  397. radio_rx(app);
  398. /* This is the main event loop: here we get the events that are pushed
  399. * in the queue by input_callback(), and process them one after the
  400. * other. The timeout is 100 milliseconds, so if not input is received
  401. * before such time, we exit the queue_get() function and call
  402. * view_port_update() in order to refresh our screen content. */
  403. InputEvent input;
  404. while(app->running) {
  405. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  406. if (qstat == FuriStatusOk) {
  407. FURI_LOG_E(TAG, "Main Loop - Input: %u", input.key);
  408. /* Handle navigation here. Then handle view-specific inputs
  409. * in the view specific handling function. */
  410. if (input.key == InputKeyBack) {
  411. /* Exit the app. */
  412. app->running = 0;
  413. } else if (input.key == InputKeyRight) {
  414. /* Go to the next view. */
  415. app->current_view++;
  416. if (app->current_view == ViewLast) app->current_view = 0;
  417. } else if (input.key == InputKeyLeft) {
  418. /* Go to the previous view. */
  419. if (app->current_view == 0)
  420. app->current_view = ViewLast-1;
  421. else
  422. app->current_view--;
  423. } else {
  424. switch(app->current_view) {
  425. case ViewRawPulses:
  426. process_input_raw_pulses(app,input);
  427. break;
  428. case ViewFrequencySettings:
  429. case ViewModulationSettings:
  430. process_input_settings(app,input);
  431. break;
  432. case ViewLast: furi_crash(TAG " ViewLast selected"); break;
  433. }
  434. }
  435. } else {
  436. static int c = 0;
  437. c++;
  438. if (!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  439. }
  440. view_port_update(app->view_port);
  441. }
  442. /* App no longer running. Shut down and free. */
  443. if (app->txrx->txrx_state == TxRxStateRx) {
  444. FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting.");
  445. radio_rx_end(app);
  446. radio_sleep(app);
  447. }
  448. furi_timer_free(timer);
  449. protoview_app_free(app);
  450. return 0;
  451. }