Sensors.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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 "Sensors.h"
  16. #include <furi_hal_power.h>
  17. //Порты ввода/вывода, которые не были обозначены в общем списке
  18. const GpioPin SWC_10 = {.pin = LL_GPIO_PIN_14, .port = GPIOA};
  19. const GpioPin SIO_12 = {.pin = LL_GPIO_PIN_13, .port = GPIOA};
  20. const GpioPin TX_13 = {.pin = LL_GPIO_PIN_6, .port = GPIOB};
  21. const GpioPin RX_14 = {.pin = LL_GPIO_PIN_7, .port = GPIOB};
  22. //Количество доступных портов ввода/вывода
  23. #define GPIO_ITEMS (sizeof(GPIOList) / sizeof(GPIO))
  24. //Количество интерфейсов
  25. #define INTERFACES_TYPES_COUNT (int)(sizeof(interfaces) / sizeof(const Interface*))
  26. //Количество типов датчиков
  27. #define SENSOR_TYPES_COUNT (int)(sizeof(sensorTypes) / sizeof(const SensorType*))
  28. //Перечень достуных портов ввода/вывода
  29. static const GPIO GPIOList[] = {
  30. {2, "2 (A7)", &gpio_ext_pa7},
  31. {3, "3 (A6)", &gpio_ext_pa6},
  32. {4, "4 (A4)", &gpio_ext_pa4},
  33. {5, "5 (B3)", &gpio_ext_pb3},
  34. {6, "6 (B2)", &gpio_ext_pb2},
  35. {7, "7 (C3)", &gpio_ext_pc3},
  36. {10, " 10(SWC) ", &SWC_10},
  37. {12, "12 (SIO)", &SIO_12},
  38. {13, "13 (TX)", &TX_13},
  39. {14, "14 (RX)", &RX_14},
  40. {15, "15 (C1)", &gpio_ext_pc1},
  41. {16, "16 (C0)", &gpio_ext_pc0},
  42. {17, "17 (1W)", &gpio_ibutton}};
  43. //Список интерфейсов, которые прикреплены к GPIO (определяется индексом)
  44. //NULL - порт свободен, указатель на интерфейс - порт занят этим интерфейсом
  45. static const Interface* gpio_interfaces_list[GPIO_ITEMS] = {0};
  46. const Interface SINGLE_WIRE = {
  47. .name = "Single wire",
  48. .allocator = unitemp_singlewire_alloc,
  49. .mem_releaser = unitemp_singlewire_free,
  50. .updater = unitemp_singlewire_update};
  51. const Interface I2C = {
  52. .name = "I2C",
  53. .allocator = unitemp_I2C_sensor_alloc,
  54. .mem_releaser = unitemp_I2C_sensor_free,
  55. .updater = unitemp_I2C_sensor_update};
  56. const Interface ONE_WIRE = {
  57. .name = "One wire",
  58. .allocator = unitemp_onewire_sensor_alloc,
  59. .mem_releaser = unitemp_onewire_sensor_free,
  60. .updater = unitemp_onewire_sensor_update};
  61. const Interface SPI = {
  62. .name = "SPI",
  63. .allocator = unitemp_spi_sensor_alloc,
  64. .mem_releaser = unitemp_spi_sensor_free,
  65. .updater = unitemp_spi_sensor_update};
  66. //Перечень интерфейсов подключения
  67. //static const Interface* interfaces[] = {&SINGLE_WIRE, &I2C, &ONE_WIRE, &SPI};
  68. //Перечень датчиков
  69. static const SensorType* sensorTypes[] = {&DHT11, &DHT12_SW, &DHT20, &DHT21, &DHT22,
  70. &Dallas, &AM2320_SW, &AM2320_I2C, &HTU21x, &AHT10,
  71. &SHT30, &GXHT30, &LM75, &HDC1080, &BMP180,
  72. &BMP280, &BME280, &BME680, &MAX31855, &MAX6675,
  73. &SCD30, &SCD40};
  74. const SensorType* unitemp_sensors_getTypeFromInt(uint8_t index) {
  75. if(index > SENSOR_TYPES_COUNT) return NULL;
  76. return sensorTypes[index];
  77. }
  78. const SensorType* unitemp_sensors_getTypeFromStr(char* str) {
  79. UNUSED(str);
  80. if(str == NULL) return NULL;
  81. for(uint8_t i = 0; i < unitemp_sensors_getTypesCount(); i++) {
  82. if(!strcmp(str, sensorTypes[i]->typename)) {
  83. return sensorTypes[i];
  84. }
  85. }
  86. return NULL;
  87. }
  88. uint8_t unitemp_sensors_getTypesCount(void) {
  89. return SENSOR_TYPES_COUNT;
  90. }
  91. const SensorType** unitemp_sensors_getTypes(void) {
  92. return sensorTypes;
  93. }
  94. int unitemp_getIntFromType(const SensorType* type) {
  95. for(int i = 0; i < SENSOR_TYPES_COUNT; i++) {
  96. if(!strcmp(type->typename, sensorTypes[i]->typename)) {
  97. return i;
  98. }
  99. }
  100. return 255;
  101. }
  102. const GPIO* unitemp_gpio_getFromInt(uint8_t name) {
  103. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  104. if(GPIOList[i].num == name) {
  105. return &GPIOList[i];
  106. }
  107. }
  108. return NULL;
  109. }
  110. const GPIO* unitemp_gpio_getFromIndex(uint8_t index) {
  111. return &GPIOList[index];
  112. }
  113. uint8_t unitemp_gpio_toInt(const GPIO* gpio) {
  114. if(gpio == NULL) return 255;
  115. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  116. if(GPIOList[i].pin->pin == gpio->pin->pin && GPIOList[i].pin->port == gpio->pin->port) {
  117. return GPIOList[i].num;
  118. }
  119. }
  120. return 255;
  121. }
  122. uint8_t unitemp_gpio_to_index(const GpioPin* gpio) {
  123. if(gpio == NULL) return 255;
  124. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  125. if(GPIOList[i].pin->pin == gpio->pin && GPIOList[i].pin->port == gpio->port) {
  126. return i;
  127. }
  128. }
  129. return 255;
  130. }
  131. uint8_t unitemp_gpio_getAviablePortsCount(const Interface* interface, const GPIO* extraport) {
  132. uint8_t aviable_ports_count = 0;
  133. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  134. //Проверка для one wire
  135. if(interface == &ONE_WIRE) {
  136. if(((gpio_interfaces_list[i] == NULL || gpio_interfaces_list[i] == &ONE_WIRE)) ||
  137. (unitemp_gpio_getFromIndex(i) == extraport)) {
  138. aviable_ports_count++;
  139. }
  140. }
  141. //Проверка для single wire
  142. if(interface == &SINGLE_WIRE || interface == &SPI) {
  143. if(gpio_interfaces_list[i] == NULL || (unitemp_gpio_getFromIndex(i) == extraport)) {
  144. aviable_ports_count++;
  145. }
  146. }
  147. if(interface == &I2C) {
  148. //У I2C два фиксированых порта
  149. return 0;
  150. }
  151. }
  152. return aviable_ports_count;
  153. }
  154. void unitemp_gpio_lock(const GPIO* gpio, const Interface* interface) {
  155. uint8_t i = unitemp_gpio_to_index(gpio->pin);
  156. if(i == 255) return;
  157. gpio_interfaces_list[i] = interface;
  158. }
  159. void unitemp_gpio_unlock(const GPIO* gpio) {
  160. uint8_t i = unitemp_gpio_to_index(gpio->pin);
  161. if(i == 255) return;
  162. gpio_interfaces_list[i] = NULL;
  163. }
  164. const GPIO*
  165. unitemp_gpio_getAviablePort(const Interface* interface, uint8_t index, const GPIO* extraport) {
  166. //Проверка для I2C
  167. if(interface == &I2C) {
  168. if((gpio_interfaces_list[10] == NULL || gpio_interfaces_list[10] == &I2C) &&
  169. (gpio_interfaces_list[11] == NULL || gpio_interfaces_list[11] == &I2C)) {
  170. //Возврат истины
  171. return unitemp_gpio_getFromIndex(0);
  172. } else {
  173. //Возврат лжи
  174. return NULL;
  175. }
  176. }
  177. // This check is incorrect and not working anymore
  178. /*if(interface == &SPI) {
  179. if(!((gpio_interfaces_list[0] == NULL || gpio_interfaces_list[0] == &SPI) &&
  180. (gpio_interfaces_list[1] == NULL || gpio_interfaces_list[1] == &SPI) &&
  181. (gpio_interfaces_list[3] == NULL || gpio_interfaces_list[3] == &SPI))) {
  182. return NULL;
  183. }
  184. }*/
  185. uint8_t aviable_index = 0;
  186. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  187. //Проверка для one wire
  188. if(interface == &ONE_WIRE) {
  189. if(((gpio_interfaces_list[i] == NULL || gpio_interfaces_list[i] == &ONE_WIRE)) ||
  190. (unitemp_gpio_getFromIndex(i) == extraport)) {
  191. if(aviable_index == index) {
  192. return unitemp_gpio_getFromIndex(i);
  193. } else {
  194. aviable_index++;
  195. }
  196. }
  197. }
  198. //Проверка для single wire
  199. if(interface == &SINGLE_WIRE || interface == &SPI) {
  200. if(gpio_interfaces_list[i] == NULL || unitemp_gpio_getFromIndex(i) == extraport) {
  201. if(aviable_index == index) {
  202. return unitemp_gpio_getFromIndex(i);
  203. } else {
  204. aviable_index++;
  205. }
  206. }
  207. }
  208. }
  209. return NULL;
  210. }
  211. void unitemp_sensor_delete(Sensor* sensor) {
  212. for(uint8_t i = 0; i < app->sensors_count; i++) {
  213. if(app->sensors[i] == sensor) {
  214. app->sensors[i]->status = UT_SENSORSTATUS_INACTIVE;
  215. unitemp_sensors_save();
  216. unitemp_sensors_reload();
  217. return;
  218. }
  219. }
  220. }
  221. Sensor* unitemp_sensor_getActive(uint8_t index) {
  222. uint8_t aviable_index = 0;
  223. for(uint8_t i = 0; i < app->sensors_count; i++) {
  224. if(app->sensors[i]->status != UT_SENSORSTATUS_INACTIVE) {
  225. if(aviable_index == index) {
  226. return app->sensors[i];
  227. } else {
  228. aviable_index++;
  229. }
  230. }
  231. }
  232. return NULL;
  233. }
  234. uint8_t unitemp_sensors_getCount(void) {
  235. if(app->sensors == NULL) return 0;
  236. return app->sensors_count;
  237. }
  238. uint8_t unitemp_sensors_getActiveCount(void) {
  239. if(app->sensors == NULL) return 0;
  240. uint8_t counter = 0;
  241. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  242. if(app->sensors[i]->status != UT_SENSORSTATUS_INACTIVE) counter++;
  243. }
  244. return counter;
  245. }
  246. void unitemp_sensors_add(Sensor* sensor) {
  247. app->sensors =
  248. (Sensor**)realloc(app->sensors, (unitemp_sensors_getCount() + 1) * sizeof(Sensor*));
  249. app->sensors[unitemp_sensors_getCount()] = sensor;
  250. app->sensors_count++;
  251. }
  252. bool unitemp_sensors_load(void) {
  253. UNITEMP_DEBUG("Loading sensors...");
  254. //Выделение памяти на поток
  255. app->file_stream = file_stream_alloc(app->storage);
  256. //Переменная пути к файлу
  257. FuriString* filepath = furi_string_alloc();
  258. //Составление пути к файлу
  259. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SENSORS);
  260. //Открытие потока к файлу с датчиками
  261. if(!file_stream_open(
  262. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  263. // Free file path string if we got an error
  264. furi_string_free(filepath);
  265. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  266. FURI_LOG_W(APP_NAME, "Missing sensors file");
  267. //Закрытие потока и освобождение памяти
  268. file_stream_close(app->file_stream);
  269. stream_free(app->file_stream);
  270. return false;
  271. } else {
  272. FURI_LOG_E(
  273. APP_NAME,
  274. "An error occurred while loading the sensors file: %d",
  275. file_stream_get_error(app->file_stream));
  276. //Закрытие потока и освобождение памяти
  277. file_stream_close(app->file_stream);
  278. stream_free(app->file_stream);
  279. return false;
  280. }
  281. }
  282. // Free file path string if we successfully opened the file
  283. furi_string_free(filepath);
  284. //Вычисление размера файла
  285. uint16_t file_size = stream_size(app->file_stream);
  286. //Если файл пустой, то:
  287. if(file_size == (uint8_t)0) {
  288. FURI_LOG_W(APP_NAME, "Sensors file is empty");
  289. //Закрытие потока и освобождение памяти
  290. file_stream_close(app->file_stream);
  291. stream_free(app->file_stream);
  292. return false;
  293. }
  294. //Выделение памяти под загрузку файла
  295. uint8_t* file_buf = malloc(file_size);
  296. //Опустошение буфера файла
  297. memset(file_buf, 0, file_size);
  298. //Загрузка файла
  299. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  300. //Выход при ошибке чтения
  301. FURI_LOG_E(APP_NAME, "Error reading sensors file");
  302. //Закрытие потока и освобождение памяти
  303. file_stream_close(app->file_stream);
  304. stream_free(app->file_stream);
  305. free(file_buf);
  306. return false;
  307. }
  308. //Указатель на начало строки
  309. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  310. //Сколько байт до конца строки
  311. size_t line_end = 0;
  312. while(line_end != ((size_t)-1) && line_end != (size_t)(file_size - 1)) {
  313. //Имя датчика
  314. char name[11] = {0};
  315. //Тип датчика
  316. char type[11] = {0};
  317. //Смещение по температуре
  318. int temp_offset = 0;
  319. //Смещение по строке для отделения аргументов
  320. int offset = 0;
  321. //Чтение из строки
  322. sscanf(((char*)(file_buf + line_end)), "%s %s %d %n", name, type, &temp_offset, &offset);
  323. //Ограничение длины имени
  324. name[10] = '\0';
  325. //Замена ? на пробел
  326. for(uint8_t i = 0; i < 10; i++) {
  327. if(name[i] == '?') name[i] = ' ';
  328. }
  329. char* args = ((char*)(file_buf + line_end + offset));
  330. const SensorType* stype = unitemp_sensors_getTypeFromStr(type);
  331. //Проверка типа датчика
  332. if(stype != NULL && sizeof(name) > 0 && sizeof(name) <= 11) {
  333. Sensor* sensor =
  334. unitemp_sensor_alloc(name, unitemp_sensors_getTypeFromStr(type), args);
  335. if(sensor != NULL) {
  336. sensor->temp_offset = temp_offset;
  337. unitemp_sensors_add(sensor);
  338. } else {
  339. FURI_LOG_E(APP_NAME, "Failed sensor (%s:%s) mem allocation", name, type);
  340. }
  341. } else {
  342. FURI_LOG_E(APP_NAME, "Unsupported sensor name (%s) or sensor type (%s)", name, type);
  343. }
  344. //Вычисление конца строки
  345. line_end = furi_string_search_char(file, '\n', line_end + 1);
  346. }
  347. free(file_buf);
  348. file_stream_close(app->file_stream);
  349. stream_free(app->file_stream);
  350. FURI_LOG_I(APP_NAME, "Sensors have been successfully loaded");
  351. return true;
  352. }
  353. bool unitemp_sensors_save(void) {
  354. UNITEMP_DEBUG("Saving sensors...");
  355. //Выделение памяти для потока
  356. app->file_stream = file_stream_alloc(app->storage);
  357. //Переменная пути к файлу
  358. FuriString* filepath = furi_string_alloc();
  359. //Составление пути к файлу
  360. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SENSORS);
  361. //Создание папки плагина
  362. storage_common_mkdir(app->storage, APP_PATH_FOLDER);
  363. //Открытие потока
  364. if(!file_stream_open(
  365. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) {
  366. // Free file path string if we got an error
  367. furi_string_free(filepath);
  368. FURI_LOG_E(
  369. APP_NAME,
  370. "An error occurred while saving the sensors file: %d",
  371. file_stream_get_error(app->file_stream));
  372. //Закрытие потока и освобождение памяти
  373. file_stream_close(app->file_stream);
  374. stream_free(app->file_stream);
  375. return false;
  376. }
  377. // Free file path string if we successfully opened the file
  378. furi_string_free(filepath);
  379. //Сохранение датчиков
  380. for(uint8_t i = 0; i < unitemp_sensors_getActiveCount(); i++) {
  381. Sensor* sensor = unitemp_sensor_getActive(i);
  382. //Замена пробела на ?
  383. for(uint8_t i = 0; i < 10; i++) {
  384. if(sensor->name[i] == ' ') sensor->name[i] = '?';
  385. }
  386. stream_write_format(
  387. app->file_stream,
  388. "%s %s %d ",
  389. sensor->name,
  390. sensor->type->typename,
  391. sensor->temp_offset);
  392. if(sensor->type->interface == &SINGLE_WIRE) {
  393. stream_write_format(
  394. app->file_stream, "%d\n", unitemp_singlewire_sensorGetGPIO(sensor)->num);
  395. }
  396. if(sensor->type->interface == &SPI) {
  397. uint8_t gpio_num = ((SPISensor*)sensor->instance)->CS_pin->num;
  398. stream_write_format(app->file_stream, "%d\n", gpio_num);
  399. }
  400. if(sensor->type->interface == &I2C) {
  401. stream_write_format(
  402. app->file_stream, "%X\n", ((I2CSensor*)sensor->instance)->currentI2CAdr);
  403. }
  404. if(sensor->type->interface == &ONE_WIRE) {
  405. stream_write_format(
  406. app->file_stream,
  407. "%d %02X%02X%02X%02X%02X%02X%02X%02X\n",
  408. ((OneWireSensor*)sensor->instance)->bus->gpio->num,
  409. ((OneWireSensor*)sensor->instance)->deviceID[0],
  410. ((OneWireSensor*)sensor->instance)->deviceID[1],
  411. ((OneWireSensor*)sensor->instance)->deviceID[2],
  412. ((OneWireSensor*)sensor->instance)->deviceID[3],
  413. ((OneWireSensor*)sensor->instance)->deviceID[4],
  414. ((OneWireSensor*)sensor->instance)->deviceID[5],
  415. ((OneWireSensor*)sensor->instance)->deviceID[6],
  416. ((OneWireSensor*)sensor->instance)->deviceID[7]);
  417. }
  418. }
  419. //Закрытие потока и освобождение памяти
  420. file_stream_close(app->file_stream);
  421. stream_free(app->file_stream);
  422. FURI_LOG_I(APP_NAME, "Sensors have been successfully saved");
  423. return true;
  424. }
  425. void unitemp_sensors_reload(void) {
  426. unitemp_sensors_deInit();
  427. unitemp_sensors_free();
  428. unitemp_sensors_load();
  429. unitemp_sensors_init();
  430. }
  431. bool unitemp_sensor_isContains(Sensor* sensor) {
  432. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  433. if(app->sensors[i] == sensor) return true;
  434. }
  435. return false;
  436. }
  437. Sensor* unitemp_sensor_alloc(char* name, const SensorType* type, char* args) {
  438. if(name == NULL || type == NULL) return NULL;
  439. bool status = false;
  440. //Выделение памяти под датчик
  441. Sensor* sensor = malloc(sizeof(Sensor));
  442. if(sensor == NULL) {
  443. FURI_LOG_E(APP_NAME, "Sensor %s allocation error", name);
  444. return NULL;
  445. }
  446. //Выделение памяти под имя
  447. sensor->name = malloc(11);
  448. if(sensor->name == NULL) {
  449. FURI_LOG_E(APP_NAME, "Sensor %s name allocation error", name);
  450. return NULL;
  451. }
  452. //Запись имени датчка
  453. strcpy(sensor->name, name);
  454. //Тип датчика
  455. sensor->type = type;
  456. //Статус датчика по умолчанию - ошибка
  457. sensor->status = UT_SENSORSTATUS_ERROR;
  458. //Время последнего опроса
  459. sensor->lastPollingTime =
  460. furi_get_tick() - 10000; //чтобы первый опрос произошёл как можно раньше
  461. sensor->temp = -128.0f;
  462. sensor->hum = -128.0f;
  463. sensor->pressure = -128.0f;
  464. sensor->temp_offset = 0;
  465. //Выделение памяти под инстанс датчика в зависимости от его интерфейса
  466. status = sensor->type->interface->allocator(sensor, args);
  467. //Выход если датчик успешно развёрнут
  468. if(status) {
  469. UNITEMP_DEBUG("Sensor %s allocated", name);
  470. return sensor;
  471. }
  472. //Выход с очисткой если память для датчика не была выделена
  473. free(sensor->name);
  474. free(sensor);
  475. FURI_LOG_E(APP_NAME, "Sensor %s(%s) allocation error", name, type->typename);
  476. return NULL;
  477. }
  478. void unitemp_sensor_free(Sensor* sensor) {
  479. if(sensor == NULL) {
  480. FURI_LOG_E(APP_NAME, "Null pointer sensor releasing");
  481. return;
  482. }
  483. if(sensor->type == NULL) {
  484. FURI_LOG_E(APP_NAME, "Sensor type is null");
  485. return;
  486. }
  487. if(sensor->type->mem_releaser == NULL) {
  488. FURI_LOG_E(APP_NAME, "Sensor releaser is null");
  489. return;
  490. }
  491. bool status = false;
  492. //Высвобождение памяти под инстанс
  493. status = sensor->type->interface->mem_releaser(sensor);
  494. if(status) {
  495. UNITEMP_DEBUG("Sensor %s memory successfully released", sensor->name);
  496. } else {
  497. FURI_LOG_E(APP_NAME, "Sensor %s memory is not released", sensor->name);
  498. }
  499. free(sensor->name);
  500. }
  501. void unitemp_sensors_free(void) {
  502. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  503. unitemp_sensor_free(app->sensors[i]);
  504. }
  505. app->sensors_count = 0;
  506. }
  507. bool unitemp_sensors_init(void) {
  508. bool result = true;
  509. app->sensors_ready = false;
  510. //Перебор датчиков из списка
  511. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  512. //Включение 5V если на порту 1 FZ его нет
  513. //Может пропасть при отключении USB
  514. if(furi_hal_power_is_otg_enabled() != true) {
  515. furi_hal_power_enable_otg();
  516. UNITEMP_DEBUG("OTG enabled");
  517. }
  518. if(!(*app->sensors[i]->type->initializer)(app->sensors[i])) {
  519. FURI_LOG_E(
  520. APP_NAME,
  521. "An error occurred during sensor initialization %s",
  522. app->sensors[i]->name);
  523. result = false;
  524. }
  525. FURI_LOG_I(APP_NAME, "Sensor %s successfully initialized", app->sensors[i]->name);
  526. }
  527. app->sensors_ready = true;
  528. return result;
  529. }
  530. bool unitemp_sensors_deInit(void) {
  531. bool result = true;
  532. //Выключение 5 В если до этого оно не было включено
  533. if(app->settings.lastOTGState != true) {
  534. furi_hal_power_disable_otg();
  535. UNITEMP_DEBUG("OTG disabled");
  536. }
  537. //Перебор датчиков из списка
  538. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  539. if(!(*app->sensors[i]->type->deinitializer)(app->sensors[i])) {
  540. FURI_LOG_E(
  541. APP_NAME,
  542. "An error occurred during sensor deinitialization %s",
  543. app->sensors[i]->name);
  544. result = false;
  545. }
  546. }
  547. return result;
  548. }
  549. UnitempStatus unitemp_sensor_updateData(Sensor* sensor) {
  550. if(sensor == NULL) {
  551. return UT_SENSORSTATUS_ERROR;
  552. }
  553. //Проверка на допустимость опроса датчика
  554. if(furi_get_tick() - sensor->lastPollingTime < sensor->type->pollingInterval) {
  555. //Возврат ошибки если последний опрос датчика был неудачным
  556. if(sensor->status == UT_SENSORSTATUS_TIMEOUT) {
  557. return UT_SENSORSTATUS_TIMEOUT;
  558. }
  559. return UT_SENSORSTATUS_EARLYPOOL;
  560. }
  561. sensor->lastPollingTime = furi_get_tick();
  562. if(!furi_hal_power_is_otg_enabled()) {
  563. furi_hal_power_enable_otg();
  564. }
  565. sensor->status = sensor->type->interface->updater(sensor);
  566. if(sensor->status != UT_SENSORSTATUS_OK && sensor->status != UT_SENSORSTATUS_POLLING) {
  567. UNITEMP_DEBUG("Sensor %s update status %d", sensor->name, sensor->status);
  568. }
  569. if(sensor->status == UT_SENSORSTATUS_OK) {
  570. if(app->settings.heat_index &&
  571. ((sensor->type->datatype & (UT_TEMPERATURE | UT_HUMIDITY)) ==
  572. (UT_TEMPERATURE | UT_HUMIDITY))) {
  573. unitemp_calculate_heat_index(sensor);
  574. }
  575. if(app->settings.temp_unit == UT_TEMP_FAHRENHEIT) {
  576. uintemp_celsiumToFarengate(sensor);
  577. }
  578. sensor->temp += sensor->temp_offset / 10.f;
  579. if(app->settings.pressure_unit == UT_PRESSURE_MM_HG) {
  580. unitemp_pascalToMmHg(sensor);
  581. } else if(app->settings.pressure_unit == UT_PRESSURE_IN_HG) {
  582. unitemp_pascalToInHg(sensor);
  583. } else if(app->settings.pressure_unit == UT_PRESSURE_KPA) {
  584. unitemp_pascalToKPa(sensor);
  585. } else if(app->settings.pressure_unit == UT_PRESSURE_HPA) {
  586. unitemp_pascalToHPa(sensor);
  587. }
  588. }
  589. return sensor->status;
  590. }
  591. void unitemp_sensors_updateValues(void) {
  592. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  593. unitemp_sensor_updateData(unitemp_sensor_getActive(i));
  594. }
  595. }