Update turn-on-before-sunset.groovy
[smartapps.git] / third-party / BatteryLow.groovy
1 /**
2  *  Low Battery Notification
3  *
4  */
5
6 definition(
7     name: "Battery Low",
8     namespace: "com.sudarkoff",
9     author: "George Sudarkoff",
10     description: "Notify when battery charge drops below the specified level.",
11     category: "Convenience",
12     iconUrl: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience.png",
13     iconX2Url: "https://s3.amazonaws.com/smartapp-icons/Convenience/Cat-Convenience%402x.png"
14 )
15
16 preferences {
17     section ("When battery change in these devices") {
18         input "devices", "capability.battery", title:"Battery Operated Devices", multiple: true
19     }
20     section ("Drops below this level") {
21         input "level", "number", title:"Battery Level (%)"
22     }
23     section ("Notify") {
24         input "sendPushMessage", "bool", title: "Send a push notification?", required: false
25         input "phone", "phone", title: "Send a Text Message?", required: false
26     }
27 }
28
29 def installed() {
30     initialize()
31 }
32
33 def updated() {
34     unsubscribe()
35     initialize()
36 }
37
38 def initialize() {
39     if (level < 5 || level > 90) {
40         sendPush("Battery level should be between 5 and 90 percent")
41         return false
42     }
43     subscribe(devices, "battery", batteryHandler)
44
45     state.lowBattNoticeSent = [:]
46     updateBatteryStatus()
47 }
48
49 def batteryHandler(evt) {
50     updateBatteryStatus()
51 }
52
53 private send(message) {
54     if (phone) {
55         sendSms(phone, message)
56     }
57     if (sendPushMessage) {
58         sendPush(message)
59     }
60 }
61
62 private updateBatteryStatus() {
63     for (device in devices) {
64         if (device.currentBattery < level) {
65             if (!state.lowBattNoticeSent.containsKey(device.id)) {
66                 send("${device.displayName}'s battery is at ${device.currentBattery}%.")
67             }
68             state.lowBattNoticeSent[(device.id)] = true
69         }
70         else {
71             if (state.lowBattNoticeSent.containsKey(device.id)) {
72                 state.lowBattNoticeSent.remove(device.id)
73             }
74         }
75     }
76 }
77