def __call__(self, buf): print lib.hexdump(buf) pkt = Packet.fromBuffer(buf) """ stamp = time.time( ) dt = datetime.fromtimestamp(stamp).replace(tzinfo=self.args.timezone) msg = lib.hexdump(buf) rssi = buf[0:2] rfpacket = buf[2:] record = dict(date=stamp , dateString=dt.isoformat( ) , rfpacket=str(rfpacket).encode('hex') , head=str(rssi).encode('hex') , serial=str(rfpacket[1:4]).encode('hex') , op=str(rfpacket[0:1]).encode('hex') , payload=str(rfpacket[4:]).encode('hex') , decocare_hex=msg ) # print """ if pkt.valid: print pkt return pkt if self.args.stream: self.args.out.write(self.formatter(record)) self.args.out.flush() else: self.data.append(record)
def find_dates(self, stream): records = [ ] bolus = bytearray(stream.read(4)) dates = [ ] extra = bytearray( ) everything = bolus SIZE = 4 opcode = '' last = 0 for B in iter(lambda: stream.read(1), ""): h, t = B[:1], B[1:] bolus.append(h) bolus.extend(t) everything.extend(B) if len(everything) < SIZE: continue candidate = everything[-SIZE:] date = parse_date(candidate) if date is not None: last = stream.tell( ) # last = len(everything) start = last - SIZE print "### FOUND ", date.isoformat( ), ' @ ', start, "%#08x" % start print "#### previous" print lib.hexdump(bolus, indent=4) print "#### datetime" print lib.hexdump(candidate, indent=4) print "" found = dict(timestamp=date, blob=bolus) print dump_four(candidate, indent=4) # print lib.hexdump(bolus) records.append(found) bolus = bytearray( ) return records
def pformat(self, prefix=''): head = '\n'.join([ " op hex (%s)" % len(self.head), lib.hexdump(self.head, indent=4), " decimal", int_dump(self.head, indent=11) ]) date = '\n'.join([ " datetime (%s)" % self.date_str(), lib.hexdump(self.date, indent=4) ]) body = " body (%s)" % len(self.body) if len(self.body) > 0: body = '\n'.join([ body, " hex", lib.hexdump(self.body, indent=4), " decimal", int_dump(self.body, indent=11) ]) extra = [] hour_bits = history.extra_hour_bits(self.date[1]) year_bits = history.extra_year_bits(self.date[4]) day_bits = history.extra_hour_bits(self.date[3]) if 1 in hour_bits: extra.append("HOUR BITS: {}".format(str(hour_bits))) if 1 in day_bits: extra.append("DAY BITS: {}".format(str(day_bits))) if 1 in year_bits: extra.append("YEAR BITS: {}".format(str(year_bits))) extra = ' ' + ' '.join(extra) return '\n'.join([prefix, head, date, body, extra])
def pformat(self, prefix=''): head = '\n'.join([ " op hex (%s)" % len(self.head), lib.hexdump(self.head, indent=4), " decimal", lib.int_dump(self.head, indent=11) ]) date = '\n'.join([ " datetime (%s)" % self.date_str( ), lib.hexdump(self.date, indent=4) ]) body = " body (%s)" % len(self.body) if len(self.body) > 0: body = '\n'.join([ body, " hex", lib.hexdump(self.body, indent=4), " decimal", lib.int_dump(self.body, indent=11) ]) extra = [ ] hour_bits = self.date[1:] and extra_hour_bits(self.date[1]) or [ ] year_bits = self.date[4:] and extra_year_bits(self.date[4]) or [ ] day_bits = self.date[3:] and extra_hour_bits(self.date[3]) or [ ] if 1 in hour_bits: extra.append("HOUR BITS: {}".format(str(hour_bits))) if 1 in day_bits: extra.append("DAY BITS: {}".format(str(day_bits))) if 1 in year_bits: extra.append("YEAR BITS: {}".format(str(year_bits))) decoded = None if len(self.head + self.date + self.body) >= self.min_length( ): decoded = self.decode( ) decode_msg = '' if decoded is not None: decode_msg = '\n'.join([ '###### DECODED', '```python', '{}'.format(lib.pformat(self.decode( ))), '```', ]) if extra: extra = ' ' + ' '.join(extra) else: extra = '' return '\n'.join([ prefix, decode_msg, head, date, body, extra ])
def find_records(stream, opts): records = [ ] errors = [ ] bolus = bytearray( ) extra = bytearray( ) opcode = '' for B in iter(lambda: bytearray(stream.read(2)), bytearray("")): if B == bytearray( [ 0x00, 0x00 ] ): print ("#### STOPPING DOUBLE NULLS @ %s," % stream.tell( )), nulls = eat_nulls(stream) print "reading more to debug %#04x" % B[0] print lib.hexdump(B, indent=4) print lib.int_dump(B, indent=11) extra = bytearray(stream.read(32)) print "##### DEBUG HEX" print lib.hexdump(extra, indent=4) print "##### DEBUG DECIMAL" print lib.int_dump(extra, indent=11) # print "XXX:???:XXX", history.parse_date(bolus).isoformat( ) break record = parse_record( stream, B, larger=opts.larger ) records.append(record) return records
def find_records(stream, opts): records = [] errors = [] bolus = bytearray() extra = bytearray() opcode = '' for B in iter(lambda: bytearray(stream.read(2)), bytearray("")): if B == bytearray([0x00, 0x00]): print("#### STOPPING DOUBLE NULLS @ %s," % stream.tell()), nulls = eat_nulls(stream) print "reading more to debug %#04x" % B[0] print lib.hexdump(B, indent=4) print lib.int_dump(B, indent=11) extra = bytearray(stream.read(32)) print "##### DEBUG HEX" print lib.hexdump(extra, indent=4) print "##### DEBUG DECIMAL" print lib.int_dump(extra, indent=11) # print "XXX:???:XXX", history.parse_date(bolus).isoformat( ) break record = parse_record(stream, B, larger=opts.larger) records.append(record) return records
def wait_response (self): link = self.link for buf in link.dump_rx_buffer( ): resp = Packet.fromBuffer(buf) if self.responds_to(resp): print "READ" print lib.hexdump(buf) return resp
def execute (self, msg, **kwds): msg.serial = self.serial message = fmt_command(msg, serial=self.serial, **kwds) self.link.write(message) framer = Framer( ) while not framer.done( ): data = self.link.read( ) framer.frame(data) print "HYPOTHETICAL PUMP RESULT", framer, len(framer.frames), len(framer.data) print lib.hexdump(framer.data) msg.respond(framer.data) return msg
def wait_for_ack (self): link = self.link # while not self.done( ): for buf in link.dump_rx_buffer( ): print "wait_for_ack" resp = Packet.fromBuffer(buf) if self.responds_to(resp): print lib.hexdump(buf) if resp.op == 0x06: # self.unframe(resp) print "found valid ACK" return resp
def execute(self, msg, **kwds): msg.serial = self.serial message = fmt_command(msg, serial=self.serial, **kwds) self.link.write(message) framer = Framer() while not framer.done(): data = self.link.read() framer.frame(data) print "HYPOTHETICAL PUMP RESULT", framer, len(framer.frames), len( framer.data) print lib.hexdump(framer.data) msg.respond(framer.data) return msg
def main (self, args): if args.dryrun: print args.set print lib.hexdump(bytearray(commands.SetRTC.fmt_datetime(args.set))) return clock = self.report_clock(args) if args.command == "query": pass if args.command == "set": new_clock = self.set_clock(args) time.sleep(1) clock = self.report_clock(args) args.out.write(json.dumps(clock, indent=2))
def write( self, string, repetitions=1, timeout=None ): if timeout is None: timeout = self.TIMEOUT self.serial.write_timeout = timeout message = bytearray( string ) message_length = len(message) # Format of transmission is as follows. Note that the content is # automatically converted to radio (FourBySix) format # # Command | Length of Message | Repetititons | Message ... # # Command is: # 0x1 Send - CRC already included # 0x81 Send - Add CRC-8 at the end # 0xC1 Send - Add CRC-16 at the end # # Repetitions must be <= 255 as it's a byte. So we loop according to the # maximum batch size remaining_messages = repetitions while remaining_messages > 0: if remaining_messages < self.MAX_REPETITION_BATCHSIZE: transmissions = remaining_messages else: transmissions = self.MAX_REPETITION_BATCHSIZE remaining_messages = remaining_messages - transmissions arr = array.array('B', bytearray([0x1, message_length, transmissions]) + message) r = self.serial.write( arr.tostring() ) if r != len(arr): raise CommsException("Could not write to serial port - Tried to write %s bytes but only wrote %s" % (len(arr), r)) io.info( 'usb.write.len: %s\n%s' % ( len( string ), hexdump( bytearray( string ) ) ) ) # If the batch is large, the hardware can take a while to respond to us. # Based on testing, this seems about right: self.serial.timeout = timeout + (0.03 * transmissions) confirmation = self.serial.read(3) # If the MMCommander stick is not write-enabled, the firmware returns 0 as the message length # and transmission count if bytearray( confirmation ) == bytearray([ 0x01, 0x0, 0x0]): raise MMCommanderNotWriteable("Error sending radio comms. Your MMCommander stick may not have write-enabled firmware?") if repetitions > 1: if bytearray( confirmation ) != bytearray([ 0x01, message_length, transmissions]): io.warn("usb.write.confirmation: Could not get confirmation of transmission from mmcommander. Response was %d %d %d, not %d %d %d" % ( ord(confirmation[0]), ord(confirmation[1]), ord(confirmation[2]), 0x01, message_length, transmissions )) self.clear_receive_buffer('Unclear message confirmation') # This is a hack - which seems to occur because we occasionally don't get # the right number of packets above. return r
def format_markdown (self, record): return """### {dateString} {op} {serial} ``` {payload_hex} ``` """.format(payload_hex=lib.hexdump(bytearray(record.get('payload').decode('hex'))), **record)
def respond (self, link): print "RESPONDING ", self.queue while self.queue: func, packet, resp = self.queue.pop( ) payload = func(packet) buf = resp.respond(payload) print "SENDING", str(buf).encode('hex') print lib.hexdump(buf) encoded = FourBySix.encode(buf) print "SENDING ENCODED", str(encoded).encode('hex') print lib.hexdump(encoded) # link.write(buf) link.write(encoded) link.triggerTX( ) link.triggerTX( ) link.triggerTX( )
def format_markdown(self, record): return """### {dateString} {op} {serial} ``` {payload_hex} ``` """.format(payload_hex=lib.hexdump( bytearray(record.get('payload').decode('hex'))), **record)
def get_pages(device): log.info("read cur page number") comm = ReadCurPageNumber() device.execute(comm) pages = comm.getData() log.info('attempting to read %s pages of history' % pages) for x in range(pages + 1): log.info('comm:READ HISTORY DATA page number: %r' % (x)) comm = ReadHistoryData(params=[x]) device.execute(comm) page = comm.getData() log.info("XXX: READ HISTORY DATA!!:\n%s" % lib.hexdump(page))
def get_pages(device): log.info("read cur page number") comm = ReadCurPageNumber( ) device.execute(comm) pages = comm.getData( ) log.info('attempting to read %s pages of history' % pages) for x in range(pages + 1): log.info('comm:READ HISTORY DATA page number: %r' % (x)) comm = ReadHistoryData( params=[ x ] ) device.execute(comm) page = comm.getData( ) log.info("XXX: READ HISTORY DATA!!:\n%s" % lib.hexdump(page))
def pformat(self, prefix=''): head = '\n'.join([ " op hex (%s)" % len(self.head), lib.hexdump(self.head, indent=4), " decimal", int_dump(self.head, indent=11) ]) date = '\n'.join([ " datetime (%s)" % self.date_str( ), lib.hexdump(self.date, indent=4) ]) body = " body (%s)" % len(self.body) if len(self.body) > 0: body = '\n'.join([ body, " hex", lib.hexdump(self.body, indent=4), " decimal", int_dump(self.body, indent=11) ]) extra = [ ] hour_bits = history.extra_hour_bits(self.date[1]) year_bits = history.extra_year_bits(self.date[4]) day_bits = history.extra_hour_bits(self.date[3]) if 1 in hour_bits: extra.append("HOUR BITS: {}".format(str(hour_bits))) if 1 in day_bits: extra.append("DAY BITS: {}".format(str(day_bits))) if 1 in year_bits: extra.append("YEAR BITS: {}".format(str(year_bits))) extra = ' ' + ' '.join(extra) return '\n'.join([ prefix, head, date, body, extra ])
def main( ): parser = get_opt_parser( ) opts = parser.parse_args( ) tw_opts = { 'width': 50, 'subsequent_indent': ' ', 'initial_indent': ' ', } wrapper = textwrap.TextWrapper(**tw_opts) for stream in opts.infile: records = find_dates(stream) print "%s: %s records" % (stream.name, len(records)) i = 0 for rec in records: date, datum, tail, extra = rec opcode = datum[0] stats = "hex({}), extra({})".format(len(datum), len(extra)) date_str = str(date) if date is not None: date_str = date.isoformat( ) print "#### RECORD %s: %s %#04x %s" % (i, date_str, opcode, stats) print " hex (%s)" % len(datum) print lib.hexdump(datum, indent=4) print " decimal" print int_dump(datum, indent=11) print " datetime\n%s" % (lib.hexdump(tail, indent=4)) print " extra(%s)" % len(extra), if len(extra) > 0: print "\n%s" % (lib.hexdump(extra, indent=4)) print int_dump(extra, indent=11) else: print "%s" % (None) print "" i += 1 stream.close( )
def readDeviceDataIO(self): results = self.readData() lb, hb = results[5] & 0x7F, results[6] self.eod = (results[5] & 0x80) > 0 resLength = lib.BangInt((lb, hb)) log.info('XXX resLength: %s' % resLength) #assert resLength < 64, ("cmd low byte count:\n%s" % lib.hexdump(results)) data = results[13:13+resLength] assert len(data) == resLength crc = results[-1] # crc check log.info('readDeviceDataIO:msgCRC:%r:expectedCRC:%r:data:%s' % (crc, CRC8(data), lib.hexdump(data))) assert crc == CRC8(data) return data
def readDeviceDataIO(self): results = self.readData() lb, hb = results[5] & 0x7F, results[6] self.eod = (results[5] & 0x80) > 0 resLength = lib.BangInt((lb, hb)) log.info('XXX resLength: %s' % resLength) #assert resLength < 64, ("cmd low byte count:\n%s" % lib.hexdump(results)) data = results[13:13 + resLength] assert len(data) == resLength crc = results[-1] # crc check log.info('readDeviceDataIO:msgCRC:%r:expectedCRC:%r:data:%s' % (crc, CRC8(data), lib.hexdump(data))) assert crc == CRC8(data) return data
def checkAck(self): log.info('checkAck sleeping .100') time.sleep(.100) result = bytearray(self.read(64)) io.info('checkAck:read') if len(result) == 0: log.error("ACK is zero bytes!") return False raise BadDeviceCommError("ACK is not 64 bytes: %s" % lib.hexdump(result)) commStatus = result[0] # usable response assert commStatus == 1, ('commStatus: %02x expected 0x1' % commStatus) status = result[1] # status == 102 'f' NAK, look up NAK if status == 85: # 'U' log.info('checkACK OK, found %s total bytes' % len(result)) return result[3:] assert False, "NAK!!"
def fromBuffer(klass, buf, stamp=None, timezone=None, chan=None): stamp = stamp or time.time() # dt = datetime.fromtimestamp(stamp).replace(tzinfo=self.args.timezone) dt = datetime.fromtimestamp(stamp).replace(tzinfo=timezone) msg = lib.hexdump(buf) # head = buf[0:2] rfpacket = buf rftype = buf[0] serial = str(rfpacket[1:4]).encode('hex') command = None payload = None crc = None valid = False if serial and len(rfpacket) > 5: rftype = rfpacket[0] command = rfpacket[4] payload = rfpacket[5:-1] crc = int(rfpacket[-1]) calculated = lib.CRC8.compute(rfpacket[:-1]) valid = calculated == crc if not valid: raise InvalidPacketReceived record = dict( date=stamp * 1000, dateString=dt.isoformat(), type=rftype, serial=serial, op=command, payload=payload, payload_hex=str(payload).encode('hex'), crc=crc, valid=valid, chan=chan # , rfpacket=str(rfpacket).encode('hex') # , head=str(head).encode('hex') # , op=str(rfpacket[0:1]).encode('hex') # , decocare_hex=msg ) pkt = klass(**record) return pkt
def fromBuffer (klass, buf, stamp=None, timezone=None, chan=None): stamp = stamp or time.time( ) # dt = datetime.fromtimestamp(stamp).replace(tzinfo=self.args.timezone) dt = datetime.fromtimestamp(stamp).replace(tzinfo=timezone) msg = lib.hexdump(buf) # head = buf[0:2] rfpacket = buf rftype = buf[0] serial = str(rfpacket[1:4]).encode('hex') command = None payload = None crc = None valid = False if serial and len(rfpacket) > 5: rftype = rfpacket[0] command = rfpacket[4] payload = rfpacket[5:-1] crc = int(rfpacket[-1]) calculated = lib.CRC8.compute(rfpacket[:-1]) valid = calculated == crc if not valid: raise InvalidPacketReceived record = dict(date=stamp * 1000 , dateString=dt.isoformat( ) , type = rftype , serial = serial , op = command , payload = payload , payload_hex = str(payload).encode('hex') , crc = crc , valid = valid , chan = chan # , rfpacket=str(rfpacket).encode('hex') # , head=str(head).encode('hex') # , op=str(rfpacket[0:1]).encode('hex') # , decocare_hex=msg ) pkt = klass(**record) return pkt
def find_dates(stream): records = [ ] errors = [ ] bolus = bytearray( ) extra = bytearray( ) opcode = '' for B in iter(lambda: bytearray(stream.read(2)), bytearray("")): opcode = B[0] #bolus.append(B) bolus.extend(B) head_length = Record.lookup_head(opcode) body_length = Record.lookup_body(opcode) date_length = Record.lookup_date(opcode) total = len(bolus) if total < head_length: bolus.extend(bytearray(stream.read(head_length-total))) variable_read = Record.variable_read(opcode, bolus) if variable_read > 2: #print "super special" bolus.extend(bytearray(stream.read(variable_read))) #print lib.hexdump( bolus ) opcode = bolus[variable_read] #print "NEW OPCODE %#04x" % opcode head_length = Record.lookup_head(opcode) body_length = Record.lookup_body(opcode) total = len(bolus) - variable_read if total < head_length: bolus.extend( stream.read(head_length-total) ) total = len(bolus) #body_length = Record.lookup_body(opcode) #date_length = Record.lookup_date(opcode) #total = len(bolus) total = len(bolus) head_length = total head = bolus[:max(total, 1)] bolus.extend(bytearray(stream.read(date_length))) date = bolus[head_length:head_length+date_length] total = len(bolus) # print repr(bolus), date_length, repr(date) if len(date) < 5: print "DATE LESS THAN 5!", stream.tell( ) print lib.hexdump(bolus) break records[-1].body.extend(bolus) datetime = parse_date(date) if bytearray( [0x00] * max(total-2, 5) ) in bolus: nulls = bytearray(eat_nulls(stream)) pos = stream.tell( ) if pos > 1021: bolus = bolus + nulls + bytearray(stream.read(-1)) crc = bolus[-2:] nulls = bolus[:-2] print "EOF {} nulls, CRC:".format(len(nulls)) print lib.hexdump(crc) else: print total, ' ', max(total-2, 5) print lib.hexdump( [0x00] * min(total, 5) ) print print "TOO MANY NULLS, BAILING ON STREAM at %s " % stream.tell( ) print "bolus" print lib.hexdump(bolus) print "nulls" print lib.hexdump(nulls) print "MISSING: ARE THERE 32 more bytes?" print lib.hexdump(bytearray(stream.read(32))) # records[-1].body.extend(nulls) break if not Record.is_midnight(head): if datetime is None: print ("#### MISSING DATETIME @ %s," % stream.tell( )), print "reading more to debug %#04x" % opcode print lib.hexdump(bolus, indent=4) print int_dump(bolus, indent=11) extra = bytearray(stream.read(32)) print "##### DEBUG HEX" print lib.hexdump(extra, indent=4) print "##### DEBUG DECIMAL" print int_dump(extra, indent=11) if history.parse_date(bolus): print "XXX:???:XXX", history.parse_date(bolus).isoformat( ) break if datetime is not None or Record.is_midnight(head): body = bytearray(stream.read(body_length)) bolus.extend(body) if False or Record.seeks_null(opcode, body): print "should eat up to null, second %s" % repr(body[1:]) if body[1:]: if body[-1] != 0x00: extra = seek_null(stream) print "found %s extra" % len(extra) body.extend(extra) bolus.extend(extra) epi = bytearray(stream.read(date_length)) finished = parse_date(epi) record = Record(head, date, body) prefix = "#### RECORD %s %s" % (len(records), str(record) ) print record.pformat(prefix) print "" records.append(record) bolus = bytearray( ) opcode = '' return records
bytearray([ 0x30, 0xa7 ]) + \ bytearray(str(serial).decode('hex')) + \ bytearray([ msg.code, 0x00 ]) crc = lib.CRC8.compute(op[33:]) length = bytearray([len(op) + 1]) return prefix + length + op + bytearray([crc]) if __name__ == '__main__': import sys, os logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) from link import Link from modem import Modem serial = os.environ.get('SERIAL') msg = fmt_command(commands.ReadPumpModel(serial=serial), serial=serial) print lib.hexdump(msg) # sys.exit(0) link = Link.Make( ) # print link.device with link: modem = Modem(link) print modem modem.init_modem( ) with modem.remote( ) as control: # now in remote command mode. remote = Remote(link, serial) model = remote.query(commands.ReadPumpModel) print model
def on_response (self, data): print "read once is {}".format(len(data)) print lib.hexdump(bytearray(data))
parser.add_argument('--model', '-M', default='mmblelink', help="Name to send") parser.add_argument('mac', help='MAC address of rileylink') parser.add_argument('serial', help='Serial of fake pump to emulate.') parser.add_argument('--timezone', '-Z', type=gettz, default=gettz( )) parser.add_argument('--out', '-o', type=argparse.FileType('w'), default='-') argcomplete.autocomplete(parser) return parser if __name__ == '__main__': from mmblelink.monitor import Monitor, choose_rx_channel as choose_channel from mmblelink.link import Link parser = setup_argparser( ) args = parser.parse_args( ) print "radio" print lib.hexdump(FourBySix.encode(bytearray(str('a79090908d090336363680').decode('hex')))) if args.verbosity > 0: print args if args.mac and args.serial: mac = args.mac link = Link(mac, sleep_interval=args.sleep_interval) link.open( ) monitor = Monitor(link, RX=choose_channel(args.rx), sleep_interval=args.sleep_interval, timeout=args.timeout, verbosity=args.verbosity) state = States(args.serial, args.model) emulate = PumpEmulate(monitor, args.serial, args.model) try: emulate.listen(state, strict=args.strict) except (KeyboardInterrupt), e: if args.verbosity > 0: print "Quitting"
def write (self, data): log.info('WRITE %s\n%s' % (len(data), lib.hexdump(data))) self.epout.write(data)
def read(self): data = bytearray(self.epin.read(self.blocksize)) log.info('READ %s\n%s' % (len(data), lib.hexdump(data))) return data
def find_dates(stream): records = [] errors = [] bolus = bytearray() extra = bytearray() opcode = '' for B in iter(lambda: bytearray(stream.read(2)), bytearray("")): opcode = B[0] #bolus.append(B) bolus.extend(B) head_length = Record.lookup_head(opcode) body_length = Record.lookup_body(opcode) date_length = Record.lookup_date(opcode) total = len(bolus) if total < head_length: bolus.extend(bytearray(stream.read(head_length - total))) variable_read = Record.variable_read(opcode, bolus) if variable_read > 2: #print "super special" bolus.extend(bytearray(stream.read(variable_read))) #print lib.hexdump( bolus ) opcode = bolus[variable_read] #print "NEW OPCODE %#04x" % opcode head_length = Record.lookup_head(opcode) body_length = Record.lookup_body(opcode) total = len(bolus) - variable_read if total < head_length: bolus.extend(stream.read(head_length - total)) total = len(bolus) #body_length = Record.lookup_body(opcode) #date_length = Record.lookup_date(opcode) #total = len(bolus) total = len(bolus) head_length = total head = bolus[:max(total, 1)] bolus.extend(bytearray(stream.read(date_length))) date = bolus[head_length:head_length + date_length] total = len(bolus) # print repr(bolus), date_length, repr(date) if len(date) < 5: print "DATE LESS THAN 5!", stream.tell() print lib.hexdump(bolus) break records[-1].body.extend(bolus) datetime = parse_date(date) if bytearray([0x00] * max(total - 2, 5)) in bolus: nulls = bytearray(eat_nulls(stream)) pos = stream.tell() if pos > 1021: bolus = bolus + nulls + bytearray(stream.read(-1)) crc = bolus[-2:] nulls = bolus[:-2] print "EOF {} nulls, CRC:".format(len(nulls)) print lib.hexdump(crc) else: print total, ' ', max(total - 2, 5) print lib.hexdump([0x00] * min(total, 5)) print print "TOO MANY NULLS, BAILING ON STREAM at %s " % stream.tell( ) print "bolus" print lib.hexdump(bolus) print "nulls" print lib.hexdump(nulls) print "MISSING: ARE THERE 32 more bytes?" print lib.hexdump(bytearray(stream.read(32))) # records[-1].body.extend(nulls) break if not Record.is_midnight(head): if datetime is None: print("#### MISSING DATETIME @ %s," % stream.tell()), print "reading more to debug %#04x" % opcode print lib.hexdump(bolus, indent=4) print int_dump(bolus, indent=11) extra = bytearray(stream.read(32)) print "##### DEBUG HEX" print lib.hexdump(extra, indent=4) print "##### DEBUG DECIMAL" print int_dump(extra, indent=11) if history.parse_date(bolus): print "XXX:???:XXX", history.parse_date(bolus).isoformat() break if datetime is not None or Record.is_midnight(head): body = bytearray(stream.read(body_length)) bolus.extend(body) if False or Record.seeks_null(opcode, body): print "should eat up to null, second %s" % repr(body[1:]) if body[1:]: if body[-1] != 0x00: extra = seek_null(stream) print "found %s extra" % len(extra) body.extend(extra) bolus.extend(extra) epi = bytearray(stream.read(date_length)) finished = parse_date(epi) record = Record(head, date, body) prefix = "#### RECORD %s %s" % (len(records), str(record)) print record.pformat(prefix) print "" records.append(record) bolus = bytearray() opcode = '' return records
def read (self): data = bytearray(self.epin.read(self.blocksize)) log.info('READ %s\n%s' % (len(data), lib.hexdump(data))) return data
def read(self, c=64): r = self.requestor.read_by_handle(self.read_handle) io.info('usb.read.len: %s' % (len(r))) io.info('usb.read.raw:\n%s' % (lib.hexdump(bytearray(r[0])))) return bytearray(r[0])
def on_notification(self, handle, data): print "ok ...", handle print lib.hexdump(data)
def write(self, string): r = self.requestor.write_by_handle(self.write_handle, str(string)) io.info('usb.write.len: %s\n%s' % (len(string), lib.hexdump(string))) return r
def on_response(self, name): print "data is ", lib.hexdump(bytearray(self.resp.received()[0]))
def on_response(self, data): print "read once is {}".format(len(data)) print lib.hexdump(bytearray(data))
devices = scanner() for addr, name in devices.items(): print """{addr} {name}""".format(addr=addr, name=name) else: link = Link(mac) link.open() while True: op = CountPackets(link) op.operate() count = ord(op.resp.received()[0]) if count < 1: print "sleeping" time.sleep(.150) else: for buf in link.dump_rx_buffer(): print lib.hexdump(buf) #while link.received( ) > 0: # print lib.hexdump(link.read( )) #op = DrainRXBuffer(link) #op.operate( ) op = CountPackets(link) op = IterReader(link) op.operate() #while link.received( ) > 0: # print lib.hexdump(link.read( )) link.close() ##### # EOF
bytearray([ 0x30, 0xa7 ]) + \ bytearray(str(serial).decode('hex')) + \ bytearray([ msg.code, 0x00 ]) crc = lib.CRC8.compute(op[33:]) length = bytearray([len(op) + 1]) return prefix + length + op + bytearray([crc]) if __name__ == '__main__': import sys, os logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) from link import Link from modem import Modem serial = os.environ.get('SERIAL') msg = fmt_command(commands.ReadPumpModel(serial=serial), serial=serial) print lib.hexdump(msg) # sys.exit(0) link = Link.Make() # print link.device with link: modem = Modem(link) print modem modem.init_modem() with modem.remote() as control: # now in remote command mode. remote = Remote(link, serial) model = remote.query(commands.ReadPumpModel) print model
def clearBuffers(self): garbage = -1 while garbage: garbage = bytearray(self.link.read(64)) log.error("found garbage:\n%s" % lib.hexdump(garbage))
def on_response (self, name): print "data is ", lib.hexdump(bytearray(self.resp.received( )[0]))
def write( self, string ): r = self.requestor.write_by_handle(self.write_handle, str(string)) io.info( 'usb.write.len: %s\n%s' % ( len( string ), lib.hexdump( string ) ) ) return r
def read( self, c=64 ): r = self.requestor.read_by_handle(self.read_handle) io.info( 'usb.read.len: %s' % ( len( r ) ) ) io.info( 'usb.read.raw:\n%s' % ( lib.hexdump( bytearray( r[0] ) ) ) ) return bytearray(r[0])
def write(self, data): log.info('WRITE %s\n%s' % (len(data), lib.hexdump(data))) self.epout.write(data)
devices = scanner( ) for addr, name in devices.items( ): print """{addr} {name}""".format(addr=addr, name=name) else: link = Link(mac) link.open( ) while True: op = CountPackets(link) op.operate( ) count = ord(op.resp.received( )[0]) if count < 1: print "sleeping" time.sleep(.150) else: for buf in link.dump_rx_buffer( ): print lib.hexdump(buf) #while link.received( ) > 0: # print lib.hexdump(link.read( )) #op = DrainRXBuffer(link) #op.operate( ) op = CountPackets(link) op = IterReader(link) op.operate( ) #while link.received( ) > 0: # print lib.hexdump(link.read( )) link.close( ) ##### # EOF