wgovideo
Posts: 4
Joined: Tue Apr 23, 2019 5:01 pm

DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0 w/BBcode)

Mon Jun 03, 2019 4:22 am

Everything works great except my "reminder" function. The goal is to get a email reminder message with the current datetime and current temp.(last "if" at the bottom) But the variables in the message is not updating as soon as the scheduler engages (right before the loop). I keep getting the same message over and over. I'm desperate for help. I've been fighting this problem for a week. I've tried timedeltas, global variables, scheduler, and apscheduler with *args &**kwargs. I can"t seem to get the variables to update once the scheduler kicks in. Like I said, everything works except my reminder function. I'm stuck! I'm self taught with limited resources. Google is great, I got as far as I could by myself having never done python before. but I'm truly frustrated and stuck. You can see all my hashed out failed attempts.
FYI's- credential entry right near the top hashed out. Scheduled task is right before the loop. temp setpoint is three paragraphs down.

Code: Select all

import os
#import sys
import glob
import smtplib, ssl
from mycreds import (user,password,list1)
#user=your@gmail
#password= 'for your gmail'
#list1= list of recipients,list of recipients

from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler()
#from threading import Thread, Event
import time
from datetime import datetime
currenttime = datetime.now()
hr = int(currenttime.strftime("%-H"))
#global dt
dt = currenttime.strftime("%c")
print (dt)

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

#Temperature activation set point in Fahrenheit----------------
setpoint = 60
#Temperature sensor status
tempss = 0
#Temperature sensor history
tempsh = 0

# Email & Textmsg ---------------------------------------------
def send_email():
    context = ssl.create_default_context()
    port = 465
    with smtplib.SMTP_SSL("smtp.gmail.com", port,context=context) as server:
        server.login(user, password)
        server.sendmail (user, (list1).split(","), message)
#Active Alarm reminder------------------------------------
def reminder():
    if read_temp() > setpoint:
        #updater()
        read_temp()
        #currenttime = datetime.now()
        #dt = currenttime.strftime("%c")
        time.sleep(1)
        #message = """Subject: T.A.N.N.S.\n
#    Alarm is still active!\n
#    Current temperature is {}F\n{}
#    \n--<<NO REPLY>>--""".format (read_temp(), dt)
        time.sleep(2)
        print ('Starting email service3')
        send_email()
        print ("Email sent!")
        print (message)
        print (read_temp())
        remindertoggle=0
        return
            
    else:
        sched.pause()
        remindertoggle=1
        return
#def updater():
#    global dt
#    dt = currenttime.strftime("%c")
#    print (dt)
#    global ct    
#    ct = (read_temp())
#    print (ct)     

     
# Reading of tempature------------------------------------
def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines =read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.02)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = round(temp_c * 9.0 / 5.0 + 32.0,2)
        return temp_f
global ct    
ct = read_temp() 
sched.add_job(reminder, 'interval', seconds = 20)

#Sensor Status-------------------------------
while True:
    if read_temp() > setpoint:
        tempss = 1
        print (read_temp())
    else:
        tempss = 0
        
#Sensor Conditions---------------------------
    #if hr > 6 and hr < 23:   
    if tempss == 1 and tempsh == 0:
        message= """Subject: T.A.N.N.S.
    Alarm Activated
    
    Current temperature is {}F
    
    {}
    --<<NO REPLY>>--""".format (read_temp(), dt)
        print (message)
        print ('Starting email service1')
        send_email()
        print ("Email sent!")
        print
        tempsh = 1
        remindertoggle=1
      # sys.exit()
    if tempss == 0 and tempsh == 1:
        message = """Subject: T.A.N.N.S.
    Alarm Resolved
    Current temperature is {}F
    {}
    --<<NO REPLY>>--""".format (read_temp(), dt)
        
        print ('Starting email service2')
        print (message)
        send_email()
        tempsh = 0
        #remindertoggle = 0
        print ("Email sent!")
        #sys.exit()
    
        
    if tempss == 0 and tempsh == 0:
        print (read_temp())
    if tempss == 1 and tempsh == 1:
        if remindertoggle==1:
            message = """Subject: T.A.N.N.S.\n
    Alarm is still active!\n
    Current temperature is {}F\n{}
    \n--<<NO REPLY>>--""".format (read_temp(), dt)
            sched.start()
            print ("reminder activated")
            remindertoggle=0
    else:
        sched.pause()
        print ("Im in bottom else")
               

    
           
        


Last edited by wgovideo on Mon Jun 03, 2019 6:15 pm, edited 6 times in total.

wgovideo
Posts: 4
Joined: Tue Apr 23, 2019 5:01 pm

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated

Mon Jun 03, 2019 1:39 pm

I'm really stuck here. If someone could at least point me in the right direction. This project is 90% done. I'm so close.

When your self-taught, sometimes fundamentals are difficult to grasp.

pcmanbob
Posts: 6225
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated

Mon Jun 03, 2019 2:21 pm

Hi.

First please edit your first post and add a space or new line after the code tag so that you code is displayed with the indentation.

Secondly you need to allow time for people to see your post, we are all just users just like you giving up our spare time to help others, it may take several days before the right person see's your post.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

ghp
Posts: 1352
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0)

Mon Jun 03, 2019 5:42 pm

Code formatting would help.
Think the problem is related to the way the message is prepared.
The scheduler calls periodially the reminder function (each 20 secs, little bit nervous for a reminder...).
The message variable is prepared outside of the 'reminder' loop formed by scheduler and reminder method. So it is not in the loop of the scheduler. Right ?

There is a subtle hint in the code of the 'reminder' method. The message formatting is commented away, thus the earlier prepared message is reused over and over.

#currenttime = datetime.now()
#dt = currenttime.strftime("%c")
time.sleep(1)
#message = """Subject: T.A.N.N.S.\n
# Alarm is still active!\n
# Current temperature is {}F\n{}
# \n--<<NO REPLY>>--""".format (read_temp(), dt)
Last edited by ghp on Mon Jun 03, 2019 7:00 pm, edited 1 time in total.

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 11847
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0)

Mon Jun 03, 2019 5:52 pm

OP had disabled his BBC codes, so the code tags didn't work

re-enabled BBC code tags.

wgovideo
Posts: 4
Joined: Tue Apr 23, 2019 5:01 pm

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0 w/BBcode)

Mon Jun 03, 2019 6:45 pm

I've tried to format the reminder message both before and after the execution of the scheduler.. Can't get the variables in the message to update. (datetime and temp). I've played with making the variables global still no luck. I left a lot of my attempts 'hashed out' just to give a feel on some of the things I've tried.

The scheduler is set for 20 seconds for testing purposes. I have print statements throughout to monitor the messages being sent. The actual intention of the reminder message will be set for 1 hour increments to show if the temp is "trending" up or down. (Did they get a delivery, or did the freezer take a dump).

The code in the first post should be properly formatted now. I goofed the first time. I did in fact have BBcode off. It should be easier to read and figure out what I am missing. I've tried *args & kwargs in the schedule setup. But I couldn't get that to work either. I suspect I'm missing something simple.

Just so there is a clear understanding of what my problem is:
when the alarm goes on- I get the right message
when the alarm goes off- I get the right message
If the alarm goes on and stays on- (when the scheduler starts) I get the same message over and over at whatever time marker I set. The datetime and temp "in" the message don't get updated. It's as if the schedule did the task the first time then just sends a copy.

Thank you everyone for your help. Other then the internet, I have no resources. If I say python around here, people thing I'm going to the zoo.

ghp
Posts: 1352
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0 w/BBcode)

Mon Jun 03, 2019 7:10 pm

Ok, with the formatted code the things look less strange.

I removed the read-sensor code and replced by a simple random function. Removed email-send and replaced by a print(message).

There are a few errors which stop part of the code.

# TODO ValueError: Invalid format string
#hr = int(currenttime.hstrftime("%-H"))
# replaced by:
hr = currenttime.hour

The scheduler seems to be started/ paused when not in the right state to be started or stopped. I get sometimes SchedulerAlreadyRunningError which indicate that the scheduler is not handled properly.
When I remove the sched.start() or sched.pause() call by a more elaborate code which checks the current sched state then these errors are not appearing.
Think this is major effort to handle this properly. Perhaps better to let it always run and use a flag 'produce_reminder_messages = True/ False and check this in 'reminder-method.

When both is done, then the message in email has latest temperature from the (fake) sensor.
The dt-variable is never updated ? Would be a good idea to re-read the time whenever a temp is measured ?

Hope this helps.

wgovideo
Posts: 4
Joined: Tue Apr 23, 2019 5:01 pm

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0 w/BBcode)

Mon Jun 03, 2019 8:05 pm

I'm actually using "email to text message"
This line:
#hr = int(currenttime.strftime("%-H"))
went with this line:
#if hr > 6 and hr < 23:
It's right at the top of the loop. It's my crude attempt to shut the whole thing down from 11pm to 6am. Both are hashed out for testing. I don't use or call "hr" anywhere else. I didn't want messages all night long. I have to sleep sometime.. I have it disabled for testing. Also, your copy of first "hr" line has a typo. hence the error. It's not like that in the code.

These 2 lines is where I pull the time content to be put in the message:
currenttime = datetime.now()
dt = currenttime.strftime("%c")

This leaves your reference to the placement of the "sched-start" & "sched-pause".
I did think to just shutdown the job then restart it every cycle. But it appears you can't restart a job once its shutdown.That why I used pause.

Where did you place the "start" and "pause" in the code to get it to work?
I've seen the errors you referred to.(schedule already running) That's when I implemented the remindertoggle=0 and remindertoggle=1, This kept the program out of that "if" statement after the schedule started. "1" to get in, "0" keeps you out. Toggle is set to "0" after fist call to the reminder function. Toggle set to "1" after initial alarm. Crude, I know.

ghp
Posts: 1352
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: DS18B20 temp alarm, schedule problem, reminder variables not getting updated(v2.0 w/BBcode)

Tue Jun 04, 2019 6:56 pm

There was a queston on whai I did with the scheduler status commands.
Something like this, but I'r recommend not to use something like this in production code.

Code: Select all

def sched_start():
    if sched.state == apscheduler.schedulers.base.STATE_STOPPED:
        sched.start()
        print ("STATE_STOPPED", "start", "start")
    elif sched.state == apscheduler.schedulers.base.STATE_PAUSED:
        print ("STATE_PAUSED", "start", "nope")
        # sched.start()
    elif sched.state == apscheduler.schedulers.base.STATE_RUNNING:
        print ("STATE_RUNNING", "start", "nope")
    else:
        print("ups", "state not known")

... other code
... somewhere
	
            if False:
                sched.start()
            else:
                sched_start()
		
The idea was to bypass the problems with the logic and learn more about the running system. As I said, improve the code and then you will not need such workarounds.

If you look for ways to improve the code, why not use the features of apscheduler and run some stuff in parallel:
- one job for the reminder()
- make one job each minute or so to read the sensors and time
- a third one for the main logic, just processing latest temp reading.

Return to “Python”