battery.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. function voltage_to_percentage(voltage)
  2. local min_voltage = 3600
  3. local max_voltage = 4190
  4. if voltage <= min_voltage then
  5. return 0
  6. elseif voltage >= max_voltage then
  7. return 100
  8. else
  9. local percentage = (voltage - min_voltage) / (max_voltage - min_voltage) * 100
  10. return math.floor(percentage + 0.5) -- 四舍五入
  11. end
  12. end
  13. adc.open(adc.CH_VBAT)
  14. sys.taskInit(function ()
  15. repeat
  16. local voltage = adc.get(adc.CH_VBAT)
  17. local percentage = voltage_to_percentage(voltage)
  18. log.info("battery", "voltage:", voltage, "percentage:", percentage)
  19. --低于3.3V时,关机
  20. if voltage < 3300 then
  21. pm.shutdown()
  22. end
  23. attributes.set("battery", percentage)
  24. attributes.set("vbat", voltage)
  25. sys.wait(60000)
  26. until nil
  27. end)
  28. --充电状态检测
  29. local function chargeCheck()
  30. log.info("chargeCheck", gpio.get(42))
  31. attributes.set("isCharging", gpio.get(42) == 0)
  32. end
  33. gpio.setup(42, chargeCheck, 0, gpio.BOTH)
  34. attributes.set("isCharging", gpio.get(42) == 0)
  35. local function exitSleepMode()
  36. pm.power(pm.WORK_MODE, 0)--退出休眠模式
  37. --上报所有参数
  38. sys.timerStart(attributes.setAll, 6000)
  39. --重启一下
  40. --pm.reboot()
  41. end
  42. sys.subscribe("SLEEP_CMD_RECEIVED", function(on)
  43. if on then
  44. log.info("battery","enter sleepMode wait")
  45. pm.power(pm.WORK_MODE, 1)--进入休眠模式
  46. else
  47. log.info("battery","exit sleepMode wait")
  48. exitSleepMode()
  49. end
  50. end)
  51. sys.subscribe("POWERKEY_PRESSED", function()
  52. log.info("battery","POWERKEY_PRESSED")
  53. if attributes.get("sleepMode") then
  54. attributes.set("sleepMode", false, true)
  55. sys.publish("SLEEP_CMD_RECEIVED", false)
  56. end
  57. end)