unitemp.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. /**
  202. * @brief Выделение места под переменные плагина
  203. *
  204. * @return true Если всё прошло успешно
  205. * @return false Если в процессе загрузки произошла ошибка
  206. */
  207. static bool unitemp_alloc(void) {
  208. //Выделение памяти под данные приложения
  209. app = malloc(sizeof(Unitemp));
  210. //Разрешение работы приложения
  211. app->processing = true;
  212. //Открытие хранилища (?)
  213. app->storage = furi_record_open(RECORD_STORAGE);
  214. storage_common_migrate(app->storage, EXT_PATH("unitemp"), APP_PATH_FOLDER);
  215. //Уведомления
  216. app->notifications = furi_record_open(RECORD_NOTIFICATION);
  217. //Установка значений по умолчанию
  218. app->settings.infinityBacklight = true; //Подсветка горит всегда
  219. app->settings.temp_unit = UT_TEMP_CELSIUS; //Единица измерения температуры - градусы Цельсия
  220. app->settings.pressure_unit = UT_PRESSURE_MM_HG; //Единица измерения давления - мм рт. ст.
  221. app->settings.heat_index = false;
  222. app->gui = furi_record_open(RECORD_GUI);
  223. //Диспетчер окон
  224. app->view_dispatcher = view_dispatcher_alloc();
  225. app->sensors = NULL;
  226. app->buff = malloc(BUFF_SIZE);
  227. unitemp_General_alloc();
  228. unitemp_MainMenu_alloc();
  229. unitemp_Settings_alloc();
  230. unitemp_SensorsList_alloc();
  231. unitemp_SensorEdit_alloc();
  232. unitemp_SensorNameEdit_alloc();
  233. unitemp_SensorActions_alloc();
  234. unitemp_widgets_alloc();
  235. //Всплывающее окно
  236. app->popup = popup_alloc();
  237. view_dispatcher_add_view(app->view_dispatcher, UnitempViewPopup, popup_get_view(app->popup));
  238. view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
  239. return true;
  240. }
  241. /**
  242. * @brief Освыбождение памяти после работы приложения
  243. */
  244. static void unitemp_free(void) {
  245. popup_free(app->popup);
  246. //Удаление вида после обработки
  247. view_dispatcher_remove_view(app->view_dispatcher, UnitempViewPopup);
  248. unitemp_widgets_free();
  249. unitemp_SensorActions_free();
  250. unitemp_SensorNameEdit_free();
  251. unitemp_SensorEdit_free();
  252. unitemp_SensorsList_free();
  253. unitemp_Settings_free();
  254. unitemp_MainMenu_free();
  255. unitemp_General_free();
  256. free(app->buff);
  257. view_dispatcher_free(app->view_dispatcher);
  258. furi_record_close(RECORD_GUI);
  259. //Очистка датчиков
  260. //Высвыбождение данных датчиков
  261. unitemp_sensors_free();
  262. free(app->sensors);
  263. //Закрытие уведомлений
  264. furi_record_close(RECORD_NOTIFICATION);
  265. //Закрытие хранилища
  266. furi_record_close(RECORD_STORAGE);
  267. //Удаление в самую последнюю очередь
  268. free(app);
  269. }
  270. /**
  271. * @brief Точка входа в приложение
  272. *
  273. * @return Код ошибки
  274. */
  275. int32_t unitemp_app() {
  276. //Выделение памяти под переменные
  277. //Выход если произошла ошибка
  278. if(unitemp_alloc() == false) {
  279. //Освобождение памяти
  280. unitemp_free();
  281. //Выход
  282. return 0;
  283. }
  284. //Загрузка настроек из SD-карты
  285. unitemp_loadSettings();
  286. //Применение настроек
  287. if(app->settings.infinityBacklight == true) {
  288. //Постоянное свечение подсветки
  289. notification_message(app->notifications, &sequence_display_backlight_enforce_on);
  290. }
  291. app->settings.lastOTGState = furi_hal_power_is_otg_enabled();
  292. //Загрузка датчиков из SD-карты
  293. unitemp_sensors_load();
  294. //Инициализация датчиков
  295. unitemp_sensors_init();
  296. unitemp_General_switch();
  297. while(app->processing) {
  298. if(app->sensors_ready) unitemp_sensors_updateValues();
  299. furi_delay_ms(100);
  300. }
  301. //Деинициализация датчиков
  302. unitemp_sensors_deInit();
  303. //Автоматическое управление подсветкой
  304. if(app->settings.infinityBacklight == true)
  305. notification_message(app->notifications, &sequence_display_backlight_enforce_auto);
  306. //Освобождение памяти
  307. unitemp_free();
  308. //Выход
  309. return 0;
  310. }