unitemp.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. Unitemp - Universal temperature reader
  3. Copyright (C) 2022 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. #ifdef UNITEMP_DEBUG
  69. FURI_LOG_D(APP_NAME, "Loading settings...");
  70. #endif
  71. //Выделение памяти на поток
  72. app->file_stream = file_stream_alloc(app->storage);
  73. //Переменная пути к файлу
  74. FuriString* filepath = furi_string_alloc();
  75. //Составление пути к файлу
  76. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  77. //Открытие потока к файлу настроек
  78. if(!file_stream_open(
  79. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  80. //Сохранение настроек по умолчанию в случае отсутствия файла
  81. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  82. FURI_LOG_W(APP_NAME, "Missing settings file. Setting defaults and saving...");
  83. //Закрытие потока и освобождение памяти
  84. file_stream_close(app->file_stream);
  85. stream_free(app->file_stream);
  86. //Сохранение стандартного конфига
  87. unitemp_saveSettings();
  88. return false;
  89. } else {
  90. FURI_LOG_E(
  91. APP_NAME,
  92. "An error occurred while loading the settings file: %d. Standard values have been applied",
  93. file_stream_get_error(app->file_stream));
  94. //Закрытие потока и освобождение памяти
  95. file_stream_close(app->file_stream);
  96. stream_free(app->file_stream);
  97. return false;
  98. }
  99. }
  100. //Вычисление размера файла
  101. uint8_t file_size = stream_size(app->file_stream);
  102. //Если файл пустой, то:
  103. if(file_size == (uint8_t)0) {
  104. FURI_LOG_W(APP_NAME, "Settings file is empty");
  105. //Закрытие потока и освобождение памяти
  106. file_stream_close(app->file_stream);
  107. stream_free(app->file_stream);
  108. //Сохранение стандартного конфига
  109. unitemp_saveSettings();
  110. return false;
  111. }
  112. //Выделение памяти под загрузку файла
  113. uint8_t* file_buf = malloc(file_size);
  114. //Опустошение буфера файла
  115. memset(file_buf, 0, file_size);
  116. //Загрузка файла
  117. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  118. //Выход при ошибке чтения
  119. FURI_LOG_E(APP_NAME, "Error reading settings file");
  120. //Закрытие потока и освобождение памяти
  121. file_stream_close(app->file_stream);
  122. stream_free(app->file_stream);
  123. free(file_buf);
  124. return false;
  125. }
  126. //Построчное чтение файла
  127. //Указатель на начало строки
  128. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  129. //Сколько байт до конца строки
  130. size_t line_end = 0;
  131. while(line_end != ((size_t)-1) && line_end != (size_t)(file_size - 1)) {
  132. char buff[20] = {0};
  133. sscanf(((char*)(file_buf + line_end)), "%s", buff);
  134. if(!strcmp(buff, "INFINITY_BACKLIGHT")) {
  135. //Чтение значения параметра
  136. int p = 0;
  137. sscanf(((char*)(file_buf + line_end)), "INFINITY_BACKLIGHT %d", &p);
  138. app->settings.infinityBacklight = p;
  139. } else if(!strcmp(buff, "TEMP_UNIT")) {
  140. //Чтение значения параметра
  141. int p = 0;
  142. sscanf(((char*)(file_buf + line_end)), "\nTEMP_UNIT %d", &p);
  143. app->settings.temp_unit = p;
  144. } else if(!strcmp(buff, "PRESSURE_UNIT")) {
  145. //Чтение значения параметра
  146. int p = 0;
  147. sscanf(((char*)(file_buf + line_end)), "\nPRESSURE_UNIT %d", &p);
  148. app->settings.pressure_unit = p;
  149. } else {
  150. FURI_LOG_W(APP_NAME, "Unknown settings parameter: %s", buff);
  151. }
  152. //Вычисление конца строки
  153. line_end = furi_string_search_char(file, '\n', line_end + 1);
  154. }
  155. free(file_buf);
  156. file_stream_close(app->file_stream);
  157. stream_free(app->file_stream);
  158. FURI_LOG_I(APP_NAME, "Settings have been successfully loaded");
  159. return true;
  160. }
  161. /**
  162. * @brief Выделение места под переменные плагина
  163. *
  164. * @return true Если всё прошло успешно
  165. * @return false Если в процессе загрузки произошла ошибка
  166. */
  167. static bool unitemp_alloc(void) {
  168. //Выделение памяти под данные приложения
  169. app = malloc(sizeof(Unitemp));
  170. //Разрешение работы приложения
  171. app->processing = true;
  172. //Открытие хранилища (?)
  173. app->storage = furi_record_open(RECORD_STORAGE);
  174. //Уведомления
  175. app->notifications = furi_record_open(RECORD_NOTIFICATION);
  176. //Установка значений по умолчанию
  177. app->settings.infinityBacklight = true; //Подсветка горит всегда
  178. app->settings.temp_unit = UT_TEMP_CELSIUS; //Единица измерения температуры - градусы Цельсия
  179. app->settings.pressure_unit = UT_PRESSURE_MM_HG; //Единица измерения давления - мм рт. ст.
  180. app->gui = furi_record_open(RECORD_GUI);
  181. //Диспетчер окон
  182. app->view_dispatcher = view_dispatcher_alloc();
  183. app->sensors = NULL;
  184. app->buff = malloc(BUFF_SIZE);
  185. unitemp_General_alloc();
  186. unitemp_MainMenu_alloc();
  187. unitemp_Settings_alloc();
  188. unitemp_SensorsList_alloc();
  189. unitemp_SensorEdit_alloc();
  190. unitemp_SensorNameEdit_alloc();
  191. unitemp_SensorActions_alloc();
  192. unitemp_widgets_alloc();
  193. //Всплывающее окно
  194. app->popup = popup_alloc();
  195. view_dispatcher_add_view(app->view_dispatcher, UnitempViewPopup, popup_get_view(app->popup));
  196. view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
  197. return true;
  198. }
  199. /**
  200. * @brief Освыбождение памяти после работы приложения
  201. */
  202. static void unitemp_free(void) {
  203. popup_free(app->popup);
  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. }