zeitraffer.c 14 KB

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