我有一个串行设备(Arduino)定期输出日志数据,这些数据应该写在一个日志文件中。该设备还通过串行接收自发命令。我通过 Telegram 将命令发送到 Raspberry,由 Telepot 处理并发送到 arduino,Telepot 在单独的线程中运行。
我怎样才能确保这两个过程彼此相处?
我是一个完整的多线程初学者。这是我的代码的缩短版本:
import time
import datetime
import telepot
import os
import serial
from time import sleep
ser = None
bot = None
def log(data):
with open('logfile', 'w') as f:
file.write("Timestamp" + data)
#The handle Function is called by the telepot thread,
#whenever a message is received from Telegram
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print( 'Command Received: %s' % command)
if command = '/start':
bot.sendMessage(chat_id, 'welcome')
elif command == 'close_door':
#This serial write could possibly happen while a
#ser.readline() is executed, which would crash my program.
ser.write("Close Door")
elif command == 'LOG':
#Here i should make sure that nothing
#is waiting from the Arduino
#so that the next two Serial lines are the Arduinos
#respoonce to the "LOG" command.
#and that hanlde is the only
#function talking to the Serial port now.
ser.write("LOG")
response = ser.readline()
response += "\0000000A" + ser.readline()
#The Arduinos response is now saved as one string
#and sent to the User.
bot.sendMessage(chat_id, response)
print("Command Processed.")
bot = telepot.Bot('BOT TOKEN')
bot.message_loop(handle)
ser = serial.Serial("Arduino Serial Port", 9600)
print( 'I am listening ...')
while True:
#anything to make it not run at full speed (Recommendations welcome)
#The log updates are only once an hour.
sleep(10)
#here i need to make sure it does not collide with the other thread.
while ser.in_waiting > 0:
data = ser.readline()
log(data)
这段代码不是我的实际代码,但它应该准确地代表我正在尝试做的事情。
我最后的办法是将串行代码放在线程循环函数中,但这需要我更改丑陋的库。
我在 Asincio 中查找了一些关于队列和锁定功能的内容。但是我真的不明白如何应用它。另外我不使用异步 Telepot。