unitemp.c 12 KB

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