Sensors.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. char* args = ((char*)(file_buf + line_end + offset));
  310. const SensorType* stype = unitemp_sensors_getTypeFromStr(type);
  311. //Проверка типа датчика
  312. if(stype != NULL && sizeof(name) > 0 && sizeof(name) <= 11) {
  313. Sensor* sensor =
  314. unitemp_sensor_alloc(name, unitemp_sensors_getTypeFromStr(type), args);
  315. if(sensor != NULL) {
  316. unitemp_sensors_add(sensor);
  317. } else {
  318. FURI_LOG_E(APP_NAME, "Failed sensor (%s:%s) mem allocation", name, type);
  319. }
  320. } else {
  321. FURI_LOG_E(APP_NAME, "Unsupported sensor name (%s) or sensor type (%s)", name, type);
  322. }
  323. //Вычисление конца строки
  324. line_end = furi_string_search_char(file, '\n', line_end + 1);
  325. }
  326. free(file_buf);
  327. file_stream_close(app->file_stream);
  328. stream_free(app->file_stream);
  329. FURI_LOG_I(APP_NAME, "Sensors have been successfully loaded");
  330. return true;
  331. }
  332. bool unitemp_sensors_save(void) {
  333. #ifdef UNITEMP_DEBUG
  334. FURI_LOG_D(APP_NAME, "Saving sensors...");
  335. #endif
  336. //Выделение памяти для потока
  337. app->file_stream = file_stream_alloc(app->storage);
  338. //Переменная пути к файлу
  339. FuriString* filepath = furi_string_alloc();
  340. //Составление пути к файлу
  341. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SENSORS);
  342. //Создание папки плагина
  343. storage_common_mkdir(app->storage, APP_PATH_FOLDER);
  344. //Открытие потока
  345. if(!file_stream_open(
  346. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) {
  347. FURI_LOG_E(
  348. APP_NAME,
  349. "An error occurred while saving the sensors file: %d",
  350. file_stream_get_error(app->file_stream));
  351. //Закрытие потока и освобождение памяти
  352. file_stream_close(app->file_stream);
  353. stream_free(app->file_stream);
  354. return false;
  355. }
  356. //Сохранение датчиков
  357. for(uint8_t i = 0; i < unitemp_sensors_getActiveCount(); i++) {
  358. if(unitemp_sensor_getActive(i)->type->interface == &SINGLE_WIRE) {
  359. stream_write_format(
  360. app->file_stream,
  361. "%s %s %d\n",
  362. unitemp_sensor_getActive(i)->name,
  363. unitemp_sensor_getActive(i)->type->typename,
  364. unitemp_singlewire_sensorGetGPIO(unitemp_sensor_getActive(i))->num);
  365. }
  366. if(unitemp_sensor_getActive(i)->type->interface == &I2C) {
  367. stream_write_format(
  368. app->file_stream,
  369. "%s %s %X\n",
  370. unitemp_sensor_getActive(i)->name,
  371. unitemp_sensor_getActive(i)->type->typename,
  372. ((I2CSensor*)unitemp_sensor_getActive(i)->instance)->currentI2CAdr);
  373. }
  374. if(unitemp_sensor_getActive(i)->type->interface == &ONE_WIRE) {
  375. stream_write_format(
  376. app->file_stream,
  377. "%s %s %d %02X%02X%02X%02X%02X%02X%02X%02X\n",
  378. unitemp_sensor_getActive(i)->name,
  379. unitemp_sensor_getActive(i)->type->typename,
  380. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->bus->gpio->num,
  381. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[0],
  382. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[1],
  383. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[2],
  384. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[3],
  385. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[4],
  386. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[5],
  387. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[6],
  388. ((OneWireSensor*)unitemp_sensor_getActive(i)->instance)->deviceID[7]);
  389. }
  390. }
  391. //Закрытие потока и освобождение памяти
  392. file_stream_close(app->file_stream);
  393. stream_free(app->file_stream);
  394. FURI_LOG_I(APP_NAME, "Sensors have been successfully saved");
  395. return true;
  396. }
  397. void unitemp_sensors_reload(void) {
  398. unitemp_sensors_deInit();
  399. unitemp_sensors_free();
  400. unitemp_sensors_load();
  401. unitemp_sensors_init();
  402. }
  403. bool unitemp_sensor_isContains(Sensor* sensor) {
  404. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  405. if(app->sensors[i] == sensor) return true;
  406. }
  407. return false;
  408. }
  409. Sensor* unitemp_sensor_alloc(char* name, const SensorType* type, char* args) {
  410. if(name == NULL || type == NULL) return NULL;
  411. bool status = false;
  412. //Выделение памяти под датчик
  413. Sensor* sensor = malloc(sizeof(Sensor));
  414. if(sensor == NULL) {
  415. FURI_LOG_E(APP_NAME, "Sensor %s allocation error", name);
  416. return false;
  417. }
  418. //Выделение памяти под имя
  419. sensor->name = malloc(11);
  420. if(sensor->name == NULL) {
  421. FURI_LOG_E(APP_NAME, "Sensor %s name allocation error", name);
  422. return false;
  423. }
  424. //Запись имени датчка
  425. strcpy(sensor->name, name);
  426. //Тип датчика
  427. sensor->type = type;
  428. //Статус датчика по умолчанию - ошибка
  429. sensor->status = UT_SENSORSTATUS_ERROR;
  430. //Время последнего опроса
  431. sensor->lastPollingTime =
  432. furi_get_tick() - 10000; //чтобы первый опрос произошёл как можно раньше
  433. sensor->temp = -128.0f;
  434. sensor->hum = -128.0f;
  435. sensor->pressure = -128.0f;
  436. //Выделение памяти под инстанс датчика в зависимости от его интерфейса
  437. status = sensor->type->interface->allocator(sensor, args);
  438. //Выход если датчик успешно развёрнут
  439. if(status) {
  440. FURI_LOG_I(APP_NAME, "Sensor %s allocated", name);
  441. return sensor;
  442. }
  443. //Выход с очисткой если память для датчика не была выделена
  444. free(sensor->name);
  445. free(sensor);
  446. FURI_LOG_E(APP_NAME, "Sensor %s(%s) allocation error", name, type->typename);
  447. return NULL;
  448. }
  449. void unitemp_sensor_free(Sensor* sensor) {
  450. if(sensor == NULL) {
  451. FURI_LOG_E(APP_NAME, "Null pointer sensor releasing");
  452. return;
  453. }
  454. if(sensor->type == NULL) {
  455. FURI_LOG_E(APP_NAME, "Sensor type is null");
  456. return;
  457. }
  458. if(sensor->type->mem_releaser == NULL) {
  459. FURI_LOG_E(APP_NAME, "Sensor releaser is null");
  460. return;
  461. }
  462. bool status = false;
  463. //Высвобождение памяти под инстанс
  464. status = sensor->type->interface->mem_releaser(sensor);
  465. UNUSED(status);
  466. #ifdef UNITEMP_DEBUG
  467. if(status) {
  468. FURI_LOG_D(APP_NAME, "Sensor %s memory successfully released", sensor->name);
  469. } else {
  470. FURI_LOG_E(APP_NAME, "Sensor %s memory is not released", sensor->name);
  471. }
  472. #endif
  473. free(sensor->name);
  474. //free(sensor);
  475. }
  476. void unitemp_sensors_free(void) {
  477. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  478. unitemp_sensor_free(app->sensors[i]);
  479. }
  480. app->sensors_count = 0;
  481. }
  482. bool unitemp_sensors_init(void) {
  483. bool result = true;
  484. //Перебор датчиков из списка
  485. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  486. //Включение 5V если на порту 1 FZ его нет
  487. //Может пропасть при отключении USB
  488. if(furi_hal_power_is_otg_enabled() != true) {
  489. furi_hal_power_enable_otg();
  490. #ifdef UNITEMP_DEBUG
  491. FURI_LOG_D(APP_NAME, "OTG enabled");
  492. #endif
  493. }
  494. if(!(*app->sensors[i]->type->initializer)(app->sensors[i])) {
  495. FURI_LOG_E(
  496. APP_NAME,
  497. "An error occurred during sensor initialization %s",
  498. app->sensors[i]->name);
  499. result = false;
  500. }
  501. #ifdef UNITEMP_DEBUG
  502. FURI_LOG_D(APP_NAME, "Sensor %s successfully initialized", app->sensors[i]->name);
  503. #endif
  504. }
  505. app->sensors_ready = true;
  506. return result;
  507. }
  508. bool unitemp_sensors_deInit(void) {
  509. bool result = true;
  510. //Выключение 5 В если до этого оно не было включено
  511. if(app->settings.lastOTGState != true) {
  512. furi_hal_power_disable_otg();
  513. #ifdef UNITEMP_DEBUG
  514. FURI_LOG_D(APP_NAME, "OTG disabled");
  515. #endif
  516. }
  517. //Перебор датчиков из списка
  518. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  519. if(!(*app->sensors[i]->type->deinitializer)(app->sensors[i])) {
  520. FURI_LOG_E(
  521. APP_NAME,
  522. "An error occurred during sensor deinitialization %s",
  523. app->sensors[i]->name);
  524. result = false;
  525. }
  526. }
  527. return result;
  528. }
  529. UnitempStatus unitemp_sensor_updateData(Sensor* sensor) {
  530. if(sensor == NULL) return UT_SENSORSTATUS_ERROR;
  531. //Проверка на допустимость опроса датчика
  532. if(furi_get_tick() - sensor->lastPollingTime < sensor->type->pollingInterval) {
  533. //Возврат ошибки если последний опрос датчика был неудачным
  534. if(sensor->status == UT_SENSORSTATUS_TIMEOUT) {
  535. return UT_SENSORSTATUS_TIMEOUT;
  536. }
  537. return UT_SENSORSTATUS_EARLYPOOL;
  538. }
  539. sensor->lastPollingTime = furi_get_tick();
  540. if(!furi_hal_power_is_otg_enabled()) {
  541. furi_hal_power_enable_otg();
  542. }
  543. sensor->status = sensor->type->interface->updater(sensor);
  544. #ifdef UNITEMP_DEBUG
  545. if(sensor->status != UT_SENSORSTATUS_OK && sensor->status != UT_SENSORSTATUS_POLLING)
  546. FURI_LOG_D(APP_NAME, "Sensor %s update status %d", sensor->name, sensor->status);
  547. #endif
  548. if(app->settings.unit == FAHRENHEIT && sensor->status == UT_SENSORSTATUS_OK)
  549. uintemp_celsiumToFarengate(sensor);
  550. if(sensor->status == UT_SENSORSTATUS_OK) {
  551. unitemp_pascalToMmHg(sensor);
  552. }
  553. return sensor->status;
  554. }
  555. void unitemp_sensors_updateValues(void) {
  556. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  557. unitemp_sensor_updateData(unitemp_sensor_getActive(i));
  558. }
  559. }