app.c 20 KB

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