Sensors.c 23 KB

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