For a little project I made a Gui where the user selects a folder to save a log file of the Can bus messages on the bus. When the directory is selected and it is an valid directory the logger instantaneously start to connect to the bus and log all the messages.
To keep the Gui from freezing I tried to integrate the window.after function. Only now I encounter a problem with connecting to the canbus via python-can module. When the script can't connect to the Can network, a message box with a warning will pop up.
When I select a directory where to save the files and then the logger tries to connect, the warning box immiadately pops up, and when I click OK button it logs one message to the file. After that the warning box pops up again and when I click OK it logs again one canbus messages. And so on.
I suspect I haven't arranged my code probably, but I can't find the mistake. So I coming to you guys for help.
The piece of code which generates the trouble:
def log_function():
#Try to connect to the CAN Network if not show Warning.
try:
while True:
global bus
bus = can.interface.Bus(interface='pcan', channel='PCAN_USBBUS1', bitrate=250000)
print("connected")
except:
messagebox.showerror("Warning", "NO CONNECTION ESTABLISHED, PLEASE CONNECT TO CAN NETWORK")
#Logger function
try:
message = bus.recv()
logger.debug(db.decode_message(message.arbitration_id, message.data))
print(db.decode_message(message.arbitration_id, message.data))
except KeyError:
pass
window.after(100, log_function)
# When Stop button is pressed the bus will shutdwon and the script/gui will exit.
def stop():
bus.shutdown()
sys.exit()
I also tried to make a separate function of the first Try statement, but that also didn't work.
CodePudding user response:
It seem that you are reconnecting to the bus over and over again. I don't understand the while loop you are using in there because I would expect you only need to connect once.
You then probably want to download the information and write it to your file.
Your example has missing code, so I'm not sure when and how you trigger the stop function. But I guess something like this should help:
def connect_bus():
try:
global bus
bus = can.interface.Bus(interface='pcan', channel='PCAN_USBBUS1', bitrate=250000)
print("connected")
except:
messagebox.showerror("Warning", "NO CONNECTION ESTABLISHED, PLEASE CONNECT TO CAN NETWORK")
def log_function():
#Logger function
try:
message = bus.recv()
logger.debug(db.decode_message(message.arbitration_id, message.data))
print(db.decode_message(message.arbitration_id, message.data))
except KeyError:
pass
window.after(100, log_function)
# When Stop button is pressed the bus will shutdwon and the script/gui will exit.
def stop():
bus.shutdown()
sys.exit()