This is a code that receives data through serial communication and sends a notification to a messenger using urlapi when data with a value of 80 or more comes more than 5 times in a row. Alerts are intended to be sent after a certain amount of time has elapsed since the first alert was sent.
From the code below to sending notification via messenger, it was successful. However, half an hour is a time of fearfully.Even in the sleep state, the function is called, so there is an error as shown in the attached photo.
Is there a way to prevent the notification function from ringing for a specific time after the notification function is called once?
import serial
import urllib2
import time
from threading import Thread
port = "/dev/ttyACM0"
baudrate=9600
api_key=''
Token=""
ChatId=""
count = 0
over=0
serial = serial.Serial(port,baudrate,timeout=80)
serial.flushInput()
def telegram(data):
#telegram
count=0
t =
urllib2.urlopen("https://api.telegram.org/bot"+Token+"/SendMessage? id="+str(ChatId)+"&text="+str(data))
time.sleep(3600)
count = 0
while True:
t1=Thread(target=telegram,args=str(over))
if serial.readable():
input_s=serial.readline()
rst=input_s[:-1].decode()
print(rst)
if int(rst) > 80 :
count =count +1
else :
count = 0
print(count)
if(count>5) :
over=int(rst)
t1.start()
Even if you call the sleep function inside Thread, it is meaningless because Main Thread continues to run and continues to generate Thread inside the while loop. Rather, the previously created Thread is called to sleep and new Threads are continuously created without being terminated.
Simply put, if you don't use Thread and call a function that sends a notification when the count is over 5, you can implement a notification delay as desired, but in this case, you won't be able to process serial input during sleep.
Therefore, a better solution would be to record the time you sent the notification without using sleep (current time - the time you sent the notification before) and implement logic to not send the notification if it does not exceed 30 minutes.
© 2024 OneMinuteCode. All rights reserved.