Jul-17-2021, 04:19 PM
Deanhystad,
With your help and others, I was able to come up with something that works consistently well.
Thanks to all!
Seems there were several issues. One was timing. The timeout parameter in the open statement needed to be long enough for the MP3 board to compile the answer to the query. Another issue was timing between the request and the response. 3rd was to not ask for the read till the inWaiting was equal to the length of the response.
Also, I had trouble when I kept the serial port open through the whole program. Opening and closing probably causes a bunch of overhead but worked best for me. I tried only opening once in the program after I was successful opening and closing many times and it failed with time out issues.
Please consider this issue closed.
Here is the resultant code:
With your help and others, I was able to come up with something that works consistently well.
Thanks to all!
Seems there were several issues. One was timing. The timeout parameter in the open statement needed to be long enough for the MP3 board to compile the answer to the query. Another issue was timing between the request and the response. 3rd was to not ask for the read till the inWaiting was equal to the length of the response.
Also, I had trouble when I kept the serial port open through the whole program. Opening and closing probably causes a bunch of overhead but worked best for me. I tried only opening once in the program after I was successful opening and closing many times and it failed with time out issues.
Please consider this issue closed.
Here is the resultant code:
"""Sends a message via serial & receives back information via serial.""" import serial import time to = 30 #<-- timeout value PLAYING_DONE = bytearray([170, 1, 1, 0, 172]) def write_command(port, command): """Write command to serial port""" command = [170] + command # Command packet starts with 0xAA command.append(sum(command) % 256) # Append checksum # print('Command = ', command) # For debugging purposes port.write(bytearray(command)) def read_status(port): """Read status? Returns bytearray""" write_command(port, [1, 0]) time.sleep(0.5) if port.inWaiting() > 4: return port.read(5) def play_track(port, track_info): """Start playing track. Track is??""" write_command(port, [7] + track_info) ser = serial.Serial( '/dev/ttyS0', # Serial port on my computer baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=to) # timeout for read play_track(ser, [2, 0, 9]) # Track info? ser.close() playing = None while playing != PLAYING_DONE: ser = serial.Serial( '/dev/ttyS0', # Serial port on my computer baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=to) # timeout for read playing = read_status(ser) # print(f'Return = {playing}') ser.close() ser.close() print("Done and closed")