Sensors.c 23 KB

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