unitemp.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*
  2. Unitemp - Universal temperature reader
  3. Copyright (C) 2022-2023 Victor Nikitchuk (https://github.com/quen0n)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "unitemp.h"
  16. #include "Sensors.h"
  17. #include "./views/UnitempViews.h"
  18. #include <furi_hal_power.h>
  19. /* Переменные */
  20. //Данные приложения
  21. Unitemp* app;
  22. void uintemp_celsiumToFarengate(Sensor* sensor) {
  23. sensor->temp = sensor->temp * (9.0 / 5.0) + 32;
  24. }
  25. void unitemp_pascalToMmHg(Sensor* sensor) {
  26. sensor->pressure = sensor->pressure * 0.007500638;
  27. }
  28. void unitemp_pascalToKPa(Sensor* sensor) {
  29. sensor->pressure = sensor->pressure / 1000.0f;
  30. }
  31. void unitemp_pascalToInHg(Sensor* sensor) {
  32. sensor->pressure = sensor->pressure * 0.0002953007;
  33. }
  34. bool unitemp_saveSettings(void) {
  35. //Выделение памяти для потока
  36. app->file_stream = file_stream_alloc(app->storage);
  37. //Переменная пути к файлу
  38. FuriString* filepath = furi_string_alloc();
  39. //Составление пути к файлу
  40. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  41. //Создание папки плагина
  42. storage_common_mkdir(app->storage, APP_PATH_FOLDER);
  43. //Открытие потока
  44. if(!file_stream_open(
  45. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) {
  46. FURI_LOG_E(
  47. APP_NAME,
  48. "An error occurred while saving the settings file: %d",
  49. file_stream_get_error(app->file_stream));
  50. //Закрытие потока и освобождение памяти
  51. file_stream_close(app->file_stream);
  52. stream_free(app->file_stream);
  53. return false;
  54. }
  55. //Сохранение настроек
  56. stream_write_format(
  57. app->file_stream, "INFINITY_BACKLIGHT %d\n", app->settings.infinityBacklight);
  58. stream_write_format(app->file_stream, "TEMP_UNIT %d\n", app->settings.temp_unit);
  59. stream_write_format(app->file_stream, "PRESSURE_UNIT %d\n", app->settings.pressure_unit);
  60. //Закрытие потока и освобождение памяти
  61. file_stream_close(app->file_stream);
  62. stream_free(app->file_stream);
  63. FURI_LOG_I(APP_NAME, "Settings have been successfully saved");
  64. return true;
  65. }
  66. bool unitemp_loadSettings(void) {
  67. UNITEMP_DEBUG("Loading settings...");
  68. //Выделение памяти на поток
  69. app->file_stream = file_stream_alloc(app->storage);
  70. //Переменная пути к файлу
  71. FuriString* filepath = furi_string_alloc();
  72. //Составление пути к файлу
  73. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  74. //Открытие потока к файлу настроек
  75. if(!file_stream_open(
  76. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  77. //Сохранение настроек по умолчанию в случае отсутствия файла
  78. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  79. FURI_LOG_W(APP_NAME, "Missing settings file. Setting defaults and saving...");
  80. //Закрытие потока и освобождение памяти
  81. file_stream_close(app->file_stream);
  82. stream_free(app->file_stream);
  83. //Сохранение стандартного конфига
  84. unitemp_saveSettings();
  85. return false;
  86. } else {
  87. FURI_LOG_E(
  88. APP_NAME,
  89. "An error occurred while loading the settings file: %d. Standard values have been applied",
  90. file_stream_get_error(app->file_stream));
  91. //Закрытие потока и освобождение памяти
  92. file_stream_close(app->file_stream);
  93. stream_free(app->file_stream);
  94. return false;
  95. }
  96. }
  97. //Вычисление размера файла
  98. uint8_t file_size = stream_size(app->file_stream);
  99. //Если файл пустой, то:
  100. if(file_size == (uint8_t)0) {
  101. FURI_LOG_W(APP_NAME, "Settings file is empty");
  102. //Закрытие потока и освобождение памяти
  103. file_stream_close(app->file_stream);
  104. stream_free(app->file_stream);
  105. //Сохранение стандартного конфига
  106. unitemp_saveSettings();
  107. return false;
  108. }
  109. //Выделение памяти под загрузку файла
  110. uint8_t* file_buf = malloc(file_size);
  111. //Опустошение буфера файла
  112. memset(file_buf, 0, file_size);
  113. //Загрузка файла
  114. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  115. //Выход при ошибке чтения
  116. FURI_LOG_E(APP_NAME, "Error reading settings file");
  117. //Закрытие потока и освобождение памяти
  118. file_stream_close(app->file_stream);
  119. stream_free(app->file_stream);
  120. free(file_buf);
  121. return false;
  122. }
  123. //Построчное чтение файла
  124. //Указатель на начало строки
  125. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  126. //Сколько байт до конца строки
  127. size_t line_end = 0;
  128. while(line_end != ((size_t)-1) && line_end != (size_t)(file_size - 1)) {
  129. char buff[20] = {0};
  130. sscanf(((char*)(file_buf + line_end)), "%s", buff);
  131. if(!strcmp(buff, "INFINITY_BACKLIGHT")) {
  132. //Чтение значения параметра
  133. int p = 0;
  134. sscanf(((char*)(file_buf + line_end)), "INFINITY_BACKLIGHT %d", &p);
  135. app->settings.infinityBacklight = p;
  136. } else if(!strcmp(buff, "TEMP_UNIT")) {
  137. //Чтение значения параметра
  138. int p = 0;
  139. sscanf(((char*)(file_buf + line_end)), "\nTEMP_UNIT %d", &p);
  140. app->settings.temp_unit = p;
  141. } else if(!strcmp(buff, "PRESSURE_UNIT")) {
  142. //Чтение значения параметра
  143. int p = 0;
  144. sscanf(((char*)(file_buf + line_end)), "\nPRESSURE_UNIT %d", &p);
  145. app->settings.pressure_unit = p;
  146. } else {
  147. FURI_LOG_W(APP_NAME, "Unknown settings parameter: %s", buff);
  148. }
  149. //Вычисление конца строки
  150. line_end = furi_string_search_char(file, '\n', line_end + 1);
  151. }
  152. free(file_buf);
  153. file_stream_close(app->file_stream);
  154. stream_free(app->file_stream);
  155. FURI_LOG_I(APP_NAME, "Settings have been successfully loaded");
  156. return true;
  157. }
  158. static void view_dispatcher_tick_event_callback(void* context) {
  159. UNUSED(context);
  160. if((app->sensors_ready) && (app->sensors_update)) {
  161. unitemp_sensors_updateValues();
  162. }
  163. }
  164. /**
  165. * @brief Выделение места под переменные плагина
  166. *
  167. * @return true Если всё прошло успешно
  168. * @return false Если в процессе загрузки произошла ошибка
  169. */
  170. static bool unitemp_alloc(void) {
  171. //Выделение памяти под данные приложения
  172. app = malloc(sizeof(Unitemp));
  173. app->sensors_ready = false;
  174. //Открытие хранилища (?)
  175. app->storage = furi_record_open(RECORD_STORAGE);
  176. //Уведомления
  177. app->notifications = furi_record_open(RECORD_NOTIFICATION);
  178. //Установка значений по умолчанию
  179. app->settings.infinityBacklight = true; //Подсветка горит всегда
  180. app->settings.temp_unit = UT_TEMP_CELSIUS; //Единица измерения температуры - градусы Цельсия
  181. app->settings.pressure_unit = UT_PRESSURE_MM_HG; //Единица измерения давления - мм рт. ст.
  182. app->gui = furi_record_open(RECORD_GUI);
  183. //Диспетчер окон
  184. app->view_dispatcher = view_dispatcher_alloc();
  185. app->sensors = NULL;
  186. app->buff = malloc(BUFF_SIZE);
  187. unitemp_General_alloc();
  188. unitemp_MainMenu_alloc();
  189. unitemp_Settings_alloc();
  190. unitemp_SensorsList_alloc();
  191. unitemp_SensorEdit_alloc();
  192. unitemp_SensorNameEdit_alloc();
  193. unitemp_SensorActions_alloc();
  194. unitemp_widgets_alloc();
  195. //Всплывающее окно
  196. app->popup = popup_alloc();
  197. view_dispatcher_add_view(app->view_dispatcher, UnitempViewPopup, popup_get_view(app->popup));
  198. view_dispatcher_set_tick_event_callback(
  199. app->view_dispatcher, view_dispatcher_tick_event_callback, furi_ms_to_ticks(100));
  200. view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
  201. return true;
  202. }
  203. /**
  204. * @brief Освыбождение памяти после работы приложения
  205. */
  206. static void unitemp_free(void) {
  207. popup_free(app->popup);
  208. //Удаление вида после обработки
  209. view_dispatcher_remove_view(app->view_dispatcher, UnitempViewPopup);
  210. unitemp_widgets_free();
  211. unitemp_SensorActions_free();
  212. unitemp_SensorNameEdit_free();
  213. unitemp_SensorEdit_free();
  214. unitemp_SensorsList_free();
  215. unitemp_Settings_free();
  216. unitemp_MainMenu_free();
  217. unitemp_General_free();
  218. free(app->buff);
  219. view_dispatcher_free(app->view_dispatcher);
  220. furi_record_close(RECORD_GUI);
  221. //Очистка датчиков
  222. //Высвыбождение данных датчиков
  223. unitemp_sensors_free();
  224. free(app->sensors);
  225. //Закрытие уведомлений
  226. furi_record_close(RECORD_NOTIFICATION);
  227. //Закрытие хранилища
  228. furi_record_close(RECORD_STORAGE);
  229. //Удаление в самую последнюю очередь
  230. free(app);
  231. }
  232. /**
  233. * @brief Точка входа в приложение
  234. *
  235. * @return Код ошибки
  236. */
  237. int32_t unitemp_app() {
  238. //Выделение памяти под переменные
  239. //Выход если произошла ошибка
  240. if(unitemp_alloc() == false) {
  241. //Освобождение памяти
  242. unitemp_free();
  243. //Выход
  244. return 0;
  245. }
  246. //Загрузка настроек из SD-карты
  247. unitemp_loadSettings();
  248. //Применение настроек
  249. if(app->settings.infinityBacklight == true) {
  250. //Постоянное свечение подсветки
  251. notification_message(app->notifications, &sequence_display_backlight_enforce_on);
  252. }
  253. app->settings.lastOTGState = furi_hal_power_is_otg_enabled();
  254. //Загрузка датчиков из SD-карты
  255. unitemp_sensors_load();
  256. //Инициализация датчиков
  257. unitemp_sensors_init();
  258. unitemp_General_switch();
  259. view_dispatcher_run(app->view_dispatcher);
  260. //Деинициализация датчиков
  261. unitemp_sensors_deInit();
  262. //Автоматическое управление подсветкой
  263. if(app->settings.infinityBacklight == true)
  264. notification_message(app->notifications, &sequence_display_backlight_enforce_auto);
  265. //Освобождение памяти
  266. unitemp_free();
  267. //Выход
  268. return 0;
  269. }