app.c 16 KB

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