Sensors.c 23 KB

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