import machine
import utime
utime.sleep(0.1) # Wait for USB to become ready
# Message related constants
MESSAGE_START = "S"
MESSAGE_END = "Z"
def parse_message(fmessage):
identifier_indices = []
# Check the start byte
if len(fmessage) == 0 or fmessage[0].upper() != MESSAGE_START:
print("Error! Start Byte Missing!")
return []
# Check the stop byte
if fmessage[-1].upper() != MESSAGE_END:
print("Error! Stop Byte Missing!")
return []
# Iterate through the message to process characters
for i in range(1, len(fmessage) - 1): # Exclude start and end bytes
if fmessage[i].isalpha():
# Add indices of alphabetic characters
identifier_indices.append(i)
return identifier_indices
def read_command(fmessage, fidentifier_indices):
command_list = []
num_identifiers = len(fidentifier_indices)
for i in range(num_identifiers):
start_index = fidentifier_indices[i] + 1
if i + 1 < num_identifiers:
end_index = fidentifier_indices[i + 1]
else:
end_index = -1 # Up to the character before 'Z'
# Extract substring based on indices
package = fmessage[start_index:end_index]
if not package.isdigit():
raise ValueError(f"Error! Data field empty or invalid for identifier '{fmessage[fidentifier_indices[i]]}'!")
command_list.append(int(package))
return command_list
def main():
# Main loop
while True:
# Prompt the user for input
message = input("What is your command? (type 'exit' to quit): ").strip()
# Exit condition
if message.lower() == "exit":
print("Exiting program. Goodbye!")
break
# Parse the message
identifier_indices = parse_message(message)
if not identifier_indices:
print("No valid command identifiers found. Please try again.")
continue
# Debugging (optional): Display the identifier indices
print("Identifier Indices:", identifier_indices)
# Process the commands
command_list = read_command(message, identifier_indices)
if not command_list:
# Error message already printed in read_command
continue
print("Command List:", command_list)
# You can add code here to handle the commands as needed
# this ensures the main() loop runs only when the file is executed directly
# In another Python script
# import script # The main() function will NOT run
if __name__ == "__main__":
main()