Reputation: 1
I'm fairly new to Python and so I'd like some feedback on the code I've written. The code is written to send and receive data from a ham radio. The code opens a serial port to the radio, then writes commands and reads the answer. The answer is saved in a dictionary for later use. This will be a part of a larger program that will allow the user to import the radio's configuration data to the app, then make modifications and send it back to the radio. It will also be able to save the data to a file so that different radio configurations can be saved and downloaded to the radio for use in different situations. I've copied the code below.
import serial
def Read_Radio():
# Configure the serial port
ser = serial.Serial(
port='COM4',
baudrate=38400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
# Function to send a command to the device
def send_command(ser, command):
ser.write(command.encode())
response = ser.readline().decode()
return response
menu_data = {}
try:
# Read all Menu items and store in dictionary
for m in range(1, 15): # Limited to 15 for testing.
ID = f"{m:03}" # formats the ID to 3 characters
command = "EX" + str(ID) + ";" # creates the command to be sent
response = send_command(ser, command) # sends the command
raw = response.lstrip("EX") # strips the leading characters
raw = raw.rstrip(";") # strips the trailing character
P1 = raw[0:3] # pulls first three characters
P2 = raw[3:] # pulls after first 3 letters
menu_data.update({P1:P2}) # Saves the data pairs in a dict
except Exception as e:
print(f"An error occurred: {e}")
finally:
print(menu_data)
# Close the serial port
ser.close()
Read_Radio()
SAMPLE DATA OUPUT: {'001': '0300', '002': '0700', '003': '3000', '004': '0', '005': '1', '006': '0', '007': '1', '008': '08', '009': '2', '010': '050', '011': '050', '012': '3', '013': '0', '014': '30'}
The results are as I expected. I'm trying to make sure that I have the data in a useful format and that my code is efficient or can it be simpler. Is there anything in my code that may be slowing it down.
Upvotes: -2
Views: 46
Reputation: 331
In my testing the script below can reduce a lot of time:
import serial
import time
def Read_Radio():
ser = serial.Serial(
port='COM4',
baudrate=38400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=0.2 # Reduced timeout for faster response
)
def send_command(ser, command):
ser.reset_input_buffer() # Flush buffer before sending
ser.write(command.encode()) # Send command
time.sleep(0.05) # Small delay to allow device processing
response = ser.readline().decode().strip() # Strip spaces/newlines
return response
menu_data = {}
try:
for m in range(1, 15): # Limited to 15 for testing.
ID = f"{m:03}"
command = f"EX{ID};"
response = send_command(ser, command)
if response: # Check if response is valid
raw = response.lstrip("EX").rstrip(";")
if len(raw) >= 3:
P1, P2 = raw[:3], raw[3:]
menu_data[P1] = P2
except Exception as e:
print(f"An error occurred: {e}")
finally:
print(menu_data)
ser.close()
Read_Radio()
Upvotes: 0