app.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. uint32_t i = 0;
  148. while (i < copy->total-1) {
  149. uint32_t thislen = search_coherent_signal(copy,i);
  150. if (thislen > minlen && thislen > app->signal_bestlen) {
  151. app->signal_bestlen = thislen;
  152. raw_samples_copy(DetectedSamples,copy);
  153. DetectedSamples->idx = (DetectedSamples->idx+i)%
  154. DetectedSamples->total;
  155. FURI_LOG_E(TAG, "Displayed sample updated (%d samples)",
  156. (int)thislen);
  157. }
  158. i += thislen ? thislen : 1;
  159. }
  160. raw_samples_free(copy);
  161. }
  162. /* Draw some text with a border. If the outside color is black and the inside
  163. * color is white, it just writes the border of the text, but the function can
  164. * also be used to write a bold variation of the font setting both the
  165. * colors to black, or alternatively to write a black text with a white
  166. * border so that it is visible if there are black stuff on the background. */
  167. void canvas_draw_str_with_border(Canvas* canvas, uint8_t x, uint8_t y, const char* str, Color text_color, Color border_color)
  168. {
  169. struct {
  170. uint8_t x; uint8_t y;
  171. } dir[8] = {
  172. {-1,-1},
  173. {0,-1},
  174. {1,-1},
  175. {1,0},
  176. {1,1},
  177. {0,1},
  178. {-1,1},
  179. {-1,0}
  180. };
  181. /* Rotate in all the directions writing the same string to create a
  182. * border, then write the actual string in the other color in the
  183. * middle. */
  184. canvas_set_color(canvas, border_color);
  185. for (int j = 0; j < 8; j++)
  186. canvas_draw_str(canvas,x+dir[j].x,y+dir[j].y,str);
  187. canvas_set_color(canvas, text_color);
  188. canvas_draw_str(canvas,x,y,str);
  189. canvas_set_color(canvas, ColorBlack);
  190. }
  191. /* Raw pulses rendering. This is our default view. */
  192. void render_view_raw_pulses(Canvas *const canvas, ProtoViewApp *app) {
  193. /* Show signal. */
  194. render_signal(app, canvas, DetectedSamples, 0);
  195. /* Show signal information. */
  196. char buf[64];
  197. snprintf(buf,sizeof(buf),"%luus",
  198. (unsigned long)DetectedSamples->short_pulse_dur);
  199. canvas_set_font(canvas, FontSecondary);
  200. canvas_draw_str_with_border(canvas, 97, 63, buf, ColorWhite, ColorBlack);
  201. }
  202. /* Renders a single view with frequency and modulation setting. However
  203. * this are logically two different views, and only one of the settings
  204. * will be highlighted. */
  205. void render_view_settings(Canvas *const canvas, ProtoViewApp *app) {
  206. UNUSED(app);
  207. canvas_set_font(canvas, FontPrimary);
  208. if (app->current_view == ViewFrequencySettings)
  209. canvas_draw_str_with_border(canvas,1,10,"Frequency",ColorWhite,ColorBlack);
  210. else
  211. canvas_draw_str(canvas,1,10,"Frequency");
  212. if (app->current_view == ViewModulationSettings)
  213. canvas_draw_str_with_border(canvas,70,10,"Modulation",ColorWhite,ColorBlack);
  214. else
  215. canvas_draw_str(canvas,70,10,"Modulation");
  216. canvas_set_font(canvas, FontSecondary);
  217. canvas_draw_str(canvas,10,61,"Use up and down to modify");
  218. /* Show frequency. We can use big numbers font since it's just a number. */
  219. if (app->current_view == ViewFrequencySettings) {
  220. char buf[16];
  221. snprintf(buf,sizeof(buf),"%.2f",(double)app->frequency/1000000);
  222. canvas_set_font(canvas, FontBigNumbers);
  223. canvas_draw_str(canvas, 30, 40, buf);
  224. } else if (app->current_view == ViewModulationSettings) {
  225. int current = app->modulation;
  226. canvas_set_font(canvas, FontPrimary);
  227. canvas_draw_str(canvas, 33, 39, ProtoViewModulations[current].name);
  228. }
  229. }
  230. /* The callback actually just passes the control to the actual active
  231. * view callback, after setting up basic stuff like cleaning the screen
  232. * and setting color to black. */
  233. static void render_callback(Canvas *const canvas, void *ctx) {
  234. ProtoViewApp *app = ctx;
  235. /* Clear screen. */
  236. canvas_set_color(canvas, ColorWhite);
  237. canvas_draw_box(canvas, 0, 0, 127, 63);
  238. canvas_set_color(canvas, ColorBlack);
  239. canvas_set_font(canvas, FontPrimary);
  240. /* Call who is in charge right now. */
  241. switch(app->current_view) {
  242. case ViewRawPulses: render_view_raw_pulses(canvas,app); break;
  243. case ViewFrequencySettings:
  244. case ViewModulationSettings:
  245. render_view_settings(canvas,app); break;
  246. case ViewLast: furi_crash(TAG " ViewLast selected"); break;
  247. }
  248. }
  249. /* Here all we do is putting the events into the queue that will be handled
  250. * in the while() loop of the app entry point function. */
  251. static void input_callback(InputEvent* input_event, void* ctx)
  252. {
  253. ProtoViewApp *app = ctx;
  254. if (input_event->type == InputTypePress) {
  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. }
  259. /* Allocate the application state and initialize a number of stuff.
  260. * This is called in the entry point to create the application state. */
  261. ProtoViewApp* protoview_app_alloc() {
  262. ProtoViewApp *app = malloc(sizeof(ProtoViewApp));
  263. // Init shared data structures
  264. RawSamples = raw_samples_alloc();
  265. DetectedSamples = raw_samples_alloc();
  266. //init setting
  267. app->setting = subghz_setting_alloc();
  268. subghz_setting_load(app->setting, EXT_PATH("protoview/settings.txt"));
  269. // GUI
  270. app->gui = furi_record_open(RECORD_GUI);
  271. app->view_port = view_port_alloc();
  272. view_port_draw_callback_set(app->view_port, render_callback, app);
  273. view_port_input_callback_set(app->view_port, input_callback, app);
  274. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  275. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  276. app->current_view = ViewRawPulses;
  277. // Signal found and visualization defaults
  278. app->signal_bestlen = 0;
  279. app->us_scale = 100;
  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.key == InputKeyOk) {
  337. /* Reset the current sample to capture the next. */
  338. app->signal_bestlen = 0;
  339. raw_samples_reset(DetectedSamples);
  340. raw_samples_reset(RawSamples);
  341. } else if (input.key == InputKeyDown) {
  342. /* Rescaling. The set becomes finer under 50us per pixel. */
  343. uint32_t scale_step = app->us_scale >= 50 ? 50 : 10;
  344. if (app->us_scale < 500) app->us_scale += scale_step;
  345. } else if (input.key == InputKeyUp) {
  346. uint32_t scale_step = app->us_scale > 50 ? 50 : 10;
  347. if (app->us_scale > 10) app->us_scale -= scale_step;
  348. }
  349. }
  350. /* Handle input for the settings view. */
  351. void process_input_settings(ProtoViewApp *app, InputEvent input) {
  352. /* Here we handle only up and down. Avoid any work if the user
  353. * pressed something else. */
  354. if (input.key != InputKeyDown && input.key != InputKeyUp) return;
  355. if (app->current_view == ViewFrequencySettings) {
  356. size_t curidx = 0, i;
  357. size_t count = subghz_setting_get_frequency_count(app->setting);
  358. /* Scan the list of frequencies to check for the index of the
  359. * currently set frequency. */
  360. for(i = 0; i < count; i++) {
  361. uint32_t freq = subghz_setting_get_frequency(app->setting,i);
  362. if (freq == app->frequency) {
  363. curidx = i;
  364. break;
  365. }
  366. }
  367. if (i == count) return; /* Should never happen. */
  368. if (input.key == InputKeyUp) {
  369. curidx = (curidx+1) % count;
  370. } else if (input.key == InputKeyDown) {
  371. curidx = curidx == 0 ? count-1 : curidx-1;
  372. }
  373. app->frequency = subghz_setting_get_frequency(app->setting,curidx);
  374. } else if (app->current_view == ViewModulationSettings) {
  375. uint32_t count = 0;
  376. uint32_t modid = app->modulation;
  377. while(ProtoViewModulations[count].name != NULL) count++;
  378. if (input.key == InputKeyUp) {
  379. modid = (modid+1) % count;
  380. } else if (input.key == InputKeyDown) {
  381. modid = modid == 0 ? count-1 : modid-1;
  382. }
  383. app->modulation = modid;
  384. }
  385. /* Apply changes. */
  386. FURI_LOG_E(TAG, "Setting view, setting frequency/modulation to %lu %s", app->frequency, ProtoViewModulations[app->modulation].name);
  387. radio_rx_end(app);
  388. radio_begin(app);
  389. radio_rx(app);
  390. }
  391. int32_t protoview_app_entry(void* p) {
  392. UNUSED(p);
  393. ProtoViewApp *app = protoview_app_alloc();
  394. /* Create a timer. We do data analysis in the callback. */
  395. FuriTimer *timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app);
  396. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
  397. /* Start listening to signals immediately. */
  398. radio_begin(app);
  399. radio_rx(app);
  400. /* This is the main event loop: here we get the events that are pushed
  401. * in the queue by input_callback(), and process them one after the
  402. * other. The timeout is 100 milliseconds, so if not input is received
  403. * before such time, we exit the queue_get() function and call
  404. * view_port_update() in order to refresh our screen content. */
  405. InputEvent input;
  406. while(app->running) {
  407. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  408. if (qstat == FuriStatusOk) {
  409. FURI_LOG_E(TAG, "Main Loop - Input: %u", input.key);
  410. /* Handle navigation here. Then handle view-specific inputs
  411. * in the view specific handling function. */
  412. if (input.key == InputKeyBack) {
  413. /* Exit the app. */
  414. app->running = 0;
  415. } else if (input.key == InputKeyRight) {
  416. /* Go to the next view. */
  417. app->current_view++;
  418. if (app->current_view == ViewLast) app->current_view = 0;
  419. } else if (input.key == InputKeyLeft) {
  420. /* Go to the previous view. */
  421. if (app->current_view == 0)
  422. app->current_view = ViewLast-1;
  423. else
  424. app->current_view--;
  425. } else {
  426. switch(app->current_view) {
  427. case ViewRawPulses:
  428. process_input_raw_pulses(app,input);
  429. break;
  430. case ViewFrequencySettings:
  431. case ViewModulationSettings:
  432. process_input_settings(app,input);
  433. break;
  434. case ViewLast: furi_crash(TAG " ViewLast selected"); break;
  435. }
  436. }
  437. } else {
  438. static int c = 0;
  439. c++;
  440. if (!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  441. }
  442. view_port_update(app->view_port);
  443. }
  444. /* App no longer running. Shut down and free. */
  445. if (app->txrx->txrx_state == TxRxStateRx) {
  446. FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting.");
  447. radio_rx_end(app);
  448. radio_sleep(app);
  449. }
  450. furi_timer_free(timer);
  451. protoview_app_free(app);
  452. return 0;
  453. }