unitemp.c 12 KB

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