zeitraffer.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #include <stdio.h>
  2. #include <furi.h>
  3. #include <gui/gui.h>
  4. #include <input/input.h>
  5. #include <notification/notification_messages.h>
  6. #include <flipper_format/flipper_format.h>
  7. #include "gpio_item.h"
  8. #define CONFIG_FILE_DIRECTORY_PATH "/ext/apps/Misc"
  9. #define CONFIG_FILE_PATH CONFIG_FILE_DIRECTORY_PATH "/zeitraffer.conf"
  10. // Часть кода покрадена из https://github.com/zmactep/flipperzero-hello-world
  11. int32_t Time = 10; // Таймер
  12. int32_t Count = 10; // Количество кадров
  13. int32_t WorkTime = 0; // Счётчик таймера
  14. int32_t WorkCount = 0; // Счётчик кадров
  15. bool InfiniteShot = false; // Бесконечная съёмка
  16. bool Bulb = false; // Режим BULB
  17. int32_t Backlight = 0; // Подсветка: вкл/выкл/авто
  18. int32_t Delay = 3; // Задержка на отскочить
  19. const NotificationSequence sequence_click = {
  20. &message_note_c7,
  21. &message_delay_50,
  22. &message_sound_off,
  23. NULL,
  24. };
  25. typedef enum {
  26. EventTypeTick,
  27. EventTypeInput,
  28. } EventType;
  29. typedef struct {
  30. EventType type;
  31. InputEvent input;
  32. } ZeitrafferEvent;
  33. static void draw_callback(Canvas* canvas, void* ctx) {
  34. UNUSED(ctx);
  35. char temp_str[36];
  36. canvas_clear(canvas);
  37. canvas_set_font(canvas, FontPrimary);
  38. switch (Count) {
  39. case -1:
  40. snprintf(temp_str,sizeof(temp_str),"Set: BULB %li sec",Time);
  41. break;
  42. case 0:
  43. snprintf(temp_str,sizeof(temp_str),"Set: infinite, %li sec",Time);
  44. break;
  45. default:
  46. snprintf(temp_str,sizeof(temp_str),"Set: %li frames, %li sec",Count,Time);
  47. }
  48. canvas_draw_str(canvas, 3, 15, temp_str);
  49. snprintf(temp_str,sizeof(temp_str),"Left: %li frames, %li sec",WorkCount,WorkTime);
  50. canvas_draw_str(canvas, 3, 35, temp_str);
  51. switch (Backlight) {
  52. case 1:
  53. canvas_draw_str(canvas, 3, 55, "Backlight: ON");
  54. break;
  55. case 2:
  56. canvas_draw_str(canvas, 3, 55, "Backlight: OFF");
  57. break;
  58. default:
  59. canvas_draw_str(canvas, 3, 55, "Backlight: AUTO");
  60. }
  61. }
  62. static void input_callback(InputEvent* input_event, void* ctx) {
  63. // Проверяем, что контекст не нулевой
  64. furi_assert(ctx);
  65. FuriMessageQueue* event_queue = ctx;
  66. ZeitrafferEvent event = {.type = EventTypeInput, .input = *input_event};
  67. furi_message_queue_put(event_queue, &event, FuriWaitForever);
  68. }
  69. static void timer_callback(FuriMessageQueue* event_queue) {
  70. // Проверяем, что контекст не нулевой
  71. furi_assert(event_queue);
  72. ZeitrafferEvent event = {.type = EventTypeTick};
  73. furi_message_queue_put(event_queue, &event, 0);
  74. }
  75. int32_t zeitraffer_app(void* p) {
  76. UNUSED(p);
  77. // Текущее событие типа кастомного типа ZeitrafferEvent
  78. ZeitrafferEvent event;
  79. // Очередь событий на 8 элементов размера ZeitrafferEvent
  80. FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(ZeitrafferEvent));
  81. // Создаем новый view port
  82. ViewPort* view_port = view_port_alloc();
  83. // Создаем callback отрисовки, без контекста
  84. view_port_draw_callback_set(view_port, draw_callback, NULL);
  85. // Создаем callback нажатий на клавиши, в качестве контекста передаем
  86. // нашу очередь сообщений, чтоб запихивать в неё эти события
  87. view_port_input_callback_set(view_port, input_callback, event_queue);
  88. // Создаем GUI приложения
  89. Gui* gui = furi_record_open(RECORD_GUI);
  90. // Подключаем view port к GUI в полноэкранном режиме
  91. gui_add_view_port(gui, view_port, GuiLayerFullscreen);
  92. // Конфигурим пины
  93. gpio_item_configure_all_pins(GpioModeOutputPushPull);
  94. // Создаем периодический таймер с коллбэком, куда в качестве
  95. // контекста будет передаваться наша очередь событий
  96. FuriTimer* timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, event_queue);
  97. // Запускаем таймер
  98. //furi_timer_start(timer, 1500);
  99. // Включаем нотификации
  100. NotificationApp* notifications = furi_record_open(RECORD_NOTIFICATION);
  101. Storage* storage = furi_record_open(RECORD_STORAGE);
  102. // Загружаем настройки
  103. FlipperFormat* load = flipper_format_file_alloc(storage);
  104. do {
  105. if(!flipper_format_file_open_existing(load, CONFIG_FILE_PATH)) {notification_message(notifications, &sequence_error); break;}
  106. if(!flipper_format_read_int32(load, "Time", &Time, 1)) {notification_message(notifications, &sequence_error); break;}
  107. if(!flipper_format_read_int32(load, "Count", &Count, 1)) {notification_message(notifications, &sequence_error); break;}
  108. if(!flipper_format_read_int32(load, "Backlight", &Backlight, 1)) {notification_message(notifications, &sequence_error); break;}
  109. if(!flipper_format_read_int32(load, "Delay", &Delay, 1)) {notification_message(notifications, &sequence_error); break;}
  110. notification_message(notifications, &sequence_success);
  111. } while(0);
  112. flipper_format_free(load);
  113. // Бесконечный цикл обработки очереди событий
  114. while(1) {
  115. // Выбираем событие из очереди в переменную event (ждем бесконечно долго, если очередь пуста)
  116. // и проверяем, что у нас получилось это сделать
  117. furi_check(furi_message_queue_get(event_queue, &event, FuriWaitForever) == FuriStatusOk);
  118. // Наше событие — это нажатие кнопки
  119. if(event.type == EventTypeInput) {
  120. if(event.input.type == InputTypeShort) { // Короткие нажатия
  121. if(event.input.key == InputKeyBack) {
  122. if(furi_timer_is_running(timer)) { // Если таймер запущен - нефиг мацать кнопки!
  123. notification_message(notifications, &sequence_error);
  124. }
  125. else {
  126. WorkCount = Count;
  127. WorkTime = 3;
  128. if (Count == 0) {
  129. InfiniteShot = true;
  130. WorkCount = 1;
  131. }
  132. else
  133. InfiniteShot = false;
  134. notification_message(notifications, &sequence_success);
  135. }
  136. }
  137. if(event.input.key == InputKeyRight) {
  138. if(furi_timer_is_running(timer)) {
  139. notification_message(notifications, &sequence_error);
  140. }
  141. else {
  142. Count++;
  143. notification_message(notifications, &sequence_click);
  144. }
  145. }
  146. if(event.input.key == InputKeyLeft) {
  147. if(furi_timer_is_running(timer)) {
  148. notification_message(notifications, &sequence_error);
  149. }
  150. else {
  151. Count--;
  152. notification_message(notifications, &sequence_click);
  153. }
  154. }
  155. if(event.input.key == InputKeyUp) {
  156. if(furi_timer_is_running(timer)) {
  157. notification_message(notifications, &sequence_error);
  158. }
  159. else {
  160. Time++;
  161. notification_message(notifications, &sequence_click);
  162. }
  163. }
  164. if(event.input.key == InputKeyDown) {
  165. if(furi_timer_is_running(timer)) {
  166. notification_message(notifications, &sequence_error);
  167. }
  168. else {
  169. Time--;
  170. notification_message(notifications, &sequence_click);
  171. }
  172. }
  173. if(event.input.key == InputKeyOk) {
  174. if(furi_timer_is_running(timer)) {
  175. notification_message(notifications, &sequence_click);
  176. furi_timer_stop(timer);
  177. }
  178. else {
  179. furi_timer_start(timer, 1000);
  180. if (WorkCount == 0)
  181. WorkCount = Count;
  182. if (WorkTime == 0)
  183. WorkTime = Delay;
  184. if (Count == 0) {
  185. InfiniteShot = true;
  186. WorkCount = 1;
  187. }
  188. else
  189. InfiniteShot = false;
  190. if (Count == -1) {
  191. gpio_item_set_pin(4, true);
  192. gpio_item_set_pin(5, true);
  193. Bulb = true;
  194. WorkCount = 1;
  195. WorkTime = Time;
  196. }
  197. else
  198. Bulb = false;
  199. notification_message(notifications, &sequence_success);
  200. }
  201. }
  202. }
  203. if(event.input.type == InputTypeLong) { // Длинные нажатия
  204. // Если нажата кнопка "назад", то выходим из цикла, а следовательно и из приложения
  205. if(event.input.key == InputKeyBack) {
  206. if(furi_timer_is_running(timer)) { // А если работает таймер - не выходим :D
  207. notification_message(notifications, &sequence_error);
  208. }
  209. else {
  210. notification_message(notifications, &sequence_click);
  211. gpio_item_set_all_pins(false);
  212. furi_timer_stop(timer);
  213. notification_message(notifications, &sequence_display_backlight_enforce_auto);
  214. break;
  215. }
  216. }
  217. if(event.input.key == InputKeyOk) {
  218. // Нам ваша подсветка и нахой не нужна! Или нужна?
  219. Backlight++;
  220. if (Backlight > 2) Backlight = 0;
  221. }
  222. }
  223. if(event.input.type == InputTypeRepeat) { // Зажатые кнопки
  224. if(event.input.key == InputKeyRight) {
  225. if(furi_timer_is_running(timer)) {
  226. notification_message(notifications, &sequence_error);
  227. }
  228. else {
  229. Count = Count+10;
  230. }
  231. }
  232. if(event.input.key == InputKeyLeft) {
  233. if(furi_timer_is_running(timer)) {
  234. notification_message(notifications, &sequence_error);
  235. }
  236. else {
  237. Count = Count-10;
  238. }
  239. }
  240. if(event.input.key == InputKeyUp) {
  241. if(furi_timer_is_running(timer)) {
  242. notification_message(notifications, &sequence_error);
  243. }
  244. else {
  245. Time = Time+10;
  246. }
  247. }
  248. if(event.input.key == InputKeyDown) {
  249. if(furi_timer_is_running(timer)) {
  250. notification_message(notifications, &sequence_error);
  251. }
  252. else {
  253. Time = Time-10;
  254. }
  255. }
  256. }
  257. }
  258. // Наше событие — это сработавший таймер
  259. else if(event.type == EventTypeTick) {
  260. WorkTime--;
  261. if( WorkTime < 1 ) { // фоткаем
  262. notification_message(notifications, &sequence_blink_white_100);
  263. if (Bulb) {
  264. gpio_item_set_all_pins(false); WorkCount = 0;
  265. }
  266. else {
  267. WorkCount--;
  268. view_port_update(view_port);
  269. notification_message(notifications, &sequence_click);
  270. // Дрыгаем ногами
  271. //gpio_item_set_all_pins(true);
  272. gpio_item_set_pin(4, true);
  273. gpio_item_set_pin(5, true);
  274. furi_delay_ms(400); // На короткие нажатия фотик плохо реагирует
  275. gpio_item_set_pin(4, false);
  276. gpio_item_set_pin(5, false);
  277. //gpio_item_set_all_pins(false);
  278. if (InfiniteShot) WorkCount++;
  279. WorkTime = Time;
  280. view_port_update(view_port);
  281. }
  282. }
  283. else {
  284. // Отправляем нотификацию мигания синим светодиодом
  285. notification_message(notifications, &sequence_blink_blue_100);
  286. }
  287. if( WorkCount < 1 ) { // закончили
  288. gpio_item_set_all_pins(false);
  289. furi_timer_stop(timer);
  290. notification_message(notifications, &sequence_audiovisual_alert);
  291. WorkTime = 3;
  292. WorkCount = 0;
  293. }
  294. switch (Backlight) { // чо по подсветке?
  295. case 1:
  296. notification_message(notifications, &sequence_display_backlight_on);
  297. break;
  298. case 2:
  299. notification_message(notifications, &sequence_display_backlight_off);
  300. break;
  301. default:
  302. notification_message(notifications, &sequence_display_backlight_enforce_auto);
  303. }
  304. }
  305. if (Time < 1) Time = 1; // Не даём открутить таймер меньше единицы
  306. if (Count < -1) Count = 0; // А тут даём, бо 0 кадров это бесконечная съёмка, а -1 кадров - BULB
  307. }
  308. // Схороняем настройки
  309. FlipperFormat* save = flipper_format_file_alloc(storage);
  310. do {
  311. if(!flipper_format_file_open_always(save, CONFIG_FILE_PATH)) {notification_message(notifications, &sequence_error); break;}
  312. if(!flipper_format_write_header_cstr(save, "Zeitraffer", 1)) {notification_message(notifications, &sequence_error); break;}
  313. if(!flipper_format_write_comment_cstr(save, "Zeitraffer app settings: № of frames, interval time, backlight type, Delay")) {notification_message(notifications, &sequence_error); break;}
  314. if(!flipper_format_write_int32(save, "Time", &Time, 1)) {notification_message(notifications, &sequence_error); break;}
  315. if(!flipper_format_write_int32(save, "Count", &Count, 1)) {notification_message(notifications, &sequence_error); break;}
  316. if(!flipper_format_write_int32(save, "Backlight", &Backlight, 1)) {notification_message(notifications, &sequence_error); break;}
  317. if(!flipper_format_write_int32(save, "Delay", &Delay, 1)) {notification_message(notifications, &sequence_error); break;}
  318. } while(0);
  319. flipper_format_free(save);
  320. furi_record_close(RECORD_STORAGE);
  321. // Очищаем таймер
  322. furi_timer_free(timer);
  323. // Специальная очистка памяти, занимаемой очередью
  324. furi_message_queue_free(event_queue);
  325. // Чистим созданные объекты, связанные с интерфейсом
  326. gui_remove_view_port(gui, view_port);
  327. view_port_free(view_port);
  328. furi_record_close(RECORD_GUI);
  329. // Очищаем нотификации
  330. furi_record_close(RECORD_NOTIFICATION);
  331. return 0;
  332. }