app.c 19 KB

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