Sensors.c 23 KB

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