app.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. #define FREQ 433920000
  10. RawSamplesBuffer *RawSamples, *DetectedSamples;
  11. extern const SubGhzProtocolRegistry protoview_protocol_registry;
  12. /* Render the received signal.
  13. *
  14. * The screen of the flipper is 128 x 64. Even using 4 pixels per line
  15. * (where low level signal is one pixel high, high level is 4 pixels
  16. * high) and 4 pixels of spacing between the different lines, we can
  17. * plot comfortably 8 lines.
  18. *
  19. * The 'idx' argument is the first sample to render in the circular
  20. * buffer. */
  21. void render_signal(ProtoViewApp *app, Canvas *const canvas, RawSamplesBuffer *buf, uint32_t idx) {
  22. canvas_set_color(canvas, ColorBlack);
  23. int rows = 8;
  24. uint32_t time_per_pixel = app->us_scale;
  25. bool level = 0;
  26. uint32_t dur = 0;
  27. for (int row = 0; row < rows ; row++) {
  28. for (int x = 0; x < 128; x++) {
  29. int y = 3 + row*8;
  30. if (dur < time_per_pixel/2) {
  31. /* Get more data. */
  32. raw_samples_get(buf, idx++, &level, &dur);
  33. }
  34. canvas_draw_line(canvas, x,y,x,y-(level*3));
  35. /* Remove from the current level duration the time we
  36. * just plot. */
  37. if (dur > time_per_pixel)
  38. dur -= time_per_pixel;
  39. else
  40. dur = 0;
  41. }
  42. }
  43. }
  44. /* Return the time difference between a and b, always >= 0 since
  45. * the absolute value is returned. */
  46. uint32_t duration_delta(uint32_t a, uint32_t b) {
  47. return a > b ? a - b : b -a;
  48. }
  49. /* This function starts scanning samples at offset idx looking for the
  50. * longest run of pulses, either high or low, that are among 10%
  51. * of each other, for a maximum of three classes. The classes are
  52. * counted separtely for high and low signals (RF on / off) because
  53. * many devices tend to have different pulse lenghts depending on
  54. * the level of the pulse.
  55. *
  56. * For instance Oregon2 sensors, in the case of protocol 2.1 will send
  57. * pulses of ~400us (RF on) VS ~580us (RF off). */
  58. #define SEARCH_CLASSES 3
  59. uint32_t search_coherent_signal(RawSamplesBuffer *s, uint32_t idx) {
  60. struct {
  61. uint32_t dur[2]; /* dur[0] = low, dur[1] = high */
  62. uint32_t count[2]; /* Associated observed frequency. */
  63. } classes[SEARCH_CLASSES];
  64. memset(classes,0,sizeof(classes));
  65. uint32_t minlen = 40, maxlen = 4000; /* Depends on data rate, here we
  66. allow for high and low. */
  67. uint32_t len = 0; /* Observed len of coherent samples. */
  68. s->short_pulse_dur = 0;
  69. for (uint32_t j = idx; j < idx+100; j++) {
  70. bool level;
  71. uint32_t dur;
  72. raw_samples_get(s, j, &level, &dur);
  73. if (dur < minlen || dur > maxlen) break; /* return. */
  74. /* Let's see if it matches a class we already have or if we
  75. * can populate a new (yet empty) class. */
  76. uint32_t k;
  77. for (k = 0; k < SEARCH_CLASSES; k++) {
  78. if (classes[k].count[level] == 0) {
  79. classes[k].dur[level] = dur;
  80. classes[k].count[level] = 1;
  81. break; /* Sample accepted. */
  82. } else {
  83. uint32_t classavg = classes[k].dur[level];
  84. uint32_t count = classes[k].count[level];
  85. uint32_t delta = duration_delta(dur,classavg);
  86. if (delta < classavg/10) {
  87. /* It is useful to compute the average of the class
  88. * we are observing. We know how many samples we got so
  89. * far, so we can recompute the average easily.
  90. * By always having a better estimate of the pulse len
  91. * we can avoid missing next samples in case the first
  92. * observed samples are too off. */
  93. classavg = ((classavg * count) + dur) / (count+1);
  94. classes[k].dur[level] = classavg;
  95. classes[k].count[level]++;
  96. break; /* Sample accepted. */
  97. }
  98. }
  99. }
  100. if (k == SEARCH_CLASSES) break; /* No match, return. */
  101. /* If we are here, we accepted this sample. Try with the next
  102. * one. */
  103. len++;
  104. }
  105. /* Update the buffer setting the shortest pulse we found
  106. * among the three classes. This will be used when scaling
  107. * for visualization. */
  108. for (int j = 0; j < SEARCH_CLASSES; j++) {
  109. for (int level = 0; level < 2; level++) {
  110. if (s->short_pulse_dur == 0 ||
  111. s->short_pulse_dur > classes[j].dur[level])
  112. {
  113. s->short_pulse_dur = classes[j].dur[level];
  114. }
  115. }
  116. }
  117. return len;
  118. }
  119. /* Search the buffer with the stored signal (last N samples received)
  120. * in order to find a coherent signal. If a signal that does not appear to
  121. * be just noise is found, it is set in DetectedSamples global signal
  122. * buffer, that is what is rendered on the screen. */
  123. void scan_for_signal(ProtoViewApp *app) {
  124. /* We need to work on a copy: the RawSamples buffer is populated
  125. * by the background thread receiving data. */
  126. RawSamplesBuffer *copy = raw_samples_alloc();
  127. raw_samples_copy(copy,RawSamples);
  128. /* Try to seek on data that looks to have a regular high low high low
  129. * pattern. */
  130. uint32_t minlen = 13; /* Min run of coherent samples. Up to
  131. 12 samples it's very easy to mistake
  132. noise for signal. */
  133. for (uint32_t i = 0; i < copy->total-1; i++) {
  134. uint32_t thislen = search_coherent_signal(copy,i);
  135. if (thislen > minlen && thislen > app->signal_bestlen) {
  136. app->signal_bestlen = thislen;
  137. raw_samples_copy(DetectedSamples,copy);
  138. DetectedSamples->idx = (DetectedSamples->idx+i)%
  139. DetectedSamples->total;
  140. FURI_LOG_E(TAG, "Displayed sample updated (%d samples)",
  141. (int)thislen);
  142. }
  143. }
  144. raw_samples_free(copy);
  145. }
  146. /* Draw some white text with a black border. */
  147. void canvas_draw_str_with_border(Canvas* canvas, uint8_t x, uint8_t y, const char* str)
  148. {
  149. struct {
  150. uint8_t x; uint8_t y;
  151. } dir[8] = {
  152. {-1,-1},
  153. {0,-1},
  154. {1,-1},
  155. {1,0},
  156. {1,1},
  157. {0,1},
  158. {-1,1},
  159. {-1,0}
  160. };
  161. /* Rotate in all the directions writing the same string in black
  162. * to create a border, then write the actaul string in white in the
  163. * middle. */
  164. canvas_set_color(canvas, ColorBlack);
  165. canvas_set_font(canvas, FontSecondary);
  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. }
  171. static void render_callback(Canvas *const canvas, void *ctx) {
  172. ProtoViewApp *app = ctx;
  173. /* Clear screen. */
  174. canvas_set_color(canvas, ColorWhite);
  175. canvas_draw_box(canvas, 0, 0, 127, 63);
  176. /* Show signal. */
  177. render_signal(app, canvas, DetectedSamples, 0);
  178. /* Show signal information. */
  179. char buf[64];
  180. snprintf(buf,sizeof(buf),"%luus", (unsigned long)DetectedSamples->short_pulse_dur);
  181. canvas_draw_str_with_border(canvas, 100, 63, buf);
  182. }
  183. /* Here all we do is putting the events into the queue that will be handled
  184. * in the while() loop of the app entry point function. */
  185. static void input_callback(InputEvent* input_event, void* ctx)
  186. {
  187. ProtoViewApp *app = ctx;
  188. if (input_event->type == InputTypePress) {
  189. furi_message_queue_put(app->event_queue,input_event,FuriWaitForever);
  190. FURI_LOG_E(TAG, "INPUT CALLBACK %d", (int)input_event->key);
  191. }
  192. }
  193. ProtoViewApp* protoview_app_alloc() {
  194. ProtoViewApp *app = malloc(sizeof(ProtoViewApp));
  195. // Init shared data structures
  196. RawSamples = raw_samples_alloc();
  197. DetectedSamples = raw_samples_alloc();
  198. //init setting
  199. app->setting = subghz_setting_alloc();
  200. subghz_setting_load(app->setting, EXT_PATH("protoview/settings.txt"));
  201. // GUI
  202. app->gui = furi_record_open(RECORD_GUI);
  203. app->view_port = view_port_alloc();
  204. view_port_draw_callback_set(app->view_port, render_callback, app);
  205. view_port_input_callback_set(app->view_port, input_callback, app);
  206. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  207. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  208. // Signal found and visualization defaults
  209. app->signal_bestlen = 0;
  210. app->us_scale = 100;
  211. //init Worker & Protocol
  212. app->txrx = malloc(sizeof(ProtoViewTxRx));
  213. app->txrx->preset = malloc(sizeof(SubGhzRadioPreset));
  214. app->txrx->preset->name = furi_string_alloc();
  215. /* Setup rx worker and environment. */
  216. app->txrx->worker = subghz_worker_alloc();
  217. app->txrx->environment = subghz_environment_alloc();
  218. subghz_environment_set_protocol_registry(
  219. app->txrx->environment, (void*)&protoview_protocol_registry);
  220. app->txrx->receiver = subghz_receiver_alloc_init(app->txrx->environment);
  221. subghz_receiver_set_filter(app->txrx->receiver, SubGhzProtocolFlag_Decodable);
  222. subghz_worker_set_overrun_callback(
  223. app->txrx->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset);
  224. subghz_worker_set_pair_callback(
  225. app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode);
  226. subghz_worker_set_context(app->txrx->worker, app->txrx->receiver);
  227. furi_hal_power_suppress_charge_enter();
  228. app->running = 1;
  229. return app;
  230. }
  231. void protoview_app_free(ProtoViewApp *app) {
  232. furi_assert(app);
  233. //CC1101 off
  234. radio_sleep(app);
  235. // View
  236. view_port_enabled_set(app->view_port, false);
  237. gui_remove_view_port(app->gui, app->view_port);
  238. view_port_free(app->view_port);
  239. furi_record_close(RECORD_GUI);
  240. furi_message_queue_free(app->event_queue);
  241. app->gui = NULL;
  242. //setting
  243. subghz_setting_free(app->setting);
  244. //Worker
  245. subghz_receiver_free(app->txrx->receiver);
  246. subghz_environment_free(app->txrx->environment);
  247. subghz_worker_free(app->txrx->worker);
  248. furi_string_free(app->txrx->preset->name);
  249. free(app->txrx->preset);
  250. free(app->txrx);
  251. furi_hal_power_suppress_charge_exit();
  252. raw_samples_free(RawSamples);
  253. raw_samples_free(DetectedSamples);
  254. free(app);
  255. }
  256. /* Called 10 times per second. Do signal processing here. Data we process here
  257. * will be later displayed by the render callback. The side effect of this
  258. * function is to scan for signals and set DetectedSamples. */
  259. static void timer_callback(void *ctx) {
  260. ProtoViewApp *app = ctx;
  261. scan_for_signal(app);
  262. }
  263. int32_t protoview_app_entry(void* p) {
  264. UNUSED(p);
  265. ProtoViewApp *app = protoview_app_alloc();
  266. /* Create a timer. We do data analysis in the callback. */
  267. FuriTimer *timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app);
  268. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  269. radio_begin(app);
  270. radio_rx(app, FREQ);
  271. InputEvent input;
  272. while(app->running) {
  273. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  274. if (qstat == FuriStatusOk) {
  275. uint32_t scale_step = app->us_scale > 50 ? 50 : 10;
  276. if (input.key == InputKeyBack) {
  277. app->running = 0;
  278. } else if (input.key == InputKeyOk) {
  279. app->signal_bestlen = 0;
  280. raw_samples_reset(DetectedSamples);
  281. raw_samples_reset(RawSamples);
  282. } else if (input.key == InputKeyDown) {
  283. if (app->us_scale < 500) app->us_scale += scale_step;
  284. } else if (input.key == InputKeyUp) {
  285. if (app->us_scale > 10) app->us_scale -= scale_step;
  286. }
  287. FURI_LOG_E(TAG, "Main Loop - Input: %u", input.key);
  288. } else {
  289. static int c = 0;
  290. c++;
  291. if (!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  292. }
  293. view_port_update(app->view_port);
  294. }
  295. if (app->txrx->txrx_state == TxRxStateRx) {
  296. FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting.");
  297. radio_rx_end(app);
  298. radio_sleep(app);
  299. }
  300. furi_timer_free(timer);
  301. protoview_app_free(app);
  302. return 0;
  303. }