import time class ParseMessage(): parms = {} raw=None def __init__(self, raw): self.time = time.time() self.raw = raw self.parse() def parse(self): """ Parser for incoming messages. :return: """ for i, line in enumerate(self.raw.split("\r\n")): entries = line.split() if entries == []: continue if i == 0: self.type = entries[0] if len(entries) < 2: raise NotImplementedError() elif len(entries) == 2: self.parms[entries[0]] = entries[1] else: self.parms[entries[0]] = entries[1:] class ComposeMessage(): def __init__(self): pass def __call__(self, mtype, args=None): """ Compose raw byte string to send over ethernet TODO: check argument type TODO: make sure all commands fit the scheme :param mtype: command as static string :param args: list of argument strings (optional, default None) :return: raw byte string """ assert isinstance(mtype, str) #assert isinstance(args, list) raw = mtype if args is not None: raw += " "+" ".join(args) raw += "\r\n\r\r" return raw.encode("ASCII") if __name__ == "__main__": sample_messages = { "SensorState": 'SensorState OK\r\n State InUse\r\n UserApplication "Process Eye Professional"\r\n UserVersion V5.2\r\n UserAddress 127.0.0.1\r\n', "Info": 'Info OK\r\n SerialNumber LM70-00197021\r\n Name "Chamber A"\r\n State Ready\r\n UserApplication N/A' +\ '\r\n UserVersion N/A\r\n UserAddress N/A\r\n ProductID 70 MicroVision+\r\n RFConfiguration 0 "Smart Head"' +\ '\r\n DetectorType 0 Faraday\r\n SEMSupply 3000 3.0kV\r\n ExternalHardware 0 None\r\n TotalPressureGauge 0 ' +\ '"Not Fitted"\r\n Page 13 of 158\r\n FilamentType 0 Tungsten\r\n ControlUnitUse 4 "Standard RGA"\r\n' +\ ' SensorType 1 "Standard Open Source"\r\n InletType 1 None\r\n Version V3.70\r\n NumEGains 3\r\n' +\ ' NumDigitalPorts 2\r\n NumAnalogInputs 4\r\n NumAnalogOutputs 1\r\n NumSourceSettings 6\r\n ' +\ 'NumInlets 1\r\n MaxMass 200\r\n ActiveFilament 1\r\n FullScaleADCAmps 0.000002\r\n FullScaleADCCount' +\ ' 8388608\r\n PeakResolution 32\r\n ConfigurableIonSource Yes\r\n RolloverCompensation No\r\n', "EGains": 'EGains OK\r\n 1\r\n 100\r\n 20000\r\n', "InletInfo": 'InletInfo OK\r\n Automatic Yes \r\nActiveInlet 0\r\n Factor Fixed CanCalibrate DefaultFactor TypeName\r\n 1 Yes No 1 "Process Chamber direct"\r\n', "Release": "Release Ok\r\n", #"AcceptProtocol": "initiate": "MKSRGA Single\r\n Protocol_Revision 1.1\r\n Min_Compatibility 1.1\r\n\r\n\r\r", "Error": 'command ERROR\r\n Number 200\r\n Description "err description"\r\n\r\n', } cm = ComposeMessage() #bmess = cm(mtype="Select", args=["LM70-00197021"]) #smess = bmess.decode("ASCII") pm = ParseMessage(sample_messages["InletInfo"]) print(pm.type, pm.parms, pm.time)