power.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "plt.h"
  2. #define DEV_PATH "/sys/class/gpio/gpio129/value" // 输入输出电平值设备
  3. #define EXPORT_PATH "/sys/class/gpio/export" // GPIO设备导出设备
  4. #define DIRECT_PATH "/sys/class/gpio/gpio129/direction" // GPIO输入输出控制设备
  5. #define IN "in"
  6. #define GPIO "129" // GPIO5_1
  7. int fd_dev, fd_export, fd_dir, ret;
  8. int device_power_on = 1;
  9. int power_detection_init()
  10. {
  11. char buf[10];
  12. fd_export = open(EXPORT_PATH, O_WRONLY); // 打开GPIO设备导出设备
  13. if (fd_export < 0)
  14. {
  15. perror("open export:");
  16. return -1;
  17. }
  18. write(fd_export, GPIO, strlen(GPIO));
  19. fd_dev = open(DEV_PATH, O_RDWR); // 打开输入输出电平值设备
  20. if (fd_dev < 0)
  21. {
  22. perror("open gpio:");
  23. return -1;
  24. }
  25. fd_dir = open(DIRECT_PATH, O_RDWR); // 打开GPIO输入输出控制设备
  26. if (fd_dir < 0)
  27. {
  28. perror("open direction:");
  29. return -1;
  30. }
  31. strcpy(buf, IN);
  32. ret = write(fd_dir, buf, strlen(IN));
  33. if (ret < 0)
  34. {
  35. perror("write direction:");
  36. close(fd_export);
  37. close(fd_dir);
  38. close(fd_dev);
  39. return -1;
  40. }
  41. return 0;
  42. }
  43. int power_detection_exe()
  44. {
  45. static char last[10] = {0};
  46. static char buf[10] = {0};
  47. memset(buf, 0, sizeof(buf));
  48. lseek(fd_dev, 0, SEEK_SET);
  49. ret = read(fd_dev, buf, sizeof(buf)); // 读取GPIO5_1输入电平值
  50. if (ret < 0)
  51. {
  52. log_dbg("ERROR : failed to read power on/off detection");
  53. // close(fd_export);
  54. // close(fd_dir);
  55. // close(fd_dev);
  56. // return -1;
  57. }
  58. else
  59. {
  60. if (buf[0] == '1')
  61. {
  62. if (strcmp(buf, last) != 0)
  63. {
  64. strcpy(last, buf);
  65. tb_send_telemetry("power:1");
  66. log_dbg("Power on");
  67. }
  68. device_power_on = 1;
  69. }
  70. else
  71. {
  72. if (strcmp(buf, last) != 0)
  73. {
  74. strcpy(last, buf);
  75. tb_send_telemetry("power:0");
  76. log_dbg("Power off");
  77. }
  78. device_power_on = 0;
  79. }
  80. }
  81. }