Imports System.Diagnostics
Imports System.Threading.Tasks
Imports System.Collections.Generic
Dim dryList As New List(Of String)()
Dim leakList As New List(Of String)()
Dim lockObj As New Object()
Dim debug As Boolean = False
Dim sw As Stopwatch = Stopwatch.StartNew()
Dim waterSensors As List(Of Scheduler.Classes.DeviceClass) = GetWaterSensors()
If debug Then hs.WriteLog("DEBUG", "Number of water sensors: " & waterSensors.Count)
Parallel.ForEach(waterSensors, Sub(dv)
If dv Is Nothing Then Return
Dim statusText As String = hs.DeviceString(dv.Ref(Nothing)).Trim().ToLower()
If debug Then hs.WriteLog("DEBUG", "Device: " & dv.Name(Nothing) & ", Status: " & statusText)
If statusText.Contains("dry") Then
dryList.Add(dv.Location(Nothing) & " " & dv.Name(Nothing) & ", <Br>")
ElseIf statusText.Contains("leak") Or statusText.Contains("water leak detected") Then
leakList.Add(dv.Location(Nothing) & " " & dv.Name(Nothing))
hs.WriteLog("WATER LEAK", "Leak detected at " & dv.Location(Nothing) & " " & dv.Name(Nothing) & " at " & DateTime.Now.ToString())
hs.WriteLog("ERROR", "Exception in Parallel.ForEach: " & ex.Message)
Dim Dry As String = String.Join("", dryList)
If Dry.EndsWith(", <Br>") Then Dry = Dry.Substring(0, Dry.Length - 6)
Dim Leak As String = String.Join(", ", leakList)
Dim current766Val As Integer = hs.DeviceValue(766)
Dim lastChange766 As DateTime = hs.DeviceLastChange(766)
hs.SetDeviceString(562, "Water Leak Detected at " & Leak, True)
hs.SetDeviceValueByRef(562, 255, True)
If current766Val <> 100 OrElse (DateTime.Now - lastChange766).TotalSeconds > 30 Then
hs.SetDeviceValueByRef(766, 100, True)
hs.URLAction("http://192.168.1.177:8123/api/webhook/water_leak_detected", "GET", "", "Content-Type: application/x-www-form-urlenc")
hs.SetDeviceString(562, "No Water Leaks Detected at <BR><BR>" & Dry, True)
hs.SetDeviceValueByRef(562, 0, True)
If current766Val <> 0 OrElse (DateTime.Now - lastChange766).TotalSeconds > 30 Then
hs.SetDeviceValueByRef(766, 0, True)
hs.WriteLog("Status", "No water leaks detected at " & DateTime.Now.ToString())
If debug Then hs.WriteLog("DEBUG", "No water leaks detected at " & DateTime.Now.ToString())
If debug Then hs.WriteLog("Script", "Script execution time: " & sw.Elapsed.TotalMilliseconds & " ms")
Catch ex As ArgumentNullException
hs.WriteLog("ERROR: Water Leak - ArgumentNullException", ex.Message)
Catch ex As InvalidOperationException
hs.WriteLog("ERROR: Water Leak - InvalidOperationException", ex.Message)
hs.WriteLog("ERROR: Water Leak - General Exception", ex.Message)
Function GetWaterSensors() As List(Of Scheduler.Classes.DeviceClass)
Dim col As New List(Of Scheduler.Classes.DeviceClass)
Dim dv As Scheduler.Classes.DeviceClass
Dim EN As Scheduler.Classes.clsDeviceEnumeration = hs.GetDeviceEnumerator
If dv Is Nothing Then Continue Do
If dv.Location2(Nothing) = "Water Sensor" Then
hs.WriteLog("ERROR: GetWaterSensors", ex.Message)