def deserialize(self): """Turns a sequence of bytes into a message dictionary.""" if self.msgbytes is None: raise LLRPError('No message bytes to deserialize.') data = ''.join(self.msgbytes) msgtype, length, msgid = struct.unpack(self.full_hdr_fmt, data[:self.full_hdr_len]) ver = (msgtype >> 10) & BITMASK(3) msgtype = msgtype & BITMASK(10) try: name = Message_Type2Name[msgtype] logger.debug('deserializing %s command', name) decoder = Message_struct[name]['decode'] except KeyError: raise LLRPError('Cannot find decoder for message type ' '{}'.format(msgtype)) body = data[self.full_hdr_len:length] try: self.msgdict = {name: dict(decoder(body))} self.msgdict[name]['Ver'] = ver self.msgdict[name]['Type'] = msgtype self.msgdict[name]['ID'] = msgid logger.debug('done deserializing %s command', name) except LLRPError: logger.exception('Problem with %s message format', name) return '' return ''
def serialize(self): if self.msgdict is None: raise LLRPError('No message dict to serialize.') name = self.msgdict.keys()[0] logger.debug('serializing %s command', name) ver = self.msgdict[name]['Ver'] & BITMASK(3) msgtype = self.msgdict[name]['Type'] & BITMASK(10) msgid = self.msgdict[name]['ID'] try: encoder = Message_struct[name]['encode'] except KeyError: raise LLRPError('Cannot find encoder for message type ' '{}'.format(name)) data = encoder(self.msgdict[name]) self.msgbytes = struct.pack(self.full_hdr_fmt, (ver << 10) | msgtype, len(data) + self.full_hdr_len, msgid) + data logger.debug('serialized bytes: %s', hexlify(self.msgbytes)) logger.debug('done serializing %s command', name)