unitemp.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. FURI_LOG_E(
  74. APP_NAME,
  75. "An error occurred while saving the settings file: %d",
  76. file_stream_get_error(app->file_stream));
  77. //Закрытие потока и освобождение памяти
  78. file_stream_close(app->file_stream);
  79. stream_free(app->file_stream);
  80. return false;
  81. }
  82. //Сохранение настроек
  83. stream_write_format(
  84. app->file_stream, "INFINITY_BACKLIGHT %d\n", app->settings.infinityBacklight);
  85. stream_write_format(app->file_stream, "TEMP_UNIT %d\n", app->settings.temp_unit);
  86. stream_write_format(app->file_stream, "PRESSURE_UNIT %d\n", app->settings.pressure_unit);
  87. stream_write_format(app->file_stream, "HEAT_INDEX %d\n", app->settings.heat_index);
  88. //Закрытие потока и освобождение памяти
  89. file_stream_close(app->file_stream);
  90. stream_free(app->file_stream);
  91. FURI_LOG_I(APP_NAME, "Settings have been successfully saved");
  92. return true;
  93. }
  94. bool unitemp_loadSettings(void) {
  95. UNITEMP_DEBUG("Loading settings...");
  96. //Выделение памяти на поток
  97. app->file_stream = file_stream_alloc(app->storage);
  98. //Переменная пути к файлу
  99. FuriString* filepath = furi_string_alloc();
  100. //Составление пути к файлу
  101. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SETTINGS);
  102. //Открытие потока к файлу настроек
  103. if(!file_stream_open(
  104. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  105. //Сохранение настроек по умолчанию в случае отсутствия файла
  106. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  107. FURI_LOG_W(APP_NAME, "Missing settings file. Setting defaults and saving...");
  108. //Закрытие потока и освобождение памяти
  109. file_stream_close(app->file_stream);
  110. stream_free(app->file_stream);
  111. //Сохранение стандартного конфига
  112. unitemp_saveSettings();
  113. return false;
  114. } else {
  115. FURI_LOG_E(
  116. APP_NAME,
  117. "An error occurred while loading the settings file: %d. Standard values have been applied",
  118. file_stream_get_error(app->file_stream));
  119. //Закрытие потока и освобождение памяти
  120. file_stream_close(app->file_stream);
  121. stream_free(app->file_stream);
  122. return false;
  123. }
  124. }
  125. //Вычисление размера файла
  126. uint8_t file_size = stream_size(app->file_stream);
  127. //Если файл пустой, то:
  128. if(file_size == (uint8_t)0) {
  129. FURI_LOG_W(APP_NAME, "Settings file is empty");
  130. //Закрытие потока и освобождение памяти
  131. file_stream_close(app->file_stream);
  132. stream_free(app->file_stream);
  133. //Сохранение стандартного конфига
  134. unitemp_saveSettings();
  135. return false;
  136. }
  137. //Выделение памяти под загрузку файла
  138. uint8_t* file_buf = malloc(file_size);
  139. //Опустошение буфера файла
  140. memset(file_buf, 0, file_size);
  141. //Загрузка файла
  142. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  143. //Выход при ошибке чтения
  144. FURI_LOG_E(APP_NAME, "Error reading settings file");
  145. //Закрытие потока и освобождение памяти
  146. file_stream_close(app->file_stream);
  147. stream_free(app->file_stream);
  148. free(file_buf);
  149. return false;
  150. }
  151. //Построчное чтение файла
  152. //Указатель на начало строки
  153. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  154. //Сколько байт до конца строки
  155. size_t line_end = 0;
  156. while(line_end != ((size_t)-1) && line_end != (size_t)(file_size - 1)) {
  157. char buff[20] = {0};
  158. sscanf(((char*)(file_buf + line_end)), "%s", buff);
  159. if(!strcmp(buff, "INFINITY_BACKLIGHT")) {
  160. //Чтение значения параметра
  161. int p = 0;
  162. sscanf(((char*)(file_buf + line_end)), "INFINITY_BACKLIGHT %d", &p);
  163. app->settings.infinityBacklight = p;
  164. } else if(!strcmp(buff, "TEMP_UNIT")) {
  165. //Чтение значения параметра
  166. int p = 0;
  167. sscanf(((char*)(file_buf + line_end)), "\nTEMP_UNIT %d", &p);
  168. app->settings.temp_unit = p;
  169. } else if(!strcmp(buff, "PRESSURE_UNIT")) {
  170. //Чтение значения параметра
  171. int p = 0;
  172. sscanf(((char*)(file_buf + line_end)), "\nPRESSURE_UNIT %d", &p);
  173. app->settings.pressure_unit = p;
  174. } else if(!strcmp(buff, "HEAT_INDEX")) {
  175. //Чтение значения параметра
  176. int p = 0;
  177. sscanf(((char*)(file_buf + line_end)), "\nHEAT_INDEX %d", &p);
  178. app->settings.heat_index = p;
  179. } else {
  180. FURI_LOG_W(APP_NAME, "Unknown settings parameter: %s", buff);
  181. }
  182. //Вычисление конца строки
  183. line_end = furi_string_search_char(file, '\n', line_end + 1);
  184. }
  185. free(file_buf);
  186. file_stream_close(app->file_stream);
  187. stream_free(app->file_stream);
  188. FURI_LOG_I(APP_NAME, "Settings have been successfully loaded");
  189. return true;
  190. }
  191. /**
  192. * @brief Выделение места под переменные плагина
  193. *
  194. * @return true Если всё прошло успешно
  195. * @return false Если в процессе загрузки произошла ошибка
  196. */
  197. static bool unitemp_alloc(void) {
  198. //Выделение памяти под данные приложения
  199. app = malloc(sizeof(Unitemp));
  200. //Разрешение работы приложения
  201. app->processing = true;
  202. //Открытие хранилища (?)
  203. app->storage = furi_record_open(RECORD_STORAGE);
  204. storage_common_migrate(app->storage, EXT_PATH("unitemp"), APP_PATH_FOLDER);
  205. //Уведомления
  206. app->notifications = furi_record_open(RECORD_NOTIFICATION);
  207. //Установка значений по умолчанию
  208. app->settings.infinityBacklight = true; //Подсветка горит всегда
  209. app->settings.temp_unit = UT_TEMP_CELSIUS; //Единица измерения температуры - градусы Цельсия
  210. app->settings.pressure_unit = UT_PRESSURE_MM_HG; //Единица измерения давления - мм рт. ст.
  211. app->settings.heat_index = false;
  212. app->gui = furi_record_open(RECORD_GUI);
  213. //Диспетчер окон
  214. app->view_dispatcher = view_dispatcher_alloc();
  215. app->sensors = NULL;
  216. app->buff = malloc(BUFF_SIZE);
  217. unitemp_General_alloc();
  218. unitemp_MainMenu_alloc();
  219. unitemp_Settings_alloc();
  220. unitemp_SensorsList_alloc();
  221. unitemp_SensorEdit_alloc();
  222. unitemp_SensorNameEdit_alloc();
  223. unitemp_SensorActions_alloc();
  224. unitemp_widgets_alloc();
  225. //Всплывающее окно
  226. app->popup = popup_alloc();
  227. view_dispatcher_add_view(app->view_dispatcher, UnitempViewPopup, popup_get_view(app->popup));
  228. view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
  229. return true;
  230. }
  231. /**
  232. * @brief Освыбождение памяти после работы приложения
  233. */
  234. static void unitemp_free(void) {
  235. popup_free(app->popup);
  236. //Удаление вида после обработки
  237. view_dispatcher_remove_view(app->view_dispatcher, UnitempViewPopup);
  238. unitemp_widgets_free();
  239. unitemp_SensorActions_free();
  240. unitemp_SensorNameEdit_free();
  241. unitemp_SensorEdit_free();
  242. unitemp_SensorsList_free();
  243. unitemp_Settings_free();
  244. unitemp_MainMenu_free();
  245. unitemp_General_free();
  246. free(app->buff);
  247. view_dispatcher_free(app->view_dispatcher);
  248. furi_record_close(RECORD_GUI);
  249. //Очистка датчиков
  250. //Высвыбождение данных датчиков
  251. unitemp_sensors_free();
  252. free(app->sensors);
  253. //Закрытие уведомлений
  254. furi_record_close(RECORD_NOTIFICATION);
  255. //Закрытие хранилища
  256. furi_record_close(RECORD_STORAGE);
  257. //Удаление в самую последнюю очередь
  258. free(app);
  259. }
  260. /**
  261. * @brief Точка входа в приложение
  262. *
  263. * @return Код ошибки
  264. */
  265. int32_t unitemp_app() {
  266. //Выделение памяти под переменные
  267. //Выход если произошла ошибка
  268. if(unitemp_alloc() == false) {
  269. //Освобождение памяти
  270. unitemp_free();
  271. //Выход
  272. return 0;
  273. }
  274. //Загрузка настроек из SD-карты
  275. unitemp_loadSettings();
  276. //Применение настроек
  277. if(app->settings.infinityBacklight == true) {
  278. //Постоянное свечение подсветки
  279. notification_message(app->notifications, &sequence_display_backlight_enforce_on);
  280. }
  281. app->settings.lastOTGState = furi_hal_power_is_otg_enabled();
  282. //Загрузка датчиков из SD-карты
  283. unitemp_sensors_load();
  284. //Инициализация датчиков
  285. unitemp_sensors_init();
  286. unitemp_General_switch();
  287. while(app->processing) {
  288. if(app->sensors_ready) unitemp_sensors_updateValues();
  289. furi_delay_ms(100);
  290. }
  291. //Деинициализация датчиков
  292. unitemp_sensors_deInit();
  293. //Автоматическое управление подсветкой
  294. if(app->settings.infinityBacklight == true)
  295. notification_message(app->notifications, &sequence_display_backlight_enforce_auto);
  296. //Освобождение памяти
  297. unitemp_free();
  298. //Выход
  299. return 0;
  300. }