app.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 (classes[j].dur[level] == 0) continue;
  111. if (classes[j].count[level] < 3) continue;
  112. if (s->short_pulse_dur == 0 ||
  113. s->short_pulse_dur > classes[j].dur[level])
  114. {
  115. s->short_pulse_dur = classes[j].dur[level];
  116. }
  117. }
  118. }
  119. return len;
  120. }
  121. /* Search the buffer with the stored signal (last N samples received)
  122. * in order to find a coherent signal. If a signal that does not appear to
  123. * be just noise is found, it is set in DetectedSamples global signal
  124. * buffer, that is what is rendered on the screen. */
  125. void scan_for_signal(ProtoViewApp *app) {
  126. /* We need to work on a copy: the RawSamples buffer is populated
  127. * by the background thread receiving data. */
  128. RawSamplesBuffer *copy = raw_samples_alloc();
  129. raw_samples_copy(copy,RawSamples);
  130. /* Try to seek on data that looks to have a regular high low high low
  131. * pattern. */
  132. uint32_t minlen = 13; /* Min run of coherent samples. Up to
  133. 12 samples it's very easy to mistake
  134. noise for signal. */
  135. for (uint32_t i = 0; i < copy->total-1; i++) {
  136. uint32_t thislen = search_coherent_signal(copy,i);
  137. if (thislen > minlen && thislen > app->signal_bestlen) {
  138. app->signal_bestlen = thislen;
  139. raw_samples_copy(DetectedSamples,copy);
  140. DetectedSamples->idx = (DetectedSamples->idx+i)%
  141. DetectedSamples->total;
  142. FURI_LOG_E(TAG, "Displayed sample updated (%d samples)",
  143. (int)thislen);
  144. }
  145. }
  146. raw_samples_free(copy);
  147. }
  148. /* Draw some white text with a black border. */
  149. void canvas_draw_str_with_border(Canvas* canvas, uint8_t x, uint8_t y, const char* str)
  150. {
  151. struct {
  152. uint8_t x; uint8_t y;
  153. } dir[8] = {
  154. {-1,-1},
  155. {0,-1},
  156. {1,-1},
  157. {1,0},
  158. {1,1},
  159. {0,1},
  160. {-1,1},
  161. {-1,0}
  162. };
  163. /* Rotate in all the directions writing the same string in black
  164. * to create a border, then write the actaul string in white in the
  165. * middle. */
  166. canvas_set_color(canvas, ColorBlack);
  167. canvas_set_font(canvas, FontSecondary);
  168. for (int j = 0; j < 8; j++)
  169. canvas_draw_str(canvas,x+dir[j].x,y+dir[j].y,str);
  170. canvas_set_color(canvas, ColorWhite);
  171. canvas_draw_str(canvas,x,y,str);
  172. }
  173. static void render_callback(Canvas *const canvas, void *ctx) {
  174. ProtoViewApp *app = ctx;
  175. /* Clear screen. */
  176. canvas_set_color(canvas, ColorWhite);
  177. canvas_draw_box(canvas, 0, 0, 127, 63);
  178. /* Show signal. */
  179. render_signal(app, canvas, DetectedSamples, 0);
  180. /* Show signal information. */
  181. char buf[64];
  182. snprintf(buf,sizeof(buf),"%luus", (unsigned long)DetectedSamples->short_pulse_dur);
  183. canvas_draw_str_with_border(canvas, 100, 63, buf);
  184. }
  185. /* Here all we do is putting the events into the queue that will be handled
  186. * in the while() loop of the app entry point function. */
  187. static void input_callback(InputEvent* input_event, void* ctx)
  188. {
  189. ProtoViewApp *app = ctx;
  190. if (input_event->type == InputTypePress) {
  191. furi_message_queue_put(app->event_queue,input_event,FuriWaitForever);
  192. FURI_LOG_E(TAG, "INPUT CALLBACK %d", (int)input_event->key);
  193. }
  194. }
  195. ProtoViewApp* protoview_app_alloc() {
  196. ProtoViewApp *app = malloc(sizeof(ProtoViewApp));
  197. // Init shared data structures
  198. RawSamples = raw_samples_alloc();
  199. DetectedSamples = raw_samples_alloc();
  200. //init setting
  201. app->setting = subghz_setting_alloc();
  202. subghz_setting_load(app->setting, EXT_PATH("protoview/settings.txt"));
  203. // GUI
  204. app->gui = furi_record_open(RECORD_GUI);
  205. app->view_port = view_port_alloc();
  206. view_port_draw_callback_set(app->view_port, render_callback, app);
  207. view_port_input_callback_set(app->view_port, input_callback, app);
  208. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  209. app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
  210. // Signal found and visualization defaults
  211. app->signal_bestlen = 0;
  212. app->us_scale = 100;
  213. //init Worker & Protocol
  214. app->txrx = malloc(sizeof(ProtoViewTxRx));
  215. app->txrx->preset = malloc(sizeof(SubGhzRadioPreset));
  216. app->txrx->preset->name = furi_string_alloc();
  217. /* Setup rx worker and environment. */
  218. app->txrx->worker = subghz_worker_alloc();
  219. app->txrx->environment = subghz_environment_alloc();
  220. subghz_environment_set_protocol_registry(
  221. app->txrx->environment, (void*)&protoview_protocol_registry);
  222. app->txrx->receiver = subghz_receiver_alloc_init(app->txrx->environment);
  223. subghz_receiver_set_filter(app->txrx->receiver, SubGhzProtocolFlag_Decodable);
  224. subghz_worker_set_overrun_callback(
  225. app->txrx->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset);
  226. subghz_worker_set_pair_callback(
  227. app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode);
  228. subghz_worker_set_context(app->txrx->worker, app->txrx->receiver);
  229. furi_hal_power_suppress_charge_enter();
  230. app->running = 1;
  231. return app;
  232. }
  233. void protoview_app_free(ProtoViewApp *app) {
  234. furi_assert(app);
  235. //CC1101 off
  236. radio_sleep(app);
  237. // View
  238. view_port_enabled_set(app->view_port, false);
  239. gui_remove_view_port(app->gui, app->view_port);
  240. view_port_free(app->view_port);
  241. furi_record_close(RECORD_GUI);
  242. furi_message_queue_free(app->event_queue);
  243. app->gui = NULL;
  244. //setting
  245. subghz_setting_free(app->setting);
  246. //Worker
  247. subghz_receiver_free(app->txrx->receiver);
  248. subghz_environment_free(app->txrx->environment);
  249. subghz_worker_free(app->txrx->worker);
  250. furi_string_free(app->txrx->preset->name);
  251. free(app->txrx->preset);
  252. free(app->txrx);
  253. furi_hal_power_suppress_charge_exit();
  254. raw_samples_free(RawSamples);
  255. raw_samples_free(DetectedSamples);
  256. free(app);
  257. }
  258. /* Called 10 times per second. Do signal processing here. Data we process here
  259. * will be later displayed by the render callback. The side effect of this
  260. * function is to scan for signals and set DetectedSamples. */
  261. static void timer_callback(void *ctx) {
  262. ProtoViewApp *app = ctx;
  263. scan_for_signal(app);
  264. }
  265. int32_t protoview_app_entry(void* p) {
  266. UNUSED(p);
  267. ProtoViewApp *app = protoview_app_alloc();
  268. /* Create a timer. We do data analysis in the callback. */
  269. FuriTimer *timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app);
  270. furi_timer_start(timer, furi_kernel_get_tick_frequency() / 10);
  271. radio_begin(app);
  272. radio_rx(app, FREQ);
  273. InputEvent input;
  274. while(app->running) {
  275. FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
  276. if (qstat == FuriStatusOk) {
  277. if (input.key == InputKeyBack) {
  278. app->running = 0;
  279. } else if (input.key == InputKeyOk) {
  280. app->signal_bestlen = 0;
  281. raw_samples_reset(DetectedSamples);
  282. raw_samples_reset(RawSamples);
  283. } else if (input.key == InputKeyDown) {
  284. uint32_t scale_step = app->us_scale >= 50 ? 50 : 10;
  285. if (app->us_scale < 500) app->us_scale += scale_step;
  286. } else if (input.key == InputKeyUp) {
  287. uint32_t scale_step = app->us_scale > 50 ? 50 : 10;
  288. if (app->us_scale > 10) app->us_scale -= scale_step;
  289. }
  290. FURI_LOG_E(TAG, "Main Loop - Input: %u", input.key);
  291. } else {
  292. static int c = 0;
  293. c++;
  294. if (!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
  295. }
  296. view_port_update(app->view_port);
  297. }
  298. if (app->txrx->txrx_state == TxRxStateRx) {
  299. FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting.");
  300. radio_rx_end(app);
  301. radio_sleep(app);
  302. }
  303. furi_timer_free(timer);
  304. protoview_app_free(app);
  305. return 0;
  306. }