Sensors.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. #include "Sensors.h"
  2. #include <furi_hal_power.h>
  3. #include <m-string.h>
  4. //Порты ввода/вывода, которые не были обозначены в общем списке
  5. const GpioPin SWC_10 = {.pin = LL_GPIO_PIN_14, .port = GPIOA};
  6. const GpioPin SIO_12 = {.pin = LL_GPIO_PIN_13, .port = GPIOA};
  7. const GpioPin TX_13 = {.pin = LL_GPIO_PIN_6, .port = GPIOB};
  8. const GpioPin RX_14 = {.pin = LL_GPIO_PIN_7, .port = GPIOB};
  9. //Количество доступных портов ввода/вывода
  10. #define GPIO_ITEMS (sizeof(GPIOList) / sizeof(GPIO))
  11. //Количество интерфейсов
  12. #define INTERFACES_TYPES_COUNT (int)(sizeof(interfaces) / sizeof(const Interface*))
  13. //Количество типов датчиков
  14. #define SENSOR_TYPES_COUNT (int)(sizeof(sensorTypes) / sizeof(const SensorType*))
  15. //Перечень достуных портов ввода/вывода
  16. static const GPIO GPIOList[] = {
  17. {2, "2 (A7)", &gpio_ext_pa7},
  18. {3, "3 (A6)", &gpio_ext_pa6},
  19. {4, "4 (A4)", &gpio_ext_pa4},
  20. {5, "5 (B3)", &gpio_ext_pb3},
  21. {6, "6 (B2)", &gpio_ext_pb2},
  22. {7, "7 (C3)", &gpio_ext_pc3},
  23. {10, " 10(SWC) ", &SWC_10},
  24. {12, "12 (SIO)", &SIO_12},
  25. {13, "13 (TX)", &TX_13},
  26. {14, "14 (RX)", &RX_14},
  27. {15, "15 (C1)", &gpio_ext_pc1},
  28. {16, "16 (C0)", &gpio_ext_pc0},
  29. {17, "17 (1W)", &ibutton_gpio}};
  30. //Список интерфейсов, которые прикреплены к GPIO (определяется индексом)
  31. //NULL - порт свободен, указатель на интерфейс - порт занят этим интерфейсом
  32. static const Interface* gpio_interfaces_list[GPIO_ITEMS] = {0};
  33. const Interface SINGLE_WIRE = {
  34. .name = "Single wire",
  35. .allocator = unitemp_singlewire_alloc,
  36. .mem_releaser = unitemp_singlewire_free,
  37. .updater = unitemp_singlewire_update};
  38. const Interface I2C = {
  39. .name = "I2C",
  40. .allocator = unitemp_I2C_sensor_alloc,
  41. .mem_releaser = unitemp_I2C_sensor_free,
  42. .updater = unitemp_I2C_sensor_update};
  43. const Interface ONE_WIRE = {
  44. .name = "One wire",
  45. .allocator = unitemp_onewire_sensor_alloc,
  46. .mem_releaser = unitemp_onewire_sensor_free,
  47. .updater = unitemp_onewire_sensor_update};
  48. //Перечень интерфейсов подключения
  49. //static const Interface* interfaces[] = {&SINGLE_WIRE, &I2C, &ONE_WIRE};
  50. //Перечень датчиков
  51. static const SensorType* sensorTypes[] =
  52. {&DHT11, &DHT12_SW, &DHT21, &DHT22, &AM2320_SW, &LM75, &BMP280, &DS18x2x};
  53. const SensorType* unitemp_sensors_getTypeFromInt(uint8_t index) {
  54. if(index > SENSOR_TYPES_COUNT) return NULL;
  55. return sensorTypes[index];
  56. }
  57. const SensorType* unitemp_sensors_getTypeFromStr(char* str) {
  58. UNUSED(str);
  59. if(str == NULL) return NULL;
  60. for(uint8_t i = 0; i < unitemp_sensors_getTypesCount(); i++) {
  61. if(!strcmp(str, sensorTypes[i]->typename)) {
  62. return sensorTypes[i];
  63. }
  64. }
  65. return NULL;
  66. }
  67. uint8_t unitemp_sensors_getTypesCount(void) {
  68. return SENSOR_TYPES_COUNT;
  69. }
  70. const SensorType** unitemp_sensors_getTypes(void) {
  71. return sensorTypes;
  72. }
  73. int unitemp_getIntFromType(const SensorType* type) {
  74. for(int i = 0; i < SENSOR_TYPES_COUNT; i++) {
  75. if(!strcmp(type->typename, sensorTypes[i]->typename)) {
  76. return i;
  77. }
  78. }
  79. return 255;
  80. }
  81. const GPIO* unitemp_gpio_getFromInt(uint8_t name) {
  82. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  83. if(GPIOList[i].num == name) {
  84. return &GPIOList[i];
  85. }
  86. }
  87. return NULL;
  88. }
  89. const GPIO* unitemp_gpio_getFromIndex(uint8_t index) {
  90. return &GPIOList[index];
  91. }
  92. uint8_t unitemp_gpio_toInt(const GPIO* gpio) {
  93. if(gpio == NULL) return 255;
  94. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  95. if(GPIOList[i].pin->pin == gpio->pin->pin && GPIOList[i].pin->port == gpio->pin->port) {
  96. return GPIOList[i].num;
  97. }
  98. }
  99. return 255;
  100. }
  101. uint8_t unitemp_gpio_to_index(const GpioPin* gpio) {
  102. if(gpio == NULL) return 255;
  103. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  104. if(GPIOList[i].pin->pin == gpio->pin && GPIOList[i].pin->port == gpio->port) {
  105. return i;
  106. }
  107. }
  108. return 255;
  109. }
  110. uint8_t unitemp_gpio_getAviablePortsCount(const Interface* interface, const GPIO* extraport) {
  111. uint8_t aviable_ports_count = 0;
  112. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  113. //Проверка для one wire
  114. if(interface == &ONE_WIRE) {
  115. if(((gpio_interfaces_list[i] == NULL || gpio_interfaces_list[i] == &ONE_WIRE) &&
  116. (i != 12)) || //Почему-то не работает на 17 порте
  117. (unitemp_gpio_getFromIndex(i) == extraport)) {
  118. aviable_ports_count++;
  119. }
  120. }
  121. //Проверка для single wire
  122. if(interface == &SINGLE_WIRE) {
  123. if(gpio_interfaces_list[i] == NULL || (unitemp_gpio_getFromIndex(i) == extraport)) {
  124. aviable_ports_count++;
  125. }
  126. }
  127. if(interface == &I2C) {
  128. //У I2C два фиксированых порта
  129. return 0;
  130. }
  131. }
  132. return aviable_ports_count;
  133. }
  134. void unitemp_gpio_lock(const GPIO* gpio, const Interface* interface) {
  135. uint8_t i = unitemp_gpio_to_index(gpio->pin);
  136. if(i == 255) return;
  137. gpio_interfaces_list[i] = interface;
  138. }
  139. void unitemp_gpio_unlock(const GPIO* gpio) {
  140. uint8_t i = unitemp_gpio_to_index(gpio->pin);
  141. if(i == 255) return;
  142. gpio_interfaces_list[i] = NULL;
  143. }
  144. const GPIO*
  145. unitemp_gpio_getAviablePort(const Interface* interface, uint8_t index, const GPIO* extraport) {
  146. uint8_t aviable_index = 0;
  147. uint8_t aviable_port_count = unitemp_gpio_getAviablePortsCount(interface, extraport);
  148. for(uint8_t i = 0; i < GPIO_ITEMS; i++) {
  149. //Проверка для one wire
  150. if(interface == &ONE_WIRE) {
  151. //Почему-то не работает на 17 порте
  152. if(((gpio_interfaces_list[i] == NULL || gpio_interfaces_list[i] == &ONE_WIRE) &&
  153. (i != 12)) || //Почему-то не работает на 17 порте
  154. (unitemp_gpio_getFromIndex(i) == extraport)) {
  155. if(aviable_index == index) {
  156. return unitemp_gpio_getFromIndex(i);
  157. } else {
  158. aviable_index++;
  159. }
  160. }
  161. }
  162. //Проверка для single wire
  163. if(interface == &SINGLE_WIRE) {
  164. if(gpio_interfaces_list[i] == NULL || unitemp_gpio_getFromIndex(i) == extraport) {
  165. if(aviable_index == index) {
  166. return unitemp_gpio_getFromIndex(i);
  167. } else {
  168. aviable_index++;
  169. }
  170. }
  171. }
  172. }
  173. return NULL;
  174. }
  175. uint8_t unitemp_sensors_getCount(void) {
  176. if(app->sensors == NULL) return 0;
  177. return app->sensors_count;
  178. }
  179. void unitemp_sensors_add(Sensor* sensor) {
  180. app->sensors =
  181. (Sensor**)realloc(app->sensors, (unitemp_sensors_getCount() + 1) * sizeof(Sensor*));
  182. app->sensors[unitemp_sensors_getCount()] = sensor;
  183. app->sensors_count++;
  184. }
  185. bool unitemp_sensors_load(void) {
  186. FURI_LOG_D(APP_NAME, "Loading sensors...");
  187. //Выделение памяти на поток
  188. app->file_stream = file_stream_alloc(app->storage);
  189. //Переменная пути к файлу
  190. FuriString* filepath = furi_string_alloc();
  191. //Составление пути к файлу
  192. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SENSORS);
  193. //Открытие потока к файлу с датчиками
  194. if(!file_stream_open(
  195. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_OPEN_EXISTING)) {
  196. if(file_stream_get_error(app->file_stream) == FSE_NOT_EXIST) {
  197. FURI_LOG_W(APP_NAME, "Missing sensors file");
  198. //Закрытие потока и освобождение памяти
  199. file_stream_close(app->file_stream);
  200. stream_free(app->file_stream);
  201. return false;
  202. } else {
  203. FURI_LOG_E(
  204. APP_NAME,
  205. "An error occurred while loading the sensors file: %d",
  206. file_stream_get_error(app->file_stream));
  207. //Закрытие потока и освобождение памяти
  208. file_stream_close(app->file_stream);
  209. stream_free(app->file_stream);
  210. return false;
  211. }
  212. }
  213. //Вычисление размера файла
  214. uint8_t file_size = stream_size(app->file_stream);
  215. //Если файл пустой, то:
  216. if(file_size == (uint8_t)0) {
  217. FURI_LOG_W(APP_NAME, "Sensors file is empty");
  218. //Закрытие потока и освобождение памяти
  219. file_stream_close(app->file_stream);
  220. stream_free(app->file_stream);
  221. return false;
  222. }
  223. //Выделение памяти под загрузку файла
  224. uint8_t* file_buf = malloc(file_size);
  225. //Опустошение буфера файла
  226. memset(file_buf, 0, file_size);
  227. //Загрузка файла
  228. if(stream_read(app->file_stream, file_buf, file_size) != file_size) {
  229. //Выход при ошибке чтения
  230. FURI_LOG_E(APP_NAME, "Error reading sensors file");
  231. //Закрытие потока и освобождение памяти
  232. file_stream_close(app->file_stream);
  233. stream_free(app->file_stream);
  234. free(file_buf);
  235. return false;
  236. }
  237. //Указатель на начало строки
  238. FuriString* file = furi_string_alloc_set_str((char*)file_buf);
  239. //Сколько байт до конца строки
  240. size_t line_end = 0;
  241. while(line_end != STRING_FAILURE) {
  242. //Имя датчика
  243. char name[11] = {0};
  244. //Тип датчика
  245. char type[11] = {0};
  246. //Смещение по строке для отделения аргументов
  247. int offset = 0;
  248. //Чтение из строки
  249. sscanf(((char*)(file_buf + line_end)), "%s %s %n", name, type, &offset);
  250. //Ограничение длины имени
  251. name[10] = '\0';
  252. char* args = ((char*)(file_buf + line_end + offset));
  253. const SensorType* stype = unitemp_sensors_getTypeFromStr(type);
  254. //Проверка типа датчика
  255. if(stype != NULL && sizeof(name) > 0 && sizeof(name) <= 11) {
  256. Sensor* sensor =
  257. unitemp_sensor_alloc(name, unitemp_sensors_getTypeFromStr(type), args);
  258. if(sensor != NULL) {
  259. unitemp_sensors_add(sensor);
  260. } else {
  261. FURI_LOG_E(APP_NAME, "Failed sensor (%s:%s) mem allocation", name, type);
  262. }
  263. } else {
  264. FURI_LOG_E(APP_NAME, "Unsupported sensor name (%s) or sensor type (%s)", name, type);
  265. }
  266. //Вычисление конца строки
  267. line_end = furi_string_search_char(file, '\n', line_end + 1);
  268. }
  269. free(file_buf);
  270. file_stream_close(app->file_stream);
  271. stream_free(app->file_stream);
  272. FURI_LOG_I(APP_NAME, "Sensors have been successfully loaded");
  273. return true;
  274. }
  275. bool unitemp_sensors_save(void) {
  276. FURI_LOG_D(APP_NAME, "Saving sensors...");
  277. //Выделение памяти для потока
  278. app->file_stream = file_stream_alloc(app->storage);
  279. //Переменная пути к файлу
  280. FuriString* filepath = furi_string_alloc();
  281. //Составление пути к файлу
  282. furi_string_printf(filepath, "%s/%s", APP_PATH_FOLDER, APP_FILENAME_SENSORS);
  283. //Создание папки плагина
  284. storage_common_mkdir(app->storage, APP_PATH_FOLDER);
  285. //Открытие потока
  286. if(!file_stream_open(
  287. app->file_stream, furi_string_get_cstr(filepath), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS)) {
  288. FURI_LOG_E(
  289. APP_NAME,
  290. "An error occurred while saving the sensors file: %d",
  291. file_stream_get_error(app->file_stream));
  292. //Закрытие потока и освобождение памяти
  293. file_stream_close(app->file_stream);
  294. stream_free(app->file_stream);
  295. return false;
  296. }
  297. //Сохранение датчиков
  298. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  299. if(app->sensors[i]->type->interface == &SINGLE_WIRE) {
  300. stream_write_format(
  301. app->file_stream,
  302. "%s %s %d\n",
  303. app->sensors[i]->name,
  304. app->sensors[i]->type->typename,
  305. unitemp_singlewire_sensorGetGPIO(app->sensors[i])->num);
  306. }
  307. if(app->sensors[i]->type->interface == &I2C) {
  308. stream_write_format(
  309. app->file_stream,
  310. "%s %s %X\n",
  311. app->sensors[i]->name,
  312. app->sensors[i]->type->typename,
  313. ((I2CSensor*)app->sensors[i]->instance)->currentI2CAdr);
  314. }
  315. if(app->sensors[i]->type->interface == &ONE_WIRE) {
  316. stream_write_format(
  317. app->file_stream,
  318. "%s %s %d %02X%02X%02X%02X%02X%02X%02X%02X\n",
  319. app->sensors[i]->name,
  320. app->sensors[i]->type->typename,
  321. ((OneWireSensor*)app->sensors[i]->instance)->bus->gpio->num,
  322. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[0],
  323. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[1],
  324. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[2],
  325. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[3],
  326. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[4],
  327. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[5],
  328. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[6],
  329. ((OneWireSensor*)app->sensors[i]->instance)->deviceID[7]);
  330. }
  331. }
  332. //Закрытие потока и освобождение памяти
  333. file_stream_close(app->file_stream);
  334. stream_free(app->file_stream);
  335. FURI_LOG_I(APP_NAME, "Sensors have been successfully saved");
  336. return true;
  337. }
  338. void unitemp_sensors_reload(void) {
  339. unitemp_sensors_deInit();
  340. unitemp_sensors_free();
  341. unitemp_sensors_load();
  342. unitemp_sensors_init();
  343. }
  344. bool unitemp_sensor_isContains(Sensor* sensor) {
  345. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  346. if(app->sensors[i] == sensor) return true;
  347. }
  348. return false;
  349. }
  350. Sensor* unitemp_sensor_alloc(char* name, const SensorType* type, char* args) {
  351. if(name == NULL || type == NULL) return NULL;
  352. bool status = false;
  353. //Выделение памяти под датчик
  354. Sensor* sensor = malloc(sizeof(Sensor));
  355. if(sensor == NULL) {
  356. FURI_LOG_E(APP_NAME, "Sensor %s allocation error", name);
  357. return false;
  358. }
  359. //Выделение памяти под имя
  360. sensor->name = malloc(11);
  361. if(sensor->name == NULL) {
  362. FURI_LOG_E(APP_NAME, "Sensor %s name allocation error", name);
  363. return false;
  364. }
  365. //Запись имени датчка
  366. strcpy(sensor->name, name);
  367. //Тип датчика
  368. sensor->type = type;
  369. //Статус датчика по умолчанию - ошибка
  370. sensor->status = UT_ERROR;
  371. //Время последнего опроса
  372. sensor->lastPollingTime =
  373. furi_get_tick() - 10000; //чтобы первый опрос произошёл как можно раньше
  374. sensor->temp = -128.0f;
  375. sensor->hum = -128.0f;
  376. sensor->pressure = -128.0f;
  377. //Выделение памяти под инстанс датчика в зависимости от его интерфейса
  378. status = sensor->type->interface->allocator(sensor, args);
  379. //Выход если датчик успешно развёрнут
  380. if(status) {
  381. FURI_LOG_I(APP_NAME, "Sensor %s allocated", name);
  382. return sensor;
  383. }
  384. //Если ни один из типов не подошёл, то выход с очисткой
  385. free(sensor->name);
  386. free(sensor);
  387. FURI_LOG_E(APP_NAME, "Sensor %s type is unsupported: %s", name, type->typename);
  388. return NULL;
  389. }
  390. void unitemp_sensor_free(Sensor* sensor) {
  391. if(sensor == NULL) {
  392. FURI_LOG_E(APP_NAME, "Null pointer sensor releasing");
  393. return;
  394. }
  395. if(sensor->type == NULL) {
  396. FURI_LOG_E(APP_NAME, "Sensor type is null");
  397. return;
  398. }
  399. if(sensor->type->mem_releaser == NULL) {
  400. FURI_LOG_E(APP_NAME, "Sensor releaser is null");
  401. return;
  402. }
  403. bool status = false;
  404. //Высвобождение памяти под инстанс
  405. status = sensor->type->interface->mem_releaser(sensor);
  406. if(status) {
  407. FURI_LOG_D(APP_NAME, "Sensor %s memory successfully released", sensor->name);
  408. } else {
  409. FURI_LOG_E(APP_NAME, "Sensor %s memory is not released", sensor->name);
  410. }
  411. free(sensor->name);
  412. //free(sensor);
  413. }
  414. void unitemp_sensors_free(void) {
  415. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  416. unitemp_sensor_free(app->sensors[i]);
  417. }
  418. app->sensors_count = 0;
  419. }
  420. bool unitemp_sensors_init(void) {
  421. bool result = true;
  422. //Перебор датчиков из списка
  423. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  424. //Включение 5V если на порту 1 FZ его нет
  425. //Может пропасть при отключении USB
  426. if(furi_hal_power_is_otg_enabled() != true) {
  427. furi_hal_power_enable_otg();
  428. FURI_LOG_D(APP_NAME, "OTG enabled");
  429. }
  430. if(!(*app->sensors[i]->type->initializer)(app->sensors[i])) {
  431. FURI_LOG_E(
  432. APP_NAME,
  433. "An error occurred during sensor initialization %s",
  434. app->sensors[i]->name);
  435. result = false;
  436. }
  437. FURI_LOG_D(APP_NAME, "Sensor %s successfully initialized", app->sensors[i]->name);
  438. }
  439. app->sensors_ready = true;
  440. return result;
  441. }
  442. bool unitemp_sensors_deInit(void) {
  443. bool result = true;
  444. //Выключение 5 В если до этого оно не было включено
  445. if(app->settings.lastOTGState != true) {
  446. furi_hal_power_disable_otg();
  447. FURI_LOG_D(APP_NAME, "OTG disabled");
  448. }
  449. //Перебор датчиков из списка
  450. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  451. if(!(*app->sensors[i]->type->deinitializer)(app->sensors[i])) {
  452. FURI_LOG_E(
  453. APP_NAME,
  454. "An error occurred during sensor deinitialization %s",
  455. app->sensors[i]->name);
  456. result = false;
  457. }
  458. }
  459. return result;
  460. }
  461. UnitempStatus unitemp_sensor_updateData(Sensor* sensor) {
  462. if(sensor == NULL) return UT_ERROR;
  463. //Проверка на допустимость опроса датчика
  464. if(furi_get_tick() - sensor->lastPollingTime < sensor->type->pollingInterval) {
  465. //Возврат ошибки если последний опрос датчика был неудачным
  466. if(sensor->status == UT_TIMEOUT) {
  467. return UT_TIMEOUT;
  468. }
  469. return UT_EARLYPOOL;
  470. }
  471. sensor->lastPollingTime = furi_get_tick();
  472. if(!furi_hal_power_is_otg_enabled()) {
  473. furi_hal_power_enable_otg();
  474. }
  475. sensor->status = sensor->type->interface->updater(sensor);
  476. FURI_LOG_D(APP_NAME, "Sensor %s update status %d", sensor->name, sensor->status);
  477. if(app->settings.unit == FAHRENHEIT && sensor->status == UT_OK)
  478. uintemp_celsiumToFarengate(sensor);
  479. if(sensor->status == UT_OK) {
  480. unitemp_pascalToMmHg(sensor);
  481. }
  482. return sensor->status;
  483. }
  484. void unitemp_sensors_updateValues(void) {
  485. for(uint8_t i = 0; i < unitemp_sensors_getCount(); i++) {
  486. unitemp_sensor_updateData(app->sensors[i]);
  487. }
  488. }