这是一个我一直在检查许多占用传感器中的一个(或多个(是否会返回1(有人进入房间(以打开灯的线程。然而,它都是在while True
循环中编写的,我认为这对内存非常不利,因为我总是存储在一个变量中。注意,return_message()
函数总是返回一个值。那么如何解决这个问题呢?
def turning_lights_on():
while True:
for occupancy_sensor_ids in ids :
# get the lights ids in the room according to the occupancy sensor id
lights_id = db.light_devices(occupancy_sensor_ids)
# the return value of the occupancy sensor is stored in message_occ_sensor
# but a topic containing the id of the sensor must be used here, so need to be changed
message_occ_sensor = occupancy_sensor.return_message(occupancy_sensor_ids)
# loop to send commands to all the lights in the room
for lights in lights_id:
# the state of lights ON/OFF is returned
# I considered that every topic starts by the device ID
state_light_tunable = light_sub.return_message(lights +"/stat/POWER")
if message_occ_sensor == "1" :
if state_light_tunable == "OFF":
# topics are to be modified and deviceID must be imported from mongoDB
#lights_id is imported from mongoDB
client.publish(lights +"/cmnd/POWER", 1)
仅仅因为某个东西在while True
循环中,并不意味着它一定会有内存问题。
在循环的迭代之间,您没有保留任何数据,所有变量都会被覆盖,因此旧数据将没有引用,Python垃圾收集器将为您删除它们。
不用担心!