How to get battery info from device

Hi. I am trying to make a device handler which will retrieve the battery percentage from a device and I wanted to know how to do this. My device sends a reports attribute, “battery percentage” to the Smartthings hub every few seconds, but I just need a way to get it showing on the app. I’d really appreciate any help to get this working.

You simply need a capability/tile/event management you can copy paste from any device implementation in the public smartthing GitHub like: https://github.com/philippeportesppo/SmartThingsPublic/blob/master/devicetypes/smartthings/arrival-sensor.src/arrival-sensor.groovy

  1. Capability
    capability “Battery”

  2. Tile
    valueTile(“battery”, “device.battery”, decoration: “flat”, inactiveLabel: false) {

     	state "battery", label:'${currentValue}% battery', unit:""
    
  3. Message:

      def parse(String description) {
     	def results
    
     if (isBatteryMessage(description)) {
    
     	results = parseBatteryMessage(description)
    
     }
     else: // your stuff
    
     }
    
    
     private Boolean isBatteryMessage(String description) {
    
     // "raw:36EF1C, dni:36EF, battery:1B, rssi:, lqi:"
    
     description ==~ /.*battery:.*rssi:.*lqi:.*/
    

    }

    private List parseBatteryMessage(String description) {

     def results = []
    
     def parts = description.split(',')
    
     parts.each { part ->
    
     	part = part.trim()
    
     	if (part.startsWith('battery:')) {
    
     		def batteryResult = getBatteryResult(part, description)
    
     		if (batteryResult) {
    
     			results << batteryResult
    
     		}
    
     	}
    
     	else if (part.startsWith('rssi:')) {
    
     		def rssiResult = getRssiResult(part, description)
    
     		if (rssiResult) {
    
     			results << rssiResult
    
     		}
    
     	}
    
     	else if (part.startsWith('lqi:')) {
    
     		def lqiResult = getLqiResult(part, description)
    
     		if (lqiResult) {
    
     			results << lqiResult
    
     		}
    
     	}
    
     }
    
    
    
     results
     }
    

Hope it helps. Of course if you directly have the measure for the battery, you can simplify the isBatteryMessage and parseBatteryMessage, even suppress them…

1 Like