用“if语句”逻辑在Python中编程一个用于时间调度的恒温器

2024-06-16 13:58:36 发布

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

我正在研制一种自动调温器,它可以根据一天中的时间自动关闭。在

这是我的恒温器功能:

def thermostat(ac_on, acPower, temp_inside, Temp_desired):
   if temp_inside > Temp_desired:
        ac_on = True
   if temp_inside < Temp_desired:
        ac_on = False
   ac_heatflow = acPower if ac_on == True else 0
   return ac_heatflow, ac_on

Temp_desired是一个设置的整数值,temp_inside是与Temp_desired(现在每隔几秒钟)比较的变化的室内温度值,看看空调(a/C)是“开”还是“关”。ac_heatflow是空调打开时的用电量,acPower是在功能之外分配的a/C功率值。在

我现在的问题是,我现在想给我的恒温器增加一个时间元件,在这里空调可以被编程为关闭。例如,空调一整天都正常工作,但是从早上8:00到10:00必须关闭,从下午3:00到下午5:45必须关闭,因此在这些时间间隔内,ac_on = False,但是在这些时间间隔之外,恒温器将恢复到原来的方法,根据室温来确定空调是否开/关。在

上述时间间隔在函数中使用时以秒为单位,因此上午8:00为28800,上午10:00--36000,下午3:00--gt;54000,下午5:45--63900。在

这就是我一直在尝试的:

^{pr2}$

start是间隔的开始时间,end是间隔结束时间,t现在是以秒为单位的。在24小时内每隔几秒就要计算一次温度,一天是86400秒,所以start和{}可以是0到86400之间的任何值,例如,start = 1000和{}。上面代码的问题是没有输出,看起来Python似乎“挂起”了初始while语句,所以我必须停止脚本。我也试过:

if t >= start or t <= end:
        ac_on = False 
else:
    if temp_inside > Temp_desired + 2:
        ac_on = True
    if temp_inside < Temp_desired:
        ac_on = False
ac_heatflow = 400 if ac_on == True else 0
return ac_heatflow, ac_on

但这会将ac_heatflow的所有值设置为0。在

我不确定如何对函数进行编码,以便编程时也能考虑到一天中的时间。也许这是一个嵌套的循环问题,或者它需要一个单独的函数来集中定义时间间隔,并将这些赋值输入到恒温器函数中。在


Tags: 函数falsetrue间隔ifon时间start
2条回答

问题出在表达式t >= start or t <= end。首先什么是开始和结束?您在这种情况下描述了两个时间段,但您只向函数传递了一个潜在时间段的参数?在

假设start=100和{}。如果t在开始之前,那么说t=5。那么t仍然小于700,所以这个陈述是正确的。或者,如果t在结束之后,比如t=705,那么{}仍然大于100,所以这个表达式的计算结果仍然是true(这就是为什么{}总是为False的原因)。基本上不管t的值是多少,这个语句都是真的。我想你想要的是t >= start and t <= end。在

尽管我仍然对您描述的两个时间段有点困惑,但是可以传入4个参数,start1、end1、start2和end2,然后使用:

if (t >= start1 and t <= end1) or (t >= start2 and t <= end2):

关键是使用pythonsdatetime库。一些提示:

  1. 在函数中不使用ac_on的先验值,因此不需要传入它。在
  2. 可以使用datetime库在函数体中找到当前时间
  3. 因为您已经习惯了pythons条件赋值,所以只要稍加重构,我们就可以变得更加简洁和python。在

    import datetime
    
    def ithermostat(temp, ac_power, desired_temp,\
       off_times={'morning':(datetime.time(8, 0), datetime.time(10, 0)),\
                  'afternoon':(datetime.time(15, 0), datetime.time(17, 45))}):
    
        """(num, num, num, dict) -> (num, bool)
    
    Return the tuple (ac_power_usage per unit time, ac_on status) of the thermostat
    The ac is turned on only when the current time is not in off times AND
    the tempreture is higher than the desired tempreture
    """
    
    off_period = False # this flag will be set when the system is in the off period
    current_time = datetime.datetime.now().time()
    for k, v in off_times.items():
        print(v)
        if v[0] <= current_time <= v[1]:
            print("system in mandatory off period")
            off_period = True
            break
    
    ac_on = False if off_period else temp > desired_temp   
    ac_power_usage = ac_power if ac_on else 0
    return ac_power_usage, ac_on
    

同一函数的更简洁、更易读、更具python风格的版本如下:

^{pr2}$

这两个功能都经过测试,运行良好。在

相关问题 更多 >