Sensors.c 23 KB

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