冷却功能

2024-05-19 10:09:23 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有一个人探测器脚本,我想发送一个信息,如果任何人检测到的邮件输入为了防止垃圾邮件,我需要一个发送邮件计时器函数。函数可能会随时触发,但只有在不冷却时才会响应。你知道吗

我尝试使用异步任务,但无法实现,因为如果有人检测到它会进入一个循环,在那里它每5分钟发送一次电子邮件,即使第一眼看到后没有检测到任何人。你知道吗

示例:

  1. 人员检测脚本正在运行。你知道吗
  2. 在摄像头上检测到人->;发送电子邮件(开始5分钟的冷却)
  3. 2分钟后再次看到的人(没有发送任何电子邮件,因为还有3分钟的冷却时间)。你知道吗
  4. 6分钟后视力恢复的人再发一封邮件(因为5分钟的冷却时间已经结束)。你知道吗

我的代码摘要。(只有必要的部分检测和发送邮件工作冷却(定时器)不工作

async def sendAlert():
        server.sendmail(sender_email, receiver_email, message)
        print('sent!')
        await asyncio.sleep(300)




if __name__ == "__main__":
    while True:
        for i in range(len(boxes)):
            if classes[i] == 1 and scores[i] > threshold:
                with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
                    sendAlert(server)     
                box = boxes[i]
                cv2.rectangle(img,(box[1],box[0]),(box[3],box[2]),(255,0,0),2)

如果检测到人员,脚本将通过发送警报电子邮件。之后如果在5分钟内再次检测到人员,sendAlert功能应在5分钟后才响应


Tags: 函数脚本box信息ifserver人员电子邮件
1条回答
网友
1楼 · 发布于 2024-05-19 10:09:23

我同意@Prune的观点,即您需要创建一个小的(最小的)用例并呈现您的代码,这样它不仅与您相关,而且与其他人相关。此外,你的问题应该有一个可验证的例子部分。如果没有这些属性,人们就很难理解、解决和/或提出任何可验证的解决方案。你知道吗

但是,据我所知,在某个cool-off时间段之后,您需要执行一些操作(如果检测到某人,则发送电子邮件)。所以,换句话说,你需要一种跟踪时间的机制。因此,您需要datetime库。你知道吗

因此,伪代码应该如下所示:

伪码

import datetime

start = capture_timestamp()
cutoff = '00:05:00'
dt_cutoff = read_in_cutoff_as_timedelta(cutoff)
if person_detected:
    now = capture_timestamp()
    dt = now - start
    if dt >= dt_cutoff:
        # Send notification
        send_email_notification()
    else:
        # Do not Send Notification
        print('now: {} | dt: {}'.format(now, dt))

您可以使用datetime.datetime.utcnow()作为时间戳。和datetime.timedelta()定义dt_cutoff。要读取时间字符串,请执行以下操作:

tm = datetime.datetime.strptime(cutoff).time()
dt_cutoff = datetime.timedelta(hours = tm.hour, minutes = tm.minute, seconds = tm.second)

我希望这能给你一些关于如何建模的想法。你知道吗

额外资源

  1. https://www.guru99.com/date-time-and-datetime-classes-in-python.html
  2. https://docs.python.org/3/library/datetime.html
  3. https://thispointer.com/python-how-to-convert-a-timestamp-string-to-a-datetime-object-using-datetime-strptime/

完整解决方案

最后,如果您急于使用现成的解决方案,可以使用下面的class对象,如图所示。您只需通过指定冷却期(timer_cutoff)实例化类对象,然后调用方法is_timeout()。如果返回True,则发送通知。还有一个obj.istimeout属性存储这个决策(True/False)。你知道吗

import time

# Set cutoff time to 2 seconds to test the output 
# after 5 seconds: expect istimeout = True
# and instantiate the TimeTracker class object.
ttk = TimeTracker(timer_cutoff = '00:00:02') # 'HH:MM:SS'
# Wait for 3 seconds
time.sleep(3)
print('start timestamp: {}'.format(ttk.timestamp_start_str))
print('cutoff timestamp'.format(ttk.timestamp_cutoff_str))
print('timer_cutoff: {}'.format(ttk.timer_cutoff_str))
# Now check if cutoff time reached
ttk.is_timeout()
print('Send Notification: {}'.format(ttk.istimeout))
print('now_timestamp: {}'.format(ttk.timestamp_now_str))

类时间跟踪器

下面是类TimeTracker类:

import datetime

class TimeTracker(object):
    def __init__(self, 
                 timer_cutoff = '00:05:00', 
                 cutoff_strformat = '%H:%M:%S'):
        self.timer_cutoff_str = timer_cutoff
        self.cutoff_strformat = cutoff_strformat
        self.timestamp_start, self.timestamp_start_str = self.get_timestamp()
        self.dt_cutoff = None # timedelta for cutoff
        self.timestamp_cutoff = None
        self.timestamp_cutoff_str = None
        self.update_timestamp_cutoff()
        self.timestamp_now = None
        self.timestamp_now_str = None
        self.dt_elapsed = None
        self.istimeout = False

    def get_timestamp(self):
        ts = datetime.datetime.utcnow()
        tss = str(ts)
        return (ts, tss)

    def readin_cutoff_as_timedelta(self):
        td = datetime.datetime.strptime(self.timer_cutoff_str, 
                                        self.cutoff_strformat)
        tdm = td.time()
        self.dt_cutoff = datetime.timedelta(hours = tdm.hour, 
                                            minutes = tdm.minute, 
                                            seconds = tdm.second)


    def update_timestamp_cutoff(self):
        self.readin_cutoff_as_timedelta()
        self.timestamp_cutoff = self.timestamp_start + self.dt_cutoff
        self.timestamp_cutoff_str = str(self.timestamp_cutoff)

    def time_elapsed(self):
        self.dt_elapsed = self.timestamp_now - self.timestamp_start

    def is_timeout(self):
        self.timestamp_now, self.timestamp_now_str = self.get_timestamp()
        self.time_elapsed()
        if (self.dt_elapsed < self.dt_cutoff):
            self.istimeout = False
        else:
            self.istimeout = True

        return self.istimeout

相关问题 更多 >

    热门问题