unitemp.c 14 KB

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