Code by Scott שאול בן ישוע
Raspberry-Pi-DHT-Sensor.groovy 11.5 KB
Newer Older
Sha'ul ben Yeshua's avatar
Sha'ul ben Yeshua committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 *  Raspberry Pi DHT11/22 Sensor
 *
 *  Copyright Scott Grayban
 *
 *  Monitor your Raspberry Pi using SmartThings and Raspberry Pi Monitor <https://github.com/sgrayban/raspberrypi.monitor>
 *
 *  Copyright 2019 Scott Grayban
 *
 * Please Note: This app is NOT released under any open-source license.
 * Please be sure to read the license agreement before installing this code.
 *
 * This software package is created and licensed by Scott Grayban.
 *
 * This software, along with associated elements, including but not limited to online and/or electronic documentation are
 * protected by international laws and treaties governing intellectual property rights.
 *
 * This software has been licensed to you. All rights are reserved. You may use and/or modify the software.
 * You may not sublicense or distribute this software or any modifications to third parties in any way.
 *
 * You may not distribute any part of this software without the author's express permission
 *
 * By downloading, installing, and/or executing this software you hereby agree to the terms and conditions set forth
 * in the Software license agreement.
 * This agreement can be found on-line at: https://sgrayban.github.io/Hubitat-Public/software_License_Agreement.txt
 * 
 * Hubitat is the Trademark and intellectual Property of Hubitat Inc.
 * Shelly is the Trademark and Intellectual Property of Allterco Robotics Ltd
 * Scott Grayban has no formal or informal affiliations or relationships with Hubitat or Allterco Robotics Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License Agreement
 * for the specific language governing permissions and limitations under the License.
 *
 *-------------------------------------------------------------------------------------------------------------------
 *
 *  Changes:
 *
 *   2.0.0 - License change -- Personal Use Only
 *   1.0.1 - Changed behavour of refresh rate
 *   1.0.0 - Initial release
 *
 */

import groovy.json.*

metadata {
        definition (
			name: "Raspberry Pi DHT11/22 Sensor",
			namespace: "sgrayban",
			author: "Scott Grayban",
Sha'ul ben Yeshua's avatar
Sha'ul ben Yeshua committed
52
			importUrl: "http://sgrayban.borgnet.online:8081/raspberrypi.monitor/Raspberry-Pi-DHT-Sensor.groovy"
Sha'ul ben Yeshua's avatar
Sha'ul ben Yeshua committed
53
		)
Sha'ul ben Yeshua's avatar
Sha'ul ben Yeshua committed
54
55
56
57
58
59
60
61
62
63
64
65
66

preferences {
                input("ip", "string", title:"IP Address", description: "Rpi IP", defaultValue: "" ,required: true, displayDuringSetup: true)
                input("port", "string", title:"Port", description: "8080", defaultValue: "8080" , required: true, displayDuringSetup: true)
                input "refreshEvery", "enum", title: "Enable auto refresh every XX Minutes", required: false, defaultValue: false, //RK
                                options: [5:"5 minutes",10:"10 minutes",15:"15 minutes",30:"30 minutes"] //RK
                input "locale", "enum", title: "Choose refresh date format", required: true, defaultValue: true, //RK
                                options: [US:"US MM/DD/YYYY",UK:"UK DD/MM/YYYY"] //RK
                input name: "debugOutput", type: "bool", title: "Enable debug logging?", defaultValue: true
                input name: "txtEnable", type: "bool", title: "Enable descriptionText logging", defaultValue: true //RK
}


Sha'ul ben Yeshua's avatar
Sha'ul ben Yeshua committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
	{
    capability "Temperature Measurement"
    capability "Polling"
    capability "Refresh"
    capability "Sensor"

	attribute "temperature", "number"
	attribute "humidity", "number"
	attribute "DriverVersion", "string"
	attribute "DriverAuthor", "string"
	attribute "DriverStatus", "string"
	attribute "LastRefresh", "string"

	}
                main(["temperature"])
                details(["temperature", "humidity", "refresh"])
}

def installed() {
		log.debug "Device installed"
		initialize();
}

// App Version   *********************************************************************************
def setVersion(){
	state.Version = "2.0.0"
	state.InternalName = "RaspberryPiDHTStats"

	sendEvent(name: "DriverAuthor", value: "sgrayban")
	sendEvent(name: "DriverVersion", value: state.Version)
	sendEvent(name: "DriverStatus", value: state.Status)
}

def updated() {
    log.debug "Updated"
    log.info "Preferences updated..."
    log.warn "Debug logging is: ${debugOutput == true}"
    unschedule()
    // RK start
    if (refreshEvery != null) {
    "runEvery${refreshEvery}Minutes"(autorefresh)
    log.info "Refresh set for every ${refreshEvery} Minutes"
    } else {
    runEvery30Minutes (autorefresh)
    log.info "Refresh set for every 30 Minutes"
    }
    if (debugOutput) runIn(1800,logsOff)
    state.LastRefresh = new Date().format("YYYY/MM/dd \n HH:mm:ss", location.timeZone)
    // RK stop
    version()
    initialized();
}

def ping() {
	debugOutput "ping"
	poll()
}

def initialize() {
	log.info "App initialize"
	if (txtEnable) log.info "App initialize" //RK
	refresh()
}

def logsOff(){
	log.warn "debug logging auto disabled..."
	device.updateSetting("debugOutput",[value:"false",type:"bool"])
}

// parse events into attributes
def parse(description) {
        logDebug "Parsing '${description}'"

        def msg = parseLanMessage(description)
        def headerString = msg.header
        def bodyString   = msg.body

        logDebug "received body:\n${bodyString}"

        if(bodyString.trim() == "ok")
        return

        def json = null;
        try{
        json = new groovy.json.JsonSlurper().parseText(bodyString)
               log.debug  "${json}"

                if(json == null){
        logDebug "body object not parsed"
                        return
                }
        }
        catch(e){
        log.error("Failed to parse json e = ${e}")
                return
        }

        logDebug "JSON '${json}'"

		sendEvent(name: "temperature", value: json.temperature)
		sendEvent(name: "humidity", value: json.humidity)
}

// handle commands
def poll() {
	if (locale == "UK") {
	if (debugOutput) log.info "Get last UK Date DD/MM/YYYY"
	state.LastRefresh = new Date().format("d/MM/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	} 
	if (locale == "US") {
	if (debugOutput) log.info "Get last US Date MM/DD/YYYY"
	state.LastRefresh = new Date().format("MM/d/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	}
	if (txtEnable) log.info "Executing 'poll'" //RK
    getTemp()
}

def refresh() {
	if (locale == "UK") {
	if (debugOutput) log.info "Get last UK Date DD/MM/YYYY"
	state.LastRefresh = new Date().format("d/MM/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	} 
	if (locale == "US") {
	if (debugOutput) log.info "Get last US Date MM/DD/YYYY"
	state.LastRefresh = new Date().format("MM/d/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	}
	if (txtEnable) log.info "Executing 'manual refresh'" //RK
    getTemp()
}

def autorefresh() {
	if (locale == "UK") {
	if (debugOutput) log.info "Get last UK Date DD/MM/YYYY"
	state.LastRefresh = new Date().format("d/MM/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	} 
	if (locale == "US") {
	if (debugOutput) log.info "Get last US Date MM/DD/YYYY"
	state.LastRefresh = new Date().format("MM/d/YYYY \n HH:mm:ss", location.timeZone)
	sendEvent(name: "LastRefresh", value: state.LastRefresh, descriptionText: "Last refresh performed")
	}
	if (txtEnable) log.info "Executing 'auto refresh'" //RK
	getTemp()

}
//RK Last Refresh End

private getTemp() {
	def iphex = convertIPtoHex(ip)
    def porthex = convertPortToHex(port)

    def uri = "/api/dht"
    def headers=[:]
    headers.put("HOST", "${ip}:${port}")
    headers.put("Accept", "application/json")

	def hubAction = new hubitat.device.HubAction
	(
        method: "GET",
        path: uri,
                headers: headers,
        "${ipHex}:${portHex}",
        [callback: parse]
    )
	logDebug "Getting Pi data ${hubAction}"
	hubAction 
}

private String convertIPtoHex(ipAddress) {
        log.debug "convertIPtoHex ${ipAddress} to hex"
    String hex = ipAddress.tokenize( '.' ).collect {  String.format( '%02x', it.toInteger() ) }.join()
    return hex
}

private String convertPortToHex(port) {
        log.debug "convertPortToHex ${port} to hex"
        String hexport = port.toString().format( '%04x', port.toInteger() )
    return hexport
}

def sync(ip, port) {
	logDebug "sync ${ip} ${port}"
	def existingIp = getDataValue("ip")
	def existingPort = getDataValue("port")
	if (ip && ip != existingIp) {
		updateDataValue("ip", ip)
	}
	if (port && port != existingPort) {
		updateDataValue("port", port)
	}
	def ipHex = convertIPToHex(ip)
	def portHex = convertPortToHex(port)
	device.deviceNetworkId = "${ipHex}:${portHex}"
}

private logDebug(msg) {
	if (settings?.debugOutput || settings?.debugOutput == null) {
	log.debug "$msg"
	}
}

private dbCleanUp() {
	unschedule()
	state.remove("version")
	state.remove("Version")
}

// Check Version   ***** with great thanks and acknowlegment to Cobra (github CobraVmax) for his original code **************
def version(){
	updatecheck()
	schedule("0 0 18 1/1 * ? *", updatecheck) // Cron schedule
//	schedule("0 0/1 * 1/1 * ? *", updatecheck) // Test Cron schedule
}

def updatecheck(){
	setVersion()
	 def paramsUD = [uri: "https://sgrayban.github.io/Hubitat-Public/version.json"]
	  try {
			httpGet(paramsUD) { respUD ->
				  if (txtEnable) log.warn " Version Checking - Response Data: ${respUD.data}"   // Troubleshooting Debug Code - Uncommenting this line should show the JSON response from your webserver
				  def copyrightRead = (respUD.data.copyright)
				  state.Copyright = copyrightRead
				  def newVerRaw = (respUD.data.versions.Driver.(state.InternalName))
				  def newVer = (respUD.data.versions.Driver.(state.InternalName).replace(".", ""))
				  def currentVer = state.Version.replace(".", "")
				  state.UpdateInfo = (respUD.data.versions.UpdateInfo.Driver.(state.InternalName))
				  state.author = (respUD.data.author)
				  state.icon = (respUD.data.icon)
				  if(newVer == "NLS"){
					   state.Status = "<b>** This driver is no longer supported by $state.author  **</b>"       
					   log.warn "** This driver is no longer supported by $state.author **"      
				  }           
				  else if(currentVer < newVer){
					   state.Status = "<b>New Version Available (Version: $newVerRaw)</b>"
					   log.warn "** There is a newer version of this driver available  (Version: $newVerRaw) **"
					   log.warn "** $state.UpdateInfo **"
				 } 
				 else if(currentVer > newVer){
					   state.Status = "<b>You are using a Test version of this Driver (Version: $newVerRaw)</b>"
				 }
				 else{ 
					 state.Status = "Current"
					 log.info "You are using the current version of this driver"
				 }
			} // httpGet
	  } // try

	  catch (e) {
		   log.error "Something went wrong: CHECK THE JSON FILE AND IT'S URI -  $e"
	  }

	  if(state.Status == "Current"){
		   state.UpdateInfo = "Up to date"
		   sendEvent(name: "DriverUpdate", value: state.UpdateInfo)
		   sendEvent(name: "DriverStatus", value: state.Status)
	  }
	  else {
		   sendEvent(name: "DriverUpdate", value: state.UpdateInfo)
		   sendEvent(name: "DriverStatus", value: state.Status)
	  }

	  sendEvent(name: "DriverAuthor", value: "sgrayban")
	  sendEvent(name: "DriverVersion", value: state.Version)
}