Reputation: 703
I want to receive serial data and depending on the data want to make announcement. my monitor function will continuously monitor serial data. But I am facing a problem that when i am announcing something then after completion of announcement serial data is monitored and the process going slow. I want to monitor serial data continuously and want to made the announcement parallel. Is threading is the best option?? how to handle it?
def announce(data):
subprocess.call('espeak',data)
while 1:
receiveddata= xbee.readline()
if receiveddata=='a1':
announce("i am ok in room1")
if receiveddata=='b2':
announce("Urgently attend room 1")
Upvotes: 3
Views: 1052
Reputation: 23480
from threading import Thread
def announce(data):
subprocess.call('espeak',data)
class worker(Thread):
def __init__(self, data):
Thread.__init__(self)
self.data = data
def run(self):
if receiveddata=='a1':
announce("i am ok in room1")
if receiveddata=='b2':
announce("Urgently attend room 1")
# at the end of run() the process will die.
while 1:
receiveddata = xbee.readline()
thread_handle = worker(receiveddata)
thread_handle.start() # <- This starts the thread but keeps on going
Here's a skeleton framework that you can use in order to achieve paralell processing in Python. It's not complete nor is it perfect, but it will give you a start and it will solve your initial problem.
There's tons of "best practices" for threading and stuff, i'll leave google to explain and find those because there will always be a better solution than what i can produce in one short answer here.
I honored the fact that you were new to threading in python.
But as discussed in the comments below, this will be a resource demanding solution if you have a a lot of data on the serial port (which will create thread
-> do work
-> die
).
There are more effective threading solutions (such as keeping a thread alive throughout the program and calling a function in the class that announces instead). But this is the bare minimum that you'll need in order to get started.
I'll leave these links here for you to experiment and evolve your threading knowledge from this very basic example above:
Working with queues
Upvotes: 1