def send(self, method, token, path, has_payload=False, payload=None): if has_payload: frame = "%s%s%s%s" % (tinypacks.pack(method), tinypacks.pack(token), tinypacks.pack(path), tinypacks.pack(payload)) else: frame = "%s%s%s" % (tinypacks.pack(method), tinypacks.pack(token), tinypacks.pack(path)) frame += struct.pack(">H", crc16.crc16str(frame)) if self.debug: print "TX:", for c in frame: print "%X" % ord(c), print "[%i]" % len(frame) try: self.fd.write("\x7E") for byte in frame: if byte == "\x7E": self.fd.write("\x7D\x5E") elif byte == "\x7D": self.fd.write("\x7D\x5D") else: self.fd.write(byte) self.fd.write("\x7E") except IOError as err: raise PostmanError("Frame sending failed: %s" % err)
def receive(self): frame = "" byte = "" try: while (byte != "\x7E" or frame == ""): byte = self.fd.read(1) if not byte: raise PostmanError("Frame receiving timed out.") if byte == "\x7D": frame += chr(ord(self.fd.read(1)) | 32) elif byte != "\x7E": frame += byte except PostmanError: raise except IOError as err: raise PostmanError("Frame receiving failed: %s" % err) if self.debug: print "RX:", for c in frame: print "%X" % ord(c), print "[%i]" % len(frame) if len(frame) >= 4 and crc16.crc16str(frame[:-2]) == struct.unpack( ">H", frame[-2:])[0]: frame = frame[:-2] response, frame = tinypacks.unpack(frame) if frame: token, frame = tinypacks.unpack(frame) if frame: payload, frame = tinypacks.unpack(frame) return [response, token, payload] else: return [response, token] else: return [response] else: raise PostmanError("Frame receiving failed, bad CRC %s != %s " % (hex(crc16.crc16str(frame[:-2])), hex(struct.unpack(">H", frame[-2:])[0])))
def receive(self): frame = "" byte = "" try: while (byte != "\x7E" or frame == ""): byte = self.fd.read(1) if not byte: raise PostmanError("Frame receiving timed out.") if byte == "\x7D": frame += chr(ord(self.fd.read(1))|32) elif byte != "\x7E": frame += byte except PostmanError: raise except IOError as err: raise PostmanError("Frame receiving failed: %s" % err) if self.debug: print "RX:", for c in frame: print "%X" % ord(c), print "[%i]" % len(frame) if len(frame) >= 4 and crc16.crc16str(frame[:-2]) == struct.unpack(">H", frame[-2:])[0]: frame = frame[:-2] response, frame = tinypacks.unpack(frame) if frame: token, frame = tinypacks.unpack(frame) if frame: payload, frame = tinypacks.unpack(frame) return [response, token, payload] else: return [response, token] else: return [response] else: raise PostmanError("Frame receiving failed, bad CRC %s != %s " % (hex(crc16.crc16str(frame[:-2])), hex(struct.unpack(">H", frame[-2:])[0])))