capybara/MessageParser.py

41 lines
1.8 KiB
Python
Raw Normal View History

class MessageParser():
def __init__(self):
self.handlers = {}
def add_handler(self, code: str, args={}):
self.handlers[code] = {
"args": args
}
def parse(self, message: str):
if len(message) < 1:
return None, "Message is empty"
message_code = message[0]
if message_code not in self.handlers:
return None, "Message code is not handled"
message_arguments = message[1:].split(";")
handler = self.handlers[message_code]
decoded_arguments = {}
if len(handler["args"]) != len(message_arguments):
return None, "Got message with invalid argument count"
for i, argument_name in enumerate(handler["args"]):
argument_type = handler["args"][argument_name]
if argument_type == "int":
try:
decoded_arguments[argument_name] = int(message_arguments[i])
except ValueError:
return None, "Error parsing int argument for message (is it really an int?)"
elif argument_type == "float":
try:
decoded_arguments[argument_name] = float(message_arguments[i])
except ValueError:
return None, "Error parsing float argument for message (is it really a float?)"
elif argument_type == "str":
decoded_arguments[argument_name] = message_arguments[i]
elif argument_type == "char":
if len(message_arguments[i]) != 1:
return None, "Error parsing char argument due to invalid size"
decoded_arguments[argument_name] = message_arguments[i]
else:
raise ValueError("parse(): Message handler references an invalid argument type")
return message_code, decoded_arguments