app.c 11 KB

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