Sensors.c 23 KB

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