unitemp.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. sensor->heat_index = sensor->heat_index * (9.0 / 5.0) + 32;
  26. }
  27. static float heat_index_consts[9] = {
  28. -42.379f,
  29. 2.04901523f,
  30. 10.14333127f,
  31. -0.22475541f,
  32. -0.00683783f,
  33. -0.05481717f,
  34. 0.00122874f,
  35. 0.00085282f,
  36. -0.00000199f};
  37. void unitemp_calculate_heat_index(Sensor* sensor) {
  38. // temp should be in Celsius, heat index will be in Celsius
  39. float temp = sensor->temp * (9.0 / 5.0) + 32.0f;
  40. float hum = sensor->hum;
  41. sensor->heat_index =
  42. (heat_index_consts[0] + heat_index_consts[1] * temp + heat_index_consts[2] * hum +
  43. heat_index_consts[3] * temp * hum + heat_index_consts[4] * temp * temp +
  44. heat_index_consts[5] * hum * hum + heat_index_consts[6] * temp * temp * hum +
  45. heat_index_consts[7] * temp * hum * hum + heat_index_consts[8] * temp * temp * hum * hum -
  46. 32.0f) *
  47. (5.0 / 9.0);
  48. }
  49. void unitemp_pascalToMmHg(Sensor* sensor) {
  50. sensor->pressure = sensor->pressure * 0.007500638;
  51. }
  52. void unitemp_pascalToKPa(Sensor* sensor) {
  53. sensor->pressure = sensor->pressure / 1000.0f;
  54. }
  55. void unitemp_pascalToHPa(Sensor* sensor) {
  56. sensor->pressure = sensor->pressure / 100.0f;
  57. }
  58. void unitemp_pascalToInHg(Sensor* sensor) {
  59. sensor->pressure = sensor->pressure * 0.0002953007;
  60. }
  61. bool unitemp_saveSettings(void) {
  62. //Выделение памяти для потока
  63. app->file_stream = file_stream_alloc(app->storage);
  64. //Переменная пути к файлу
  65. FuriString* filepath = furi_string_alloc();
  66. //Составление пути к файлу
  67. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  68. //Создание папки плагина
  69. storage_common_mkdir(app->storage, APP_PATH_FOLDER);
  70. //Открытие потока
  71. if(!file_stream_open(
  72. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) {
  73. // Free file path string if we got an error
  74. furi_string_free(filepath);
  75. FURI_LOG_E(
  76. APP_NAME,
  77. "An error occurred while saving the settings file: %d",
  78. file_stream_get_error(app->file_stream));
  79. //Закрытие потока и освобождение памяти
  80. file_stream_close(app->file_stream);
  81. stream_free(app->file_stream);
  82. return false;
  83. }
  84. //Сохранение настроек
  85. stream_write_format(
  86. app->file_stream, "INFINITY_BACKLIGHT %d\n", app->settings.infinityBacklight);
  87. stream_write_format(app->file_stream, "TEMP_UNIT %d\n", app->settings.temp_unit);
  88. stream_write_format(app->file_stream, "PRESSURE_UNIT %d\n", app->settings.pressure_unit);
  89. stream_write_format(app->file_stream, "HEAT_INDEX %d\n", app->settings.heat_index);
  90. //Закрытие потока и освобождение памяти
  91. file_stream_close(app->file_stream);
  92. stream_free(app->file_stream);
  93. // Free file path string if we successfully opened the file
  94. furi_string_free(filepath);
  95. FURI_LOG_I(APP_NAME, "Settings have been successfully saved");
  96. return true;
  97. }
  98. bool unitemp_loadSettings(void) {
  99. UNITEMP_DEBUG("Loading settings...");
  100. //Выделение памяти на поток
  101. app->file_stream = file_stream_alloc(app->storage);
  102. //Переменная пути к файлу
  103. FuriString* filepath = furi_string_alloc();
  104. //Составление пути к файлу
  105. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  106. //Открытие потока к файлу настроек
  107. if(!file_stream_open(
  108. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  109. //Сохранение настроек по умолчанию в случае отсутствия файла
  110. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  111. FURI_LOG_W(APP_NAME, "Missing settings file. Setting defaults and saving...");
  112. //Закрытие потока и освобождение памяти
  113. file_stream_close(app->file_stream);
  114. stream_free(app->file_stream);
  115. // Free file path string if we got an error
  116. furi_string_free(filepath);
  117. //Сохранение стандартного конфига
  118. unitemp_saveSettings();
  119. return false;
  120. } else {
  121. FURI_LOG_E(
  122. APP_NAME,
  123. "An error occurred while loading the settings file: %d. Standard values have been applied",
  124. file_stream_get_error(app->file_stream));
  125. //Закрытие потока и освобождение памяти
  126. file_stream_close(app->file_stream);
  127. stream_free(app->file_stream);
  128. // Free file path string if we got an error
  129. furi_string_free(filepath);
  130. return false;
  131. }
  132. }
  133. // Free file path string if we successfully opened the file
  134. furi_string_free(filepath);
  135. //Вычисление размера файла
  136. uint8_t file_size = stream_size(app->file_stream);
  137. //Если файл пустой, то:
  138. if(file_size == (uint8_t)0) {
  139. FURI_LOG_W(APP_NAME, "Settings file is empty");
  140. //Закрытие потока и освобождение памяти
  141. file_stream_close(app->file_stream);
  142. stream_free(app->file_stream);
  143. //Сохранение стандартного конфига
  144. unitemp_saveSettings();
  145. return false;
  146. }
  147. //Выделение памяти под загрузку файла
  148. uint8_t* file_buf = malloc(file_size);
  149. //Опустошение буфера файла
  150. memset(file_buf, 0, file_size);
  151. //Загрузка файла
  152. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  153. //Выход при ошибке чтения
  154. FURI_LOG_E(APP_NAME, "Error reading settings file");
  155. //Закрытие потока и освобождение памяти
  156. file_stream_close(app->file_stream);
  157. stream_free(app->file_stream);
  158. free(file_buf);
  159. return false;
  160. }
  161. //Построчное чтение файла
  162. //Указатель на начало строки
  163. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  164. //Сколько байт до конца строки
  165. size_t line_end = 0;
  166. while(line_end != ((size_t)-1) && line_end != (size_t)(file_size - 1)) {
  167. char buff[20] = {0};
  168. sscanf(((char*)(file_buf + line_end)), "%s", buff);
  169. if(!strcmp(buff, "INFINITY_BACKLIGHT")) {
  170. //Чтение значения параметра
  171. int p = 0;
  172. sscanf(((char*)(file_buf + line_end)), "INFINITY_BACKLIGHT %d", &p);
  173. app->settings.infinityBacklight = p;
  174. } else if(!strcmp(buff, "TEMP_UNIT")) {
  175. //Чтение значения параметра
  176. int p = 0;
  177. sscanf(((char*)(file_buf + line_end)), "\nTEMP_UNIT %d", &p);
  178. app->settings.temp_unit = p;
  179. } else if(!strcmp(buff, "PRESSURE_UNIT")) {
  180. //Чтение значения параметра
  181. int p = 0;
  182. sscanf(((char*)(file_buf + line_end)), "\nPRESSURE_UNIT %d", &p);
  183. app->settings.pressure_unit = p;
  184. } else if(!strcmp(buff, "HEAT_INDEX")) {
  185. //Чтение значения параметра
  186. int p = 0;
  187. sscanf(((char*)(file_buf + line_end)), "\nHEAT_INDEX %d", &p);
  188. app->settings.heat_index = p;
  189. } else {
  190. FURI_LOG_W(APP_NAME, "Unknown settings parameter: %s", buff);
  191. }
  192. //Вычисление конца строки
  193. line_end = furi_string_search_char(file, '\n', line_end + 1);
  194. }
  195. free(file_buf);
  196. file_stream_close(app->file_stream);
  197. stream_free(app->file_stream);
  198. FURI_LOG_I(APP_NAME, "Settings have been successfully loaded");
  199. return true;
  200. }
  201. static void unitemp_sensors_update_callback(void* context) {
  202. Unitemp* app = context;
  203. if(!app->processing) {
  204. view_dispatcher_stop(app->view_dispatcher);
  205. return;
  206. }
  207. if(app->sensors_ready) {
  208. unitemp_sensors_updateValues();
  209. }
  210. view_port_update(app->view_port);
  211. }
  212. /**
  213. * @brief Выделение места под переменные плагина
  214. *
  215. * @return true Если всё прошло успешно
  216. * @return false Если в процессе загрузки произошла ошибка
  217. */
  218. static bool unitemp_alloc(void) {
  219. //Выделение памяти под данные приложения
  220. app = malloc(sizeof(Unitemp));
  221. //Разрешение работы приложения
  222. app->processing = true;
  223. //Открытие хранилища (?)
  224. app->storage = furi_record_open(RECORD_STORAGE);
  225. //Уведомления
  226. app->notifications = furi_record_open(RECORD_NOTIFICATION);
  227. //Установка значений по умолчанию
  228. app->settings.infinityBacklight = true; //Подсветка горит всегда
  229. app->settings.temp_unit = UT_TEMP_CELSIUS; //Единица измерения температуры - градусы Цельсия
  230. app->settings.pressure_unit = UT_PRESSURE_MM_HG; //Единица измерения давления - мм рт. ст.
  231. app->settings.heat_index = false;
  232. app->gui = furi_record_open(RECORD_GUI);
  233. //Диспетчер окон
  234. app->view_dispatcher = view_dispatcher_alloc();
  235. view_dispatcher_enable_queue(app->view_dispatcher);
  236. view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
  237. view_dispatcher_set_tick_event_callback(
  238. app->view_dispatcher, unitemp_sensors_update_callback, 100);
  239. app->view_port = view_port_alloc();
  240. app->sensors = NULL;
  241. app->buff = malloc(BUFF_SIZE);
  242. unitemp_General_alloc();
  243. unitemp_MainMenu_alloc();
  244. unitemp_Settings_alloc();
  245. unitemp_SensorsList_alloc();
  246. unitemp_SensorEdit_alloc();
  247. unitemp_SensorNameEdit_alloc();
  248. unitemp_SensorActions_alloc();
  249. unitemp_widgets_alloc();
  250. //Всплывающее окно
  251. app->popup = popup_alloc();
  252. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  253. view_dispatcher_add_view(app->view_dispatcher, UnitempViewPopup, popup_get_view(app->popup));
  254. view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
  255. return true;
  256. }
  257. /**
  258. * @brief Освыбождение памяти после работы приложения
  259. */
  260. static void unitemp_free(void) {
  261. popup_free(app->popup);
  262. //Удаление вида после обработки
  263. view_dispatcher_remove_view(app->view_dispatcher, UnitempViewPopup);
  264. unitemp_widgets_free();
  265. unitemp_SensorActions_free();
  266. unitemp_SensorNameEdit_free();
  267. unitemp_SensorEdit_free();
  268. unitemp_SensorsList_free();
  269. unitemp_Settings_free();
  270. unitemp_MainMenu_free();
  271. unitemp_General_free();
  272. free(app->buff);
  273. view_dispatcher_free(app->view_dispatcher);
  274. view_port_enabled_set(app->view_port, false);
  275. gui_remove_view_port(app->gui, app->view_port);
  276. view_port_free(app->view_port);
  277. furi_record_close(RECORD_GUI);
  278. //Очистка датчиков
  279. //Высвыбождение данных датчиков
  280. unitemp_sensors_free();
  281. free(app->sensors);
  282. //Закрытие уведомлений
  283. furi_record_close(RECORD_NOTIFICATION);
  284. //Закрытие хранилища
  285. furi_record_close(RECORD_STORAGE);
  286. //Удаление в самую последнюю очередь
  287. free(app);
  288. }
  289. /**
  290. * @brief Точка входа в приложение
  291. *
  292. * @return Код ошибки
  293. */
  294. int32_t unitemp_app() {
  295. //Выделение памяти под переменные
  296. //Выход если произошла ошибка
  297. if(unitemp_alloc() == false) {
  298. //Освобождение памяти
  299. unitemp_free();
  300. //Выход
  301. return 0;
  302. }
  303. //Загрузка настроек из SD-карты
  304. unitemp_loadSettings();
  305. //Применение настроек
  306. if(app->settings.infinityBacklight == true) {
  307. //Постоянное свечение подсветки
  308. notification_message(app->notifications, &sequence_display_backlight_enforce_on);
  309. }
  310. app->settings.lastOTGState = furi_hal_power_is_otg_enabled();
  311. //Загрузка датчиков из SD-карты
  312. unitemp_sensors_load();
  313. //Инициализация датчиков
  314. unitemp_sensors_init();
  315. unitemp_General_switch();
  316. view_dispatcher_run(app->view_dispatcher);
  317. //Деинициализация датчиков
  318. unitemp_sensors_deInit();
  319. //Автоматическое управление подсветкой
  320. if(app->settings.infinityBacklight == true)
  321. notification_message(app->notifications, &sequence_display_backlight_enforce_auto);
  322. //Освобождение памяти
  323. unitemp_free();
  324. //Выход
  325. return 0;
  326. }