Code Help - schedule for dehumidifier


(Cesare Pagani) #1

Hi there,
I am pretty new to SmartThings. I created below smart app doing some copy and paste from other users smart apps.

The idea behind this smart app is to turn on a Dehumidifier, connected to a smart switch, if the humidity from a sensor exceed a certain value. Thereafter turn it off when the humidity goes below a lower humidity value. This is because I do not want the Dehumidifier keeping on going on and off every hour around a single humidity value but I want it to “suck” humidity away up to a lower value so that it will take longer to reach the high humidity value and start the Dehumidifier again.

So far so good. The app is working (although probably is not perfectly written).

Now, to save on the energy bills, I would like to ensure that the dehumidifier goes on if the humidity is above a certain value but only with-in a specific time of the day (my plan is to get the dehumidifier going only at night between 2AM and 6AM when electricity is cheaper in my area).

I put in the start time and the end time but I have no idea how to create the event handler and other items needed to work.

Here below is the code. Any help?

/**
 *  SMART Dehumidifier
 *  Date: 2015-05-14
 */

definition(   
    name: "SMART Dehumidifier",
    namespace: "SMART-D",
    author: "CMP",
    description: "When the humidity level goes above a certain value, turn on a switched dehumidifier. When that value drops below a separate threshold, turn off the dehumidifier.",
    category: "Convenience",
    iconUrl: "https://graph.api.smartthings.com/api/devices/icons/st.Weather.weather12-icn",
    iconX2Url: "https://graph.api.smartthings.com/api/devices/icons/st.Weather.weather12-icn?displaySize=2x"
)

preferences 
{
	section("Monitor the humidity...")
	{
		input "humiditySensor1", "capability.relativeHumidityMeasurement", title: "Humidity Sensor?", required: true
    }    
	section("Choose a Switch that controls a dehumidifier...")
	{
		input "fanSwitch1", "capability.switch", title: "Dehumidifier Location?", required: true
    }
    section("Turn dehumidifier on when the humidity is above:") 
	{
		input "humidityUP", "number", title: "Humidity Upper Threshold (%)?"
	}
    section("Turn dehumidifier off when the humidity returns below:") 
	{
		input "humidityDW", "number", title: "Humidity Lower Threshold (%)?"
	}
    	section("Turn on only during this timeframe")
	{
		input "starting", "time", title: "Start time", required: true
		input "ending", "time", title: "End time", required: true
    }
    	section("Send this message (optional, sends standard status message if not specified)")
	{
		input "messageText", "text", title: "Message Text", required: false
	}
	section("Via a push notification and/or an SMS message")
	{
        	input("recipients", "contact", title: "Send notifications to") 
		{
        		input "pushAndPhone", "enum", title: "Both Push and SMS?", required: false, options: ["Yes", "No"]
        		input "phone", "phone", title: "Main Phone Number (use sign + for country code)", required: true             
    	}
	}
}

def installed() 
{
	subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Installed with settings: ${settings}"
}

def updated() 
{
	unsubscribe()
    subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Updated with settings: ${settings}"
}

def humidityHandler(evt) 
{
	log.debug "Humidity: $evt.value, $evt.unit, $evt.name, $evt"
    def humNum = Double.parseDouble(evt.value.replace("%", ""))
	def tooHumidNum = humidityUP
    double tooHumid = tooHumidNum
    def OKHumidNum = humidityDW
    double OKHumid = OKHumidNum
    def mySwitch = settings.fanSwitch1
	log.debug "Current Humidity: $humNum, Humidity Setting: $tooHumid"
	def msg = messageText ?: defaultText(evt)
   	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg'"
    
    
// ********************************************************************** def time interval *****************************************************
    
    
	if (humNum >= tooHumid) 
	{
        	
// ********************************************************************** def if time is between x and y *****************************************************       
            
            log.debug "Humidity is very high"
        	if ( fanSwitch1.currentValue("switch") == "off" ) 
			{
				if (location.contactBookEnabled) 
				{
        			sendNotificationToContacts(msg, recipients)
    			}
    			else 
				{
        			if (!phone || pushAndPhone != "No") 
					{
            				log.debug "sending push"
            				sendPush(msg)
        			}
        			if (phone) 
					{
            				log.debug "sending SMS"
            				sendSms(phone, msg)
        			}
    			}
 			fanSwitch1.on()   
        	}
    } 
	else 
	{
 		if (humNum <= OKHumid) 
		{ 
			log.debug "Humidity is back to normal"
        		if ( fanSwitch1.currentValue("switch") == "on" ) 
				{
					if (location.contactBookEnabled) 
					{
        				sendNotificationToContacts("Humidity is back to normal", recipients)
    				}
    				else 
					{
						if (!phone || pushAndPhone != "No") 
						{
            					log.debug "sending push"
            					sendPush("Humidity is back to normal")
        				}
        				if (phone) 
						{
            				log.debug "sending SMS"
            				sendSms(phone, "Humidity is back to normal")
        				}
    				}
     				fanSwitch1.off()   
        		}
    	}    
  	}
}

(Patrick Stuart [@pstuart]) #2

I would love to help, but any chance you can either post the code to a github repo or re-post it in a “preformatted” text block? the </> button in the editor?

If I understand your question, you are looking for a code example or help on testing if the humidityHandler is firing between x and y time.

Couple of things to note, in the docs, the input type of “Time” creates a new datetime value of that next time.

So, you just need to compare the server time to that start or end time to find out if you are inside that time window to allow the event to run.

There are several good smartapp examples in the code library in the IDE that will help you with the next step. Let me know if you don’t know how to browse that, but its in the upper right corner of the IDE.

Take a look at the Good Night code example for one of many ways to check if the time is within the input time.

There are a lot of other ways to do this, some more appropriate for this case the others.

I’ve been struggling with time input, since it creates that datetime element. Personally it would be a lot easier to just get an hour and minute segment and then just get local hub time and compare. Still working on that, but since we can’t constraint input, validation become a bit more of an issue requiring dynamic pages.


(ActionTiles.com co-founder Terry @ActionTiles; GitHub: @cosmicpuppy) #3

:+1:

Or use triple back quote. BTW:: Markdown actually allows you to specify a language name so it can attempt to do some pretty formatting, but it doesn’t help much with groovy.

Like this:

// iterate over a map
def map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
    x += e.value
}

(Cesare Pagani) #4

Thanks guys, I already learned somethin new :wink:


(Cesare Pagani) #5

Thanks Patrick,
I has a look at the shared smart apps but failed to really grasp how this works. Anyway, now that you put me in the right direction, i will have a look at Good Night code and see if I can figure out how it works.

Your understanding of my request is correct.

Cheers Cesare


(Tony - SmartThings Unpublished Contributor ) #6

Cesare-

If you want to limit the code to only run during the specified time interval, try this.

  1. place the getTimeOK check around the code you want to limit:

    if ( getTimeOK() {

    [CODE TO BE LIMITED]

    }

  2. Then add the getTimeOK() function to your smartapp:

    private getTimeOk() {
    def result = true
    if (starting && ending) {
    def currTime = now()
    def start = timeToday(starting).time
    def stop = timeToday(ending).time
    result = start < stop ? currTime >= start && currTime <= stop : currTime <= stop || currTime >= start
    }
    log.trace "timeOk = $result"
    result
    }

Here’s where I think it should go in your existing code:

/**
* SMART Dehumidifier
* Author: CM PAGANI
* Date: 2015-05-14
*/

definition(   
    name: "SMART Dehumidifier",
    namespace: "SMART-D",
    author: "CMPAGANI",
    description: "When the humidity level goes above a certain value, turn on a switched dehumidifier. When that value drops below a separate threshold, turn off the dehumidifier.",
    category: "Convenience",
    iconUrl: "https://graph.api.smartthings.com/api/devices/icons/st.Weather.weather12-icn",
    iconX2Url: "https://graph.api.smartthings.com/api/devices/icons/st.Weather.weather12-icn?displaySize=2x"
)

preferences 
{
	section("Monitor the humidity...")
	{
		input "humiditySensor1", "capability.relativeHumidityMeasurement", title: "Humidity Sensor?", required: true
    }    
	section("Choose a Switch that controls a dehumidifier...")
	{
		input "fanSwitch1", "capability.switch", title: "Dehumidifier Location?", required: true
    }
    section("Turn dehumidifier on when the humidity is above:") 
	{
		input "humidityUP", "number", title: "Humidity Upper Threshold (%)?"
	}
    section("Turn dehumidifier off when the humidity returns below:") 
	{
		input "humidityDW", "number", title: "Humidity Lower Threshold (%)?"
	}
    	section("Turn on only during this timeframe")
	{
		input "starting", "time", title: "Start time", required: true
		input "ending", "time", title: "End time", required: true
    }
    	section("Send this message (optional, sends standard status message if not specified)")
	{
		input "messageText", "text", title: "Message Text", required: false
	}
	section("Via a push notification and/or an SMS message")
	{
        	input("recipients", "contact", title: "Send notifications to") 
		{
        		input "pushAndPhone", "enum", title: "Both Push and SMS?", required: false, options: ["Yes", "No"]
        		input "phone", "phone", title: "Main Phone Number (use sign + for country code)", required: true             
    	}
	}
}

def installed() 
{
	subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Installed with settings: ${settings}"
}

def updated() 
{
	unsubscribe()
    subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Updated with settings: ${settings}"
}

def humidityHandler(evt) 
{
	log.debug "Humidity: $evt.value, $evt.unit, $evt.name, $evt"
    def humNum = Double.parseDouble(evt.value.replace("%", ""))
	def tooHumidNum = humidityUP
    double tooHumid = tooHumidNum
    def OKHumidNum = humidityDW
    double OKHumid = OKHumidNum
    def mySwitch = settings.fanSwitch1
	log.debug "Current Humidity: $humNum, Humidity Setting: $tooHumid"
	def msg = messageText ?: defaultText(evt)
   	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg'"
    
    
    // ********************************************************************** def time interval *****************************************************
   	if ( getTimeOK() ) { 
    
		if (humNum >= tooHumid) {
        	
// ********************************************************************** def if time is between x and y *****************************************************       
            
            log.debug "Humidity is very high"
        	if ( fanSwitch1.currentValue("switch") == "off" ) {
				if (location.contactBookEnabled) {
        			sendNotificationToContacts(msg, recipients)
    			} else {
        			if (!phone || pushAndPhone != "No") {
           				log.debug "sending push"
           				sendPush(msg)
        			}
        			if (phone) {
           				log.debug "sending SMS"
           				sendSms(phone, msg)
        			}
    			}
	 			fanSwitch1.on()   
        	}
    	} else {

			if (humNum <= OKHumid) 	{ 
				log.debug "Humidity is back to normal"
    	    	if ( fanSwitch1.currentValue("switch") == "on" ) {
					if (location.contactBookEnabled) {
        				sendNotificationToContacts("Humidity is back to normal", recipients)
    				} else {
						if (!phone || pushAndPhone != "No") {
           					log.debug "sending push"
           					sendPush("Humidity is back to normal")
        				}

						if (phone) {
            				log.debug "sending SMS"
            				sendSms(phone, "Humidity is back to normal")
        				}
    				}
     				fanSwitch1.off()   
        		}
    		}    
  		}
	}
}

private getTimeOk() {
	def result = true
	if (starting && ending) {
		def currTime = now()
		def start = timeToday(starting).time
		def stop = timeToday(ending).time
		result = start < stop ? currTime >= start && currTime <= stop : currTime <= stop || currTime >= start
	}
	log.trace "timeOk = $result"
	result
}

(Cesare Pagani) #7

Thanks for the help. I will test it and post it back if it works.


(Cesare Pagani) #8

I test it out but it does not seem to works. B.T.W. I moved the if (getTimeOK() ) after if (humNum >= tooHumid) because I still want the dehumidifier to turn off, in case it is on, after the ending time… I thought that otherwise it wont turn off if it is on and the humidity goes below the lower threshold after the end time… In the logic of saving energy and money I would like the dehumidifier to turn off when it reach the threshold, also after the ending time, if that the case.


(Tony - SmartThings Unpublished Contributor ) #9

what doesn’t work? Are you getting an error in the IDE log?


(Cesare Pagani) #10

Hi, the IDE is ok. no errors there.

I put the if (getTimeOK()) in a slightly different place (see below). It also does not works turning off the switch though so I am not too sure what is not functioning.

After that I excluded the entire getTimeOK ()) function and instruction and it works like before.

if (humNum >= tooHumid) {
                           if ( getTimeOK() ) { 
        
                    log.debug "Humidity is very high"
                	if ( fanSwitch1.currentValue("switch") == "off" ) {

(Cesare Pagani) #11

Hi Guys, in the mean time I kept on “playing” on this code and I got it partially working on turning on the dehumidifier at the right humidity and at the right set time interval… However it still does not work when the conditions of set humidity are such that the humidifier / switch can be turned off… Cannot understand why…

Can anyone of you have a look at this code and may-be figure out what is missing?

 /**
* SMART Dehumidifier
* Author: CM PAGANI
* Date: 2015-05-14
*/

definition(   
    name: "SMART Dehumidifier 2",
    namespace: "SMART-D2",
    author: "CMPAGANI",
    description: "When the humidity level goes above a certain value, with-in a specified time interval, turn on a switched dehumidifier. When that value drops below a separate threshold, turn off the dehumidifier.",
    category: "Convenience",
    iconUrl: "http://zizaza.com/cache/icon_256/iconset/580464/580468/PNG/512/weather/weather_flat_icon_weather_icon_png_humidity_humidity_png_humidity_icon.png",
    iconX2Url: "http://zizaza.com/cache/icon_256/iconset/580464/580468/PNG/512/weather/weather_flat_icon_weather_icon_png_humidity_humidity_png_humidity_icon.png"
)

preferences 
{
	section("Monitor the humidity...")
	{
		input "humiditySensor1", "capability.relativeHumidityMeasurement", title: "Humidity Sensor?", required: true
    }    
	section("Choose a Switch that controls a dehumidifier...")
	{
		input "fanSwitch1", "capability.switch", title: "Dehumidifier Location?", required: true
    }
    section("Turn dehumidifier on when the humidity is above:") 
	{
		input "humidityUP", "number", title: "Humidity Upper Threshold (%)?"
	}
    section("Turn dehumidifier off when the humidity returns below:") 
	{
		input "humidityDW", "number", title: "Humidity Lower Threshold (%)?"
	}
    section("Turn on only during this timeframe")
	{
		input "starting", "time", title: "Start time", required: true
		input "ending", "time", title: "End time", required: true
    }
    section("Send this message when humidity is too high (optional, sends standard status message if not specified)")
	{
		input "messageText", "text", title: "Message Text High Humidity", required: false
	}
	section("Send this message when humidity is back to normal (optional, sends standard status message if not specified)")
    {
        input "messageText2", "text", title: "Message Text Humidity OK", required: false
	}	
	section("Via a push notification and/or an SMS message")
	{
        input("recipients", "contact", title: "Send notifications to") 
		{
        	input "pushAndPhone", "enum", title: "Both Push and SMS?", required: false, options: ["Yes", "No"]
        	input "phone", "phone", title: "Main Phone Number (use sign + for country code)", required: true             
    	}
	}
}

def installed() 
{
	subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Installed with settings: ${settings}"
}

def updated() 
{
	unsubscribe()
    subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Updated with settings: ${settings}"
}

def humidityHandler(evt) 
{
	log.debug "Humidity: $evt.value, $evt.unit, $evt.name, $evt"
    def humNum = Double.parseDouble(evt.value.replace("%", ""))
	def tooHumidNum = humidityUP
    double tooHumid = tooHumidNum
    def OKHumidNum = humidityDW
    double OKHumid = OKHumidNum
    def mySwitch = settings.fanSwitch1
	log.debug "Current Humidity: $humNum, Humidity Setting: $tooHumid"


	def timeNow = now()
	log.debug("Current time is ${(new Date(timeNow)).format("EEE MMM dd yyyy HH:mm z", location.timeZone)}")
	def msg = messageText ?: defaultText(evt)
  	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg'"
	def msg2 = messageText2 ?: defaultText(evt)
	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg2'"
   	
    if (humNum >= tooHumid)
		{
		if (timeNow >= timeToday(starting, location.timeZone).time && timeNow < timeToday(ending, location.timeZone).time)
			{ 
   			 	log.debug "Humidity is very high"
        		if ( fanSwitch1.currentValue("switch") == "off" ) 
				{
					if (location.contactBookEnabled) 
				{
        			sendNotificationToContacts(msg, recipients)
    			} 
				else 
				{
        			if (!phone || pushAndPhone != "No") 
					{
           				log.debug "sending push"
           				sendPush(msg)
        			}
        				if (phone) 
					{
           				log.debug "sending SMS"
           				sendSms(phone, msg)
        			}
    			}
	 			fanSwitch1.on()   
	       	}
    	} 
		else 
		{
			if (humNum <= OKHumid) 	
			{ 
				log.debug "Humidity is back to normal"
    	    	if ( fanSwitch1.currentValue("switch") == "on" ) 
				{
					if (location.contactBookEnabled) 
					{
        				sendNotificationToContacts(msg2, recipients)
    				} 
					else 
					{
						if (!phone || pushAndPhone != "No") 
						{
           					log.debug "sending push"
           					sendPush(msg2)
        				}
						if (phone) 
						{
            				log.debug "sending SMS"
            				sendSms(phone, msg2)
        				}
    				}
     				fanSwitch1.off()   
        		}
    		}    
  		}
	}
}

(Ernie) #12

Hey, I can’t help with your code but wouldn’t the Smart Humidifier app located in the Smartsetup-More-Convienance section do what you want. I think all you would need to do is setup a mode from 2 am to 6 am.


(Cesare Pagani) #13

Hi, yes that will help to turn on the dehumidifier with in that time interval. This is already working also in the app i posted. What i need now is that the dehumidifier turns off at any time (so also if it is outside the time interval) once it reaches the lower threshold humidity.

Anyway, you gave me an idea for another app… thanks…


(Cesare Pagani) #14

BINGO! — Here the code fully working… Sure it can be better but it works for me… if anyone likes to improve it you are welcome…

/**
* SMART Dehumidifier
* Author: CM PAGANI
* Date: 2015-05-14
*/

definition(   
    name: "SMART Dehumidifier",
    namespace: "SMART-D",
    author: "CMPAGANI",
    description: "When the humidity level goes above a certain value, with-in a specified time interval, turn on a switched dehumidifier. When that value drops below a separate threshold, turn off the dehumidifier.",
    category: "Convenience",
    iconUrl: "http://zizaza.com/cache/icon_256/iconset/580464/580468/PNG/512/weather/weather_flat_icon_weather_icon_png_humidity_humidity_png_humidity_icon.png",
    iconX2Url: "http://zizaza.com/cache/icon_256/iconset/580464/580468/PNG/512/weather/weather_flat_icon_weather_icon_png_humidity_humidity_png_humidity_icon.png"
)

preferences 
{
	section("Monitor the humidity...")
	{
		input "humiditySensor1", "capability.relativeHumidityMeasurement", title: "Humidity Sensor?", required: true
    }    
	section("Choose a Switch that controls a dehumidifier...")
	{
		input "fanSwitch1", "capability.switch", title: "Dehumidifier Location?", required: true
    }
    section("Turn dehumidifier on when the humidity is above:") 
	{
		input "humidityUP", "number", title: "Humidity Upper Threshold (%)?"
	}
    section("Turn dehumidifier off when the humidity returns below:") 
	{
		input "humidityDW", "number", title: "Humidity Lower Threshold (%)?"
	}
    section("Turn on only during this timeframe")
	{
		input "starting", "time", title: "Start time", required: true
		input "ending", "time", title: "End time", required: true
    }
    section("Send this message when humidity is too high (optional, sends standard status message if not specified)")
	{
		input "messageText", "text", title: "Message Text High Humidity", required: false
	}
	section("Send this message when humidity is back to normal (optional, sends standard status message if not specified)")
    {
        input "messageText2", "text", title: "Message Text Humidity OK", required: false
	}	
	section("Via a push notification and/or an SMS message")
	{
        input("recipients", "contact", title: "Send notifications to") 
		{
        	input "pushAndPhone", "enum", title: "Both Push and SMS?", required: false, options: ["Yes", "No"]
        	input "phone", "phone", title: "Main Phone Number (use sign + for country code)", required: true             
    	}
	}
}

def installed() 
{
	subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Installed with settings: ${settings}"
}

def updated() 
{
	unsubscribe()
    subscribe(humiditySensor1, "humidity", humidityHandler)
	log.debug "Updated with settings: ${settings}"
}

def humidityHandler(evt) 
{
	log.debug "Humidity: $evt.value, $evt.unit, $evt.name, $evt"
    def humNum = Double.parseDouble(evt.value.replace("%", ""))
	def tooHumidNum = humidityUP
    double tooHumid = tooHumidNum
    def OKHumidNum = humidityDW
    double OKHumid = OKHumidNum
    def mySwitch = settings.fanSwitch1
	log.debug "Current Humidity: $humNum, Humidity Setting: $tooHumid"


	def timeNow = now()
	log.debug("Current time is ${(new Date(timeNow)).format("EEE MMM dd yyyy HH:mm z", location.timeZone)}")
	def msg = messageText ?: defaultText(evt)
  	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg'"
	def msg2 = messageText2 ?: defaultText(evt)
	log.debug "$evt.name:$evt.value, pushAndPhone:$pushAndPhone, '$msg2'"
   	
    if (humNum >= tooHumid) // && ( getTimeOK() )
		{
		if (timeNow >= timeToday(starting, location.timeZone).time && timeNow < timeToday(ending, location.timeZone).time)
			{ 
   			 	log.debug "Humidity is very high"
        		if ( fanSwitch1.currentValue("switch") == "off" ) 
				{
					if (location.contactBookEnabled) 
					{
        				sendNotificationToContacts(msg, recipients)
    				} 
					else 
					{
        				if (!phone || pushAndPhone != "No") 
						{
           					log.debug "sending push"
           					sendPush(msg)
        				}
        				if (phone) 
						{
           					log.debug "sending SMS"
           					sendSms(phone, msg)
        				}
    				}
	 				fanSwitch1.on()   
	       		}
    		} 
		}
        else 
		{
			if (humNum <= OKHumid) 	
			{ 
				log.debug "Humidity is back to normal"
    	    	if ( fanSwitch1.currentValue("switch") == "on" ) 
				{
					if (location.contactBookEnabled) 
					{
        				sendNotificationToContacts(msg2, recipients)
    				} 
					else 
					{
						if (!phone || pushAndPhone != "No") 
						{
           					log.debug "sending push"
           					sendPush(msg2)
        				}
						if (phone) 
						{
            				log.debug "sending SMS"
            				sendSms(phone, msg2)
        				}
    				}
     				fanSwitch1.off()   
        		}
    		}    
  		}
}

(John L) #15

Thank you. I have been looking around for code similar to this for some time.


(Joseph) #16

Thanks cesare_m_pagani, this app is exactly what I was looking for. I’m new to ST, this is my first SmartApp implementation. I’m trying to use this app with a ST Temperature/Humidity sensor (Zigbee) to control a GE Smart Appliance switch (Z-wave) which has the dehumidifier connected to it. I can’t get the switch to turn on. I suspect the issue is that the humidity sensor is also a temperature sensor and maybe the humidity value isn’t getting parsed correctly in the humidityHandler, Can anyone confirm if this could be my problem and how I could verify it? If this is the issue does anyone know how to modify the code to properly parse the data from the sensor?

Thanks,


(Tarsier Blip) #18

So, the app wasn’t working for me, so I started re-writing it. Lots of comments, and main changes are in the revision notes:

[code]/**

  • SMART Dehumidifier
  • Author: CM PAGANI
  • Date: 2015-05-14
    /
    /
    Revised 2016-12-17, Tarsier Blip
    • General re-write of most code (various fixes)
    • “Full tank” functionality added (if the switch has this capability)
    • Scheduling fixed to accurately operate inside scheduled times
    • Notification system fixed
      */

definition(
name: “SMART Dehumidifier”,
namespace: “SMART-D”,
author: “CMPAGANI”,
description: “When the humidity level goes above a certain value, within a specified time interval, turn on a switched dehumidifier. When that value drops below a separate threshold, turn off the dehumidifier.”,
category: “Convenience”,
iconUrl: “https://image.flaticon.com/icons/png/128/67/67780.png”,
iconX2Url: “https://image.flaticon.com/icons/png/128/67/67780.png
)

preferences
{
section(“Monitor the humidity…”)
{
input “humiditySensor1”, “capability.relativeHumidityMeasurement”, title: “Humidity Sensor”, required: true, multiple: true
}
section(“Choose a Switch that controls a dehumidifier…”)
{
input “outlet1”, “capability.switch”, title: “Dehumidifier Switch”, required: true, multiple: false
}
section(“Turn dehumidifier on when the humidity is above:”)
{
input “humidityUP”, “number”, title: “Humidity Upper Threshold (%)”
}
section(“Turn dehumidifier off when the humidity returns below:”)
{
input “humidityDW”, “number”, title: “Humidity Lower Threshold (%)”
}
section(“Turn on only during this timeframe”)
{
input “starting”, “time”, title: “Start time”, required: true
input “ending”, “time”, title: “End time”, required: true
}
section(“Send this message when humidity is too high (optional, sends standard status message if not specified)”)
{
input “messageHighHumidity”, “text”, title: “Message Text High Humidity”, required: false
}
section(“Send this message when humidity is back to normal (optional, sends standard status message if not specified)”)
{
input “messageOKHumidity”, “text”, title: “Message Text Humidity OK”, required: false
}
section(“Send this message when water tank is full (optional, sends standard status message if not specified)”)
{
input “messageTankFull”, “text”, title: “Message Text Tank Full”, required: false
}
section(“Via a push notification and/or an SMS message”)
{
input(“recipients”, “contact”, title: “Send notifications to”)
{
input “pushAndPhone”, “enum”, title: “Enable push notifications?”, required: true, options: [“Yes”, “No”]
input “phone”, “phone”, title: “Main Phone Number (use sign + for country code)”, required: false
}
}
}

def installed()
{
subscribe(humiditySensor1, “humidity”, humidityHandler)
schedule(starting, humidityHandler)
schedule(ending, humidityHandler)
log.debug “Installed with settings: ${settings}”
}

def updated()
{
unsubscribe()
subscribe(humiditySensor1, “humidity”, humidityHandler)
schedule(starting, humidityHandler)
schedule(ending, humidityHandler)
log.debug “Updated with settings: ${settings}”
}

def humidityHandler(evt)
{
def humNum = 0
double tooHumid = humidityUP
double OKHumid = humidityDW
boolean OKRun = false // Variable to indicate whether we are within the time range set
def timeNow = now()

// If there is an event; we get humidity from the event information
if ( evt )
	{
	log.debug "Humidity: $evt.value, $evt.unit, $evt.name, $evt"
	humNum = Double.parseDouble(evt.value.replace("%", ""))
	}
// ... otherwise, we use whatever the last reported humidity was.
else
	{
	humNum = humiditySensor1.currentValue("humidity")
	}

log.debug("Current time is ${(new Date(timeNow)).format("EEE MMM dd yyyy HH:mm z", location.timeZone)}")
log.debug "Current Humidity: $humNum, Low humidity limit: $OKHumid, High humidity limit: $tooHumid"

// If end time is before start time ...
if (timeToday(starting, location.timeZone).time > timeToday(ending, location.timeZone).time)
	{
	//log.debug("Times go overnight; using alternate method.")
	// If we are earlier or later than the two times set, then we should be running
	if (now() >= timeToday(starting, location.timeZone).time || now() <= timeToday(ending, location.timeZone).time)
		{
		OKRun = true
		}
	}
else
	{
	//log.debug("Times go during the day; using standard method.")
	// If we are between the two times set, then we should be running
	if (now() >= timeToday(starting, location.timeZone).time && now() <= timeToday(ending, location.timeZone).time)
		{
		OKRun = true
		}
	}

if ( OKRun )
	{
	//log.debug("Operation is within set times.")
	}

if ( !OKRun && outlet1.currentValue("switch") == "on" )
	{
	log.debug "Operation ran out of time range; turning off device."
	outlet1.off()   
	sendMessage(evt, "Operation ran out of time range; turning off device.", "")
	}
    
if ( OKRun && humNum >= tooHumid && outlet1.currentValue("switch") == "off" )
	{
	log.debug "Humidity is over the setpoint of $tooHumid; turning on device."
	outlet1.on()   
	if ( !messageHighHumidity )
		{ sendMessage(evt, "Humidity level is $humNum% (above the $tooHumid threshold); activating dehumidifier.", "") }
	else
		{ sendMessage(evt, messageHighHumidity, "") }
	}
else if ( OKRun && humNum <= OKHumid && outlet1.currentValue("switch") == "on" )
	{
	log.debug "Humidity is below the setpoint of $OKHumid; turning off device."
	outlet1.off()
	if ( !messageOKHumidity )
		{ sendMessage(evt, "Humidity level is $humNum% (below the $OKHumid threshold); deactivating dehumidifier.", "") }
	else
		{ sendMessage(evt, messageOKHumidity, "") }
	}
else if ( outlet1.hasAttribute("power") && outlet1.currentValue("switch") == "on" )
	{
	int avgPower = 0		// Variable to hold the average power draw, if available
	// My outlet randomly reports odd wattages (sometimes 0); we quickly check it 5 times, then average them.
	// Due to the drastic difference between "running" and "idle; tank full", even a few misreads would not make a difference.
	for (int ii = 0; ii<5; ii++)
		{
		//log.debug(outlet1.currentValue("power"))
		avgPower += outlet1.currentValue("power")
		pause(250)
		}
	avgPower /= 5
	//log.debug("Dehumidifier is drawing $avgPower watts.")

	if ( avgPower < 10 )
		{
		//log.debug("Tank Full")
		if ( !messageTankFull )
			{ sendMessage(evt, "Dehumidifier tank appears to be full.", "Force") }
		else
			{ sendMessage(evt, messageTankFull, "Force") }
		}
	else
		{
		//log.debug("Tank Not Full")
		}
	}
}

private sendMessage(evt, msg, override)
{
msg = msg ?: evt.descriptionText
if ( evt )
{
//log.debug “$evt.name:$evt.value, pushAndPhone:$pushAndPhone, ‘$msg’”
}
if (location.contactBookEnabled)
{
sendNotificationToContacts(msg, recipients)
}
else
{
if ( pushAndPhone == “Yes” || override == “Force” )
{
log.debug "sending push"
sendPushMessage(msg)
}
if ( phone )
{
log.debug "sending SMS"
sendSmsMessage(phone, msg)
}
}
}[/code]


(Mario) #19

Joseph or CESARE PAGANI, did you guys get this setup to work for you, i tried the last code posted for this app, i got a combination of xiaomi humidity sensor and iris 3210l smart plug, but this does not seem to work for me. any help truly appreciated. from you or Cesare. Thank you much


(Cesare Pagani) #20

Hi Mario,
It works for me. I won’t be able to tell what is the issue you face. If the
sensors you use are connected to your hub it should work.

Cheers


(Mario) #21

Cesare: thank you much for the reply, is this the code in this posting that worked for you,my issue is the dehumidifier turns on fine base on the humidity threshold but the app never turns it off when it reaches the turn dehumidifier off when humidity returns below x: the dehumidifier just keeps running . i was using the last code posted here.
any suggestion, should i change to this version

thanks