def parse_bundle(bundle, strict=False): """Parse a binary OSC bundle. Returns a generator which walks over all contained messages and bundles recursively, depth-first. Each item yielded is a (timetag, message) tuple. """ if not bundle.startswith(b'#bundle\0'): raise TypeError("Bundle must start with '#bundle\\0'.") ofs = 16 timetag = to_time(*unpack('>II', bundle[8:ofs])) while True: if ofs >= len(bundle): break size = unpack('>I', bundle[ofs:ofs + 4])[0] element = bundle[ofs + 4:ofs + 4 + size] ofs += size + 4 if element.startswith('#bundle'): for el in parse_bundle(element): yield el else: yield timetag, parse_message(element, strict)
def _handle_suback(self): print("_handle_suback") #needed after _packet_handle pack_format = "!H" + str(len(self._in_packet['packet'])-2) + 's' (mid, packet) = struct.unpack(pack_format, self._in_packet['packet']) pack_format = "!" + "B"*len(packet) granted_qos = struct.unpack(pack_format, packet) if self.on_subscribe: self.on_subscribe(self, self._userdata, mid, granted_qos) return MQTT_ERR_SUCCESS
def parse_message(msg, strict=False): args = [] addr, ofs = split_oscstr(msg, 0) if not addr.startswith('/'): raise ValueError("OSC address pattern must start with a slash.") # type tag string must start with comma (ASCII 44) if ofs < len(msg) and msg[ofs] == 44: tags, ofs = split_oscstr(msg, ofs) tags = tags[1:] else: msg = "Missing/invalid OSC type tag string." if strict: raise ValueError(msg) else: log.warning(msg + ' Ignoring arguments.') tags = '' for typetag in tags: size = 0 if typetag in 'ifd': size = 8 if typetag == 'd' else 4 args.append(unpack('>' + typetag, msg[ofs:ofs + size])[0]) elif typetag in 'sS': s, ofs = split_oscstr(msg, ofs) args.append(s) elif typetag == 'b': s, ofs = split_oscblob(msg, ofs) args.append(s) elif typetag in 'rm': size = 4 args.append(unpack('BBBB', msg[ofs:ofs + size])) elif typetag == 'c': size = 4 args.append(chr(unpack('>I', msg[ofs:ofs + size])[0])) elif typetag == 'h': size = 8 args.append(unpack('>q', msg[ofs:ofs + size])[0]) elif typetag == 't': size = 8 args.append(parse_timetag(msg, ofs)) elif typetag in 'TFNI': args.append({'T': True, 'F': False, 'I': Impulse}.get(typetag)) else: raise ValueError("Type tag '%s' not supported." % typetag) ofs += size return (addr, tags, tuple(args))
def main(): global initrgbdata global ARTNET_header global sock while True: # initrgbdata = initrgbdata[1:] + initrgbdata[0:1] # print(initrgbdata) # time.sleep_ms(25) chain.show(initrgbdata) # print("waiting to receive message") # sn = sock.getsockname() try: data = sock.recv(530) # print("received data: ", len(data)) except: # print("no data") continue # print "received bytes: ", len(data) if data[0:7] != ARTNET_header: # print("no artnet packet") continue # else: # print("found artnet packet") opcode = ustruct.unpack('H', data[8:10])[0] # print(hex(opcode)) if opcode == 0x5000: data_length = ustruct.unpack('>H', data[16:18])[0] # print("data length: ", data_length) rgbdata = [] ndx = 0 while ndx < data_length and ndx < CHAIN_LEN * 3: rgb = [0, 0, 0] i = 0 while ndx+i < data_length and i < 3: rgb[i] = int(data[18+ndx+i]) # print(str(data[18+ndx+i])) i += 1 rgbdata.append(tuple(rgb)) ndx += 3 # chain.show(rgbdata[0:CHAIN_LEN-1]) # print(rgbdata[0]) initrgbdata = rgbdata[0:CHAIN_LEN]
def rd16( self, addr ): """ read a word (16 bits) @ addr """ # Status: Certified! self.__start( addr ) _bytes = self.spi.read( 2 ) # read 2 bytes self.__end() return ustruct.unpack( '>H', _bytes )[0] # was initialy '<H' ?
def minmax(): global offset global rate reg = register min_temp = 1000 max_temp = -1000 for i in range(0, 64): val = ustruct.unpack('<h', i2c.readfrom_mem(i2c_address, reg, 2))[0] tmp = getval(val) if tmp < min_temp: min_temp = tmp if max_temp < tmp: max_temp = tmp reg += 2 diff = max_temp - min_temp # add some margin diff *= 1.4 rate = len(colors) / diff offset = min_temp * 0.8 lcd.clear() lcd.print('min: ' + '{:.2f}'.format(min_temp), 0, 0) lcd.print('max: ' + '{:.2f}'.format(max_temp), 0, 10) lcd.print('rate: ' + '{:.2f}'.format(rate), 0, 20) lcd.print('offset: ' + '{:.2f}'.format(offset), 0, 30)
def _handle_connack(self): print("_handle_connack") #needed if len(self._in_packet['packet']) != 2: return MQTT_ERR_PROTOCOL (flags, result) = struct.unpack("!BB", self._in_packet['packet']) # Do now support downgrade to MQTT v3.1 if result == 0: self._state = mqtt_cs_connected print("_handle_connack: self._state =", self._state) if self.on_connect: flags_dict = dict() flags_dict['session present'] = flags & 0x01 self.on_connect(self, self._userdata, flags_dict, result) if result == 0: rc = 0 return rc elif result > 0 and result < 6: return MQTT_ERR_CONN_REFUSED else: return MQTT_ERR_PROTOCOL
def _register_short(self, register, value=None, buf=bytearray(2)): if value is None: self.i2c.readfrom_mem_into(self.address, register, buf) return ustruct.unpack("<h", buf)[0] ustruct.pack_into("<h", buf, 0, value) return self.i2c.writeto_mem(self.address, register, buf)
def time(ms_accuracy=False): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b addr = socket.getaddrinfo(host, 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() sec = struct.unpack("!I", msg[40:44])[0] - NTP_DELTA frac = struct.unpack("!I", msg[44:48])[0] * MILLIS_PER_SECOND >> 32 if ms_accuracy: return sec, frac return sec
def altitude(self): """Read the altitude as calculated based on the sensor pressure and previously configured pressure at sea-level. This will return a value in meters. Set the sea-level pressure by updating the sealevel_pressure property first to get a more accurate altitude value. """ # First poll for a measurement to be finished. self._poll_reg1(_MPL3115A2_CTRL_REG1_OST) # Set control bits for pressure reading. self._ctrl_reg1 |= 0b10000000 # Turn on bit 0, ALT. self._write_u8(_MPL3115A2_CTRL_REG1, self._ctrl_reg1) self._ctrl_reg1 |= 0b00000010 # Set OST to 1 to start measurement. self._write_u8(_MPL3115A2_CTRL_REG1, self._ctrl_reg1) # Poll status for PDR to be set. while self._read_u8(_MPL3115A2_REGISTER_STATUS) & _MPL3115A2_REGISTER_STATUS_PDR == 0: time.sleep(0.01) # Read 3 bytes of altitude data into buffer. # Yes even though this is the address of the pressure register it # returns altitude when the ALT bit is set above. self._read_into(_MPL3115A2_REGISTER_PRESSURE_MSB, self._BUFFER, count=3) # Reconstruct signed 32-bit altitude value (actually 24 bits shifted up # and then scaled down). self._BUFFER[3] = 0 # Top 3 bytes of buffer were read from the chip. altitude = struct.unpack('>i', self._BUFFER[0:4])[0] # Scale down to meters. return altitude / 65535.0
def getpwnam(user): passwd = getpwnam_(user) if not passwd: raise KeyError("getpwnam(): name not found: {}".format(user)) passwd_fmt = "SSIISSS" passwd = uctypes.bytes_at(passwd, ustruct.calcsize(passwd_fmt)) passwd = ustruct.unpack(passwd_fmt, passwd) return struct_passwd(*passwd)
def read(self): # Return current mode measurement result in lx. # needs to be on and mode set first data = unpack('>H', self.bus.readfrom(self.addr, 2))[0] count = data >> 8 | (data&0xff)<<8 mode2coeff = 2 if (self.mode & 0x03) == 0x01 else 1 ratio = 1/(1.2 * (self._sensitivity/69.0) * mode2coeff) return ratio*count
def draw_char(self,ch,x,y,*args,**kwargs): if x<-self._font_width or x>=self._width or y<-self._font_height or y>=self._height: return for char_x in range(self._font_width): self._font.seek(2+(ord(ch)*self._font_width)+char_x) line=ustruct.unpack('B',self._font.read(1))[0] for char_y in range(self._font_height): if(line>>char_y)&0x1: self._pixel(x+char_x,y+char_y,*args,**kwargs)
def master(): csn = Pin(cfg['csn'], mode=Pin.OUT, value=1) ce = Pin(cfg['ce'], mode=Pin.OUT, value=0) if cfg['spi'] == -1: spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso'])) nrf = NRF24L01(spi, csn, ce, payload_size=8) else: nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8) nrf.open_tx_pipe(pipes[0]) nrf.open_rx_pipe(1, pipes[1]) nrf.start_listening() num_needed = 16 num_successes = 0 num_failures = 0 led_state = 0 print('NRF24L01 master mode, sending %d packets...' % num_needed) while num_successes < num_needed and num_failures < num_needed: # stop listening and send packet nrf.stop_listening() millis = utime.ticks_ms() led_state = max(1, (led_state << 1) & 0x0f) print('sending:', millis, led_state) try: nrf.send(struct.pack('ii', millis, led_state)) except OSError: pass # start listening again nrf.start_listening() # wait for response, with 250ms timeout start_time = utime.ticks_ms() timeout = False while not nrf.any() and not timeout: if utime.ticks_diff(utime.ticks_ms(), start_time) > 250: timeout = True if timeout: print('failed, response timed out') num_failures += 1 else: # recv packet got_millis, = struct.unpack('i', nrf.recv()) # print response and round-trip delay print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)') num_successes += 1 # delay then loop utime.sleep_ms(250) print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
def _handle_publish(self): rc = 0 print("_handle_publish") #needed after packet_handle header = self._in_packet['command'] #!H = ! means Network Byte Order, Size, and Alignment with H means unsigned short 2 bytes # For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string # return mtPacket(0b00110001, mtStr(topic), data) pack_format = "!H" + str(len(self._in_packet['packet'])-2) + 's' (slen, packet) = struct.unpack(pack_format, self._in_packet['packet']) pack_format = '!' + str(slen) + 's' + str(len(packet)-slen) + 's' topic, packet = struct.unpack(pack_format, packet) # message.topic = b'test' msg = {} msg['topic'] = topic.decode('utf-8') msg['payload'] = packet msg['timestamp'] = time.time() self.on_message(self, self._userdata, msg) return 0
def __init__(self, mode=BME280_OSAMPLE_1, address=BME280_I2CADDR, i2c=None, **kwargs): # Check that mode is valid. if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4, BME280_OSAMPLE_8, BME280_OSAMPLE_16]: raise ValueError( 'Unexpected mode value {0}. Set mode to one of ' 'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or ' 'BME280_ULTRAHIGHRES'.format(mode)) self._mode = mode self.address = address if i2c is None: raise ValueError('An I2C object is required.') self.i2c = i2c # load calibration data dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26) dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7) self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \ self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \ self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \ _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1) self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7) e4_sign = unpack_from("<b", dig_e1_e7, 3)[0] self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF) e6_sign = unpack_from("<b", dig_e1_e7, 5)[0] self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4) self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0] self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL, bytearray([0x3F])) self.t_fine = 0 # temporary data holders which stay allocated self._l1_barray = bytearray(1) self._l8_barray = bytearray(8) self._l3_resultarray = array("i", [0, 0, 0])
def __init__(self, mode=BME280_OSAMPLE_8, address=BME280_I2CADDR, i2c=None, **kwargs): # Check that mode is valid. if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4, BME280_OSAMPLE_8, BME280_OSAMPLE_16]: raise ValueError( 'Unexpected mode value {0}. Set mode to one of ' 'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or ' 'BME280_ULTRAHIGHRES'.format(mode)) self._mode = mode self.address = address if i2c is None: raise ValueError('An I2C object is required.') self.i2c = i2c self.__sealevel = 101325 # load calibration data dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26) dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7) self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \ self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \ self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \ _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1) self.dig_H2, self.dig_H3, self.dig_H4,\ self.dig_H5, self.dig_H6 = unpack("<hBbhb", dig_e1_e7) # unfold H4, H5, keeping care of a potential sign self.dig_H4 = (self.dig_H4 * 16) + (self.dig_H5 & 0xF) self.dig_H5 //= 16 self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL, bytearray([0x3F])) self.t_fine = 0 # temporary data holders which stay allocated self._l1_barray = bytearray(1) self._l8_barray = bytearray(8) self._l3_resultarray = array("i", [0, 0, 0])
def time(): NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b addr = socket.getaddrinfo(host, 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) res = s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA
def ntp(): # noqa ntp_query = bytearray(48) ntp_query[0] = 0x1b addr = socket.getaddrinfo('pool.ntp.org', 123)[0][-1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1) s.sendto(ntp_query, addr) msg = s.recv(48) s.close() val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA
def decode_payload(payload): """ Decode message payload :param payload: byte stream representing the message payload :return: an array of 8 float [stab_Kp,stab_Kd,stab_Ki,Max Increment,gyro_Kp,gyro_Kd,gyro_Ki,gyro_Max Increment] """ pid_settings = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] for i in range(0, 8): pid_settings[i] = ustruct.unpack('>f', payload[i*4:i*4 + 4])[0] return pid_settings
def poll(self, timeout=-1): s = bytearray(self.evbuf) while True: n = epoll_wait(self.epfd, s, 1, timeout) if not os.check_error(n): break # TODO: what about timeout value? res = [] if n > 0: vals = struct.unpack(epoll_event, s) res.append((vals[1], vals[0])) return res
def GetCharacterData(self,c): uni=ord(c) if uni not in range(self.first_char,self.last_char): return None char_info_address=self.first_char_info_address+(uni-self.first_char)*6 buffer=bytearray(6) esp.flash_read(char_info_address,buffer) ptr_char_data,len=ustruct.unpack('IH',buffer) if(ptr_char_data)==0 or(len==0): return None buffer=bytearray(len) esp.flash_read(ptr_char_data+self.font_address,buffer) return buffer
def __init__(self, font_address=0x300000): self.font_address = font_address buffer = bytearray(18) esp.flash_read(self.font_address, buffer) self.header, \ self.height, \ self.width, \ self.baseline, \ self.x_height, \ self.Y_height, \ self.first_char,\ self.last_char = ustruct.unpack('4sHHHHHHH', buffer) self.first_char_info_address = self.font_address + 18
def temperature(self): """Read the temperature as measured by the sensor in degrees Celsius. """ # Poll status for TDR to be set. while self._read_u8(_MPL3115A2_REGISTER_STATUS) & _MPL3115A2_REGISTER_STATUS_TDR == 0: time.sleep(0.01) # Read 2 bytes of data from temp register. self._read_into(_MPL3115A2_REGISTER_TEMP_MSB, self._BUFFER, count=2) # Reconstruct signed 12-bit value. temperature = struct.unpack('>h', self._BUFFER[0:2])[0] temperature >>= 4 # Scale down to degrees Celsius. return temperature / 16.0
def ilistdir_ex(path="."): dir = opendir_(path) if not dir: raise_error() res = [] dirent_fmt = "LLHB256s" while True: dirent = readdir_(dir) if not dirent: break dirent = ffi.as_bytearray(dirent, struct.calcsize(dirent_fmt)) dirent = struct.unpack(dirent_fmt, dirent) yield dirent
def default_remote_id(): """generate remote id based on machine.unique_id()""" import uhashlib from ustruct import unpack # we compute a hash of board's unique_id, since a boards manufactured # closely together probably share prefix or suffix, and I don't know # which one. we want to avoid accidental remote_id clashes unique_hash = uhashlib.sha256(machine.unique_id()).digest() # and a 4 byte prefix of a sha256 hash is more than enough uint32 = unpack("I", unique_hash[:4])[0] # let's mask it to 26 bits uint26 = uint32 & (2**26 - 1) return uint26
def DispChar(self, s, x, y, mode=TextMode.normal): if self.f is None: return for c in s: data = self.f.GetCharacterData(c) if data is None: x = x + self.width continue width, bytes_per_line = ustruct.unpack('HH', data[:4]) # print('character [%d]: width = %d, bytes_per_line = %d' % (ord(c) # , width, bytes_per_line)) for h in range(0, self.f.height): w = 0 i = 0 while w < width: mask = data[4 + h * bytes_per_line + i] if (width - w) >= 8: n = 8 else: n = width - w py = y + h page = py >> 3 bit = 0x80 >> (py % 8) for p in range(0, n): px = x + w + p c = 0 if (mask & 0x80) != 0: if mode == TextMode.normal or \ mode == TextMode.trans: c = 1 if mode == TextMode.rev: c = 0 if mode == TextMode.xor: c = self.buffer[page * 128 + px] & bit if c != 0: c = 0 else: c = 1 print("px = %d, py = %d, c = %d" % (px, py, c)) super().pixel(px, py, c) else: if mode == TextMode.normal: c = 0 super().pixel(px, py, c) if mode == TextMode.rev: c = 1 super().pixel(px, py, c) mask = mask << 1 w = w + 8 i = i + 1 x = x + width + 1
def graph(): global offset global rate reg = register for ic in range(0, 8): for ir in range(0, 8): val = ustruct.unpack('<h', i2c.readfrom_mem(i2c_address, reg, 2))[0] tmp = (getval(val) - offset) * rate if tmp < 0: tmp = 0 if 127 < tmp: tmp = 127 lcd.rect((8-ic) * 30 + 40, ir * 30, 30, 30, 0, colors[int(tmp)]) reg += 2
def ilistdir(path="."): dir = opendir_(path) if not dir: raise_error() res = [] dirent_fmt = "LLHB256s" while True: dirent = readdir_(dir) if not dirent: break import uctypes dirent = uctypes.bytes_at(dirent, struct.calcsize(dirent_fmt)) dirent = struct.unpack(dirent_fmt, dirent) dirent = (dirent[-1].split(b'\0', 1)[0], dirent[-2], dirent[0]) yield dirent
def draw_char(self, ch, x, y, *args, **kwargs): # Don't draw the character if it will be clipped off the visible area. if x < -self._font_width or x >= self._width or \ y < -self._font_height or y >= self._height: return # Go through each column of the character. for char_x in range(self._font_width): # Grab the byte for the current column of font data. self._font.seek(2 + (ord(ch) * self._font_width) + char_x) line = ustruct.unpack('B', self._font.read(1))[0] # Go through each row in the column byte. for char_y in range(self._font_height): # Draw a pixel for each bit that's flipped on. if (line >> char_y) & 0x1: self._pixel(x + char_x, y + char_y, *args, **kwargs)
def read(self): cnt = self._uart.any() if cnt > 250: log.warning("PMSx003: uart overrun") self._uart.read(300) return None if cnt == 0: return None # read first header char while self._state == S_INIT: if cnt == 0: return None if self._assert_byte(self._uart.read(1), 0x42): self._state = S_STARTED cnt -= 1 # read second header char if self._state == S_STARTED: if cnt == 0: return None if not self._assert_byte(self._uart.read(1), 0x4D): self._state = S_INIT return None cnt -= 1 self._state = S_LEN # read packet length if self._state == S_LEN: if cnt < 2: return None hdr = self._uart.read(2) if len(hdr) != 2: log.warning("PMSx003: len vanished") self._state = S_INIT return None ll = hdr[0] * 256 + hdr[1] cnt -= 2 # print("PMSx003: len={}".format(ll)) if ll != 2 * 13 + 2: log.warning("PMSx003: bad length ({})".format(ll)) self._state = S_INIT return None self._state = S_DATA # read packet body if self._state == S_DATA: if cnt < 28: return None read_buffer = self._uart.read(28) self._state = S_INIT if len(read_buffer) != 28: log.warning("PMSx003: data vanished") return None if False: for i in range(len(read_buffer)): print("0x{:02x} ".format(read_buffer[i]), end="") print(" (cnt={})".format(cnt - 28)) data = struct.unpack("!HHHHHHHHHHHHBBH", read_buffer) # verify checksum checksum = 0x42 + 0x4D + 28 for c in read_buffer[0:26]: checksum += c if checksum == data[PMS_CHECKSUM]: # print("PMSx003:", data) return (data[PMS_PM2_5_ATM], data[PMS_PCNT_0_3] - data[PMS_PCNT_2_5]) trig(1) log.warning("PMSx003: bad checksum") return None
print("SKIP") raise SystemExit # check maximum pack on 32-bit machine print(struct.pack("<I", 2**32 - 1)) print(struct.pack("<I", 0xffffffff)) # long long ints print(struct.pack("<Q", 2**64 - 1)) print(struct.pack(">Q", 2**64 - 1)) print(struct.pack("<Q", 0xffffffffffffffff)) print(struct.pack(">Q", 0xffffffffffffffff)) print(struct.pack("<q", -1)) print(struct.pack(">q", -1)) print(struct.pack("<Q", 1234567890123456789)) print(struct.pack("<q", -1234567890123456789)) print(struct.pack(">Q", 1234567890123456789)) print(struct.pack(">q", -1234567890123456789)) print(struct.unpack("<Q", b"\x12\x34\x56\x78\x90\x12\x34\x56")) print(struct.unpack(">Q", b"\x12\x34\x56\x78\x90\x12\x34\x56")) print(struct.unpack("<q", b"\x12\x34\x56\x78\x90\x12\x34\xf6")) print(struct.unpack(">q", b"\xf2\x34\x56\x78\x90\x12\x34\x56")) # check maximum unpack print(struct.unpack("<I", b"\xff\xff\xff\xff")) print(struct.unpack("<Q", b"\xff\xff\xff\xff\xff\xff\xff\xff")) # check small int overflow print(struct.unpack("<i", b'\xff\xff\xff\x7f')) print(struct.unpack("<q", b'\xff\xff\xff\xff\xff\xff\xff\x7f'))
def read_word2(self, reg): self.bus.readfrom_mem_into(self.address, reg, self.wordbuf) return unpack('>h', self.wordbuf)[0]
print("wrong adr {} instead of {}".format(adr_rx, adr)) return retval #def dac81408_set_range(cfg_string): i2c = I2C(2, freq=100000) adr = 0x62 >> 1 lt3582 = LT3582(i2c, adr) volt_p = 10 volt_n = -10 for reg in range(5): print("reg {}:".format(reg)) print(bin(ustruct.unpack("<b", i2c.readfrom_mem(adr, reg, 1))[0])) lt3582.set_voltage(volt_p, volt_n) spi = machine.SPI(2, baudrate=156250, polarity=0, phase=1, bits=8) cs = machine.Pin('I0', mode=machine.Pin.OUT) cs.high() val = 0b0101010100100 & (~(1 << 5)) #disable power down dac81408_writeReg(spi, cs, DAC81408_SPICONFIG, val) retval = dac81408_readReg(spi, cs, DAC81408_DEVICEID) #read chip id if (retval >> 2) != 0x298: print('did not receive correct device id of DAC81408') print('got: {} instead of 0x298'.format(hex(retval >> 2)))
def _set_value(self, value, register, bit_mask): ctrl_byte = self.i2c.readfrom_mem(self.bme_i2c_addr, register, 1) ctrl_byte = unpack('<b', ctrl_byte)[0] out_value = (ctrl_byte & bit_mask) | value self.i2c.writeto_mem(self.bme_i2c_addr, register, bytearray([out_value]))
def _register_six_char(self, register, buf=bytearray(6)): self.i2c.readfrom_mem_into(self.address, register, buf) return struct.unpack("<BBBBBB", buf)
def swab32(n): # endian swap: 32 bits return ustruct.unpack('>I', ustruct.pack('<I', n))[0]
def uint256_from_str(s): r = 0 t = struct.unpack("<IIIIIIII", s[:32]) for i in range(8): r += t[i] << (i * 32) return r
def start_socks5_session(socket, proxy, cf): """ask the proxy server to connect us to the cloud application that is listening on port: destport at IP: destip""" destadd = cf[0] destport = cf[1] # check if the user supplied us with authentication if proxy[3] != None and proxy[4] != None: #=>>> we support both None authentication and authentication with username+password #ToDo: make support for other type of authentication socket.sendall(b"\x05\x02\x00\x02") #05=the protocol version, #02=number of suported methods (2 in our case) -- see rfc 1928 #00 the code for None authentication #02 the code for authentication with username and password else: #we suport only None authentication socket.sendall(b"\x05\x01\x00") chosenauth = list(__recvall(socket, 2)) # the first byte is the socks version. must be 5. the second is the authentication method selected if chosenauth[0] != list(b"\x05")[0]: socket.close() # bad guys are sitting at the server side raise GeneralProxyError((1, _generalerrors[1])) if chosenauth[1] == list(b"\x00")[0]: pass # No need to send username and password elif chosenauth[1] == list(b"\x02")[0]: #-> The server selected authetication method with username and password. We should send them :( # we should send the following: sub_negotioation version + length of username + username + length of password + password _username = proxy[3].encode() _password = proxy[4].encode() socket.sendall(b"\x01" + chr(len(_username)) + _username + chr(len(_password)) + _password) #The reply: consistes of 2 bytes. first byte is the sus_negotioation version. second is the answer (Accept, or not) -> auth_reply = list(__recvall(socket, 2)) if auth_reply[0] != list(b"\x01")[0]: socket.close() # bad guys are sitting at the server side raise GeneralProxyError((1, _generalerrors[1])) if auth_reply[1] != list(b"\x00")[0]: socket.close() # incorrect username or password! raise Socks5AuthError((3, _socks5autherrors[3])) else: socket.close( ) # the server didn't accept our authentication methods :( shit!! if chosenauth[1] == list(b"\xff")[0]: raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError( (1, _generalerrors[1])) # the bad guys again #Ask the proxy to establish a connection with the target Cloud application :) #We support only tcp. # ToDo: make support for udp connection_request = b'\x05\x01\x00' # Version + command (tcp) + reserved byte #ToDo: support BIND and UDP assoiciate try: ipadd = _dotted_ip_to_bits(destadd) connection_request = connection_request + b'\x01' + ipadd except ValueError: #it's not an ip address !! if proxy[2] == True: #means we want to enable remote dns ipadd = None connection_request = connection_request + b'\x03' + chr( len(destadd.encode())) + destadd.encode() else: #local dns resolving! ipadd = _dotted_ip_to_bits( usocket.getaddrinfo(destadd, destport)[0][-1][0]) connection_request = connection_request + b"\x01" + ipadd connection_request = connection_request + ustruct.pack(">H", destport) socket.sendall(connection_request) #response: connection_response = list(__recvall(socket, 4)) if connection_response[0] != list(b'\x05')[0]: socket.close() # bad guys are sitting at the server side raise GeneralProxyError((1, _generalerrors[1])) elif connection_response[1] != list(b'\x00')[0]: socket.close() if ord(connection_response[1]) <= 8: raise Socks5Error((ord(connection_response[1]), _generalerrors[ord(connection_response[1])])) else: raise Socks5Error((9, _generalerrors[9])) elif connection_response[3] == list(b'\x01')[0]: proxy_bound_address = __recvall(socket, 4) elif connection_response[3] == list(b'\x03')[0]: connection_response = connection_response + __recvall(socket, 1) proxy_bound_address = __recvall(socket, ord(connection_response[4])) else: socket.close() raise GeneralProxyError((1, _generalerrors[1])) proxy_bound_port = ustruct.unpack('>H', __recvall(socket, 2))[0] __proxysockname = (_bits_to_dotted_ip(proxy_bound_address), proxy_bound_port ) # 32 bit binary ip address (4 bytes) , int port return __proxysockname
# Using structs which are not aligned on machine word boundary try: import ustruct as struct except: try: import struct except ImportError: print("SKIP") raise SystemExit buf = struct.pack("I", 0x01020304) buf_offseted = b"\xff" + buf v1 = struct.unpack("I", buf) v2 = struct.unpack_from("I", buf_offseted, 1) print("1:", v1 == v2) v3 = struct.unpack("I", memoryview(buf_offseted)[1:]) print("2:", v1 == v3) wbuf = bytearray(20) struct.pack_into("I", wbuf, 1, 0x01020304) print("3:", bytes(wbuf[1:]).startswith(buf)) wbuf = bytearray(20) struct.pack_into("I", memoryview(wbuf)[1:], 0, 0x01020304) print("4:", bytes(wbuf[1:]).startswith(buf))
def _register_three_shorts(self, register, buf=bytearray(6)): self.i2c.readfrom_mem_into(self.address, register, buf) return ustruct.unpack(">hhh", buf)
def thermistor(self): data = self.i2c.readfrom_mem(self.addr, AMG8833_TTHL, 2) return unpack('>H', data)[0]
def _decode_single(single): return ustruct.unpack("!f", ustruct.pack("!I", single))[0]
def readiacctemperature(): k = i2c.readfrom_mem(0x6B, 0x15, 2) t = ustruct.unpack("<h", k) return t[0] / 18.1 + 28.6 # worked out experimentally in fridge
def str2xfp(txt): # Inverse of xfp2str return ustruct.unpack('<I', a2b_hex(txt))[0]
def _calc_from_int(self, integer): struct_int = struct.pack('>i', integer) b = struct.unpack('>BBBB', struct_int) return b
def deser_uint256(f): r = 0 for i in range(8): t = struct.unpack("<I", f.read(4))[0] r += t << (i * 32) return r
def _read_register(self, register): result = unpack('BB', self._i2c.readfrom_mem(self._addr, register, 2)) return ((result[1] << 8) | result[0])
def _get_value(self, register, bit_mask): ctrl_byte = self.i2c.readfrom_mem(self.bme_i2c_addr, register, 1) ctrl_byte = unpack('<b', ctrl_byte)[0] return ctrl_byte & bit_mask
class _websocket: def __init__(self, s): self.s = s #发送二进制Blob def write(self, data): l = len(data) if l < 126: # TODO: hardcoded "binary" type hdr = struct.pack(">BB", 0x82, l) else: hdr = struct.pack(">BBH", 0x82, 126, l) self.s.send(hdr) self.s.send(data) #发送文本 def send(self,msg,fin=True): msg=msg.encode('utf-8') data = struct.pack('B', 129) if fin else struct.pack('B', 0) msg_len = len(msg) if msg_len <= 125: data += struct.pack('B', msg_len) elif msg_len <= (2**16 - 1): data += struct.pack('!BH', 126, msg_len) elif msg_len <= (2**64 - 1): data += struct.pack('!BQ', 127, msg_len) else: # 分片传输超大内容(应该用不到) while True: fragment = msg[:(2**64 - 1)] msg -= fragment if msg > (2**64 - 1): self.s.send(fragment, False) else: self.s.send(fragment) data += bytes(msg) print (data) self.s.send(data) def recvexactly(self, sz): res = b"" while sz: data = self.s.recv(sz) print(sz) if not data: break res += data sz -= len(data) return res def read(self): #while True: #禁用循环 带到外面自行循环 hdr = self.recvexactly(2) print (hdr) assert len(hdr) == 2 firstbyte, secondbyte = struct.unpack(">BB", hdr) mskenable = True if secondbyte & 0x80 else False length = secondbyte & 0x7f if DEBUG: print('test length=%d' % length) print('mskenable=' + str(mskenable)) if length == 126: hdr = self.recvexactly(2) assert len(hdr) == 2 (length,) = struct.unpack(">H", hdr) if length == 127: hdr = self.recvexactly(8) assert len(hdr) == 8 check: -1 (length,) = struct.unpack(">Q", hdr) if DEBUG: print('length=%d' % length) opcode = firstbyte & 0x0f if opcode == 8: self.s.close() return '' fin = True if firstbyte&0x80 else False if DEBUG: print('fin='+str(fin)) print('opcode=%d'%opcode) if mskenable: hdr = self.recvexactly(4) assert len(hdr) == 4 (msk1,msk2,msk3,msk4) = struct.unpack(">BBBB", hdr) msk = [msk1,msk2,msk3,msk4] #print('msk'+str(msk)) # debugmsg("Got unexpected websocket record of type %x, skipping it" % fl) data = [] while length: skip = self.s.recv(length) # debugmsg("Skip data: %s" % skip) length -= len(skip) data.extend(skip) newdata = [] #解码数据 for i,item in enumerate(data): j = i % 4 newdata.append(chr(data[i] ^ msk[j])) res = ''.join(newdata) if res!='': return res
def deserialize(self, f): self.nValue = struct.unpack("<q", f.read(8))[0] self.scriptPubKey = deser_string(f)
def deserialize(self, f): self.prevout = COutPoint() self.prevout.deserialize(f) self.scriptSig = deser_string(f) self.nSequence = struct.unpack("<I", f.read(4))[0]
def get_a_x(self): self.i2c.writeto(self.addr, b'\x02', False) buf = self.i2c.readfrom(self.addr, 2) x = ustruct.unpack('h', buf)[0] return x / 4 / 4096
def _c_tm_to_tuple(tm): t = ustruct.unpack("@iiiiiiiii", tm) return _struct_time(t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8])
def read(self, internal=False, raw=False): """ Read the measured temperature. If ``internal`` is ``True``, return a tuple with the measured temperature first and the internal reference temperature second. If ``raw`` is ``True``, return the values as 14- and 12- bit integers, otherwise convert them to Celsuius degrees and return as floating point numbers. """ if hasattr(self.cs, 'off'): self.cs.off() else: self.cs.value = 0 self.spi.readinto(self.data) if hasattr(self.cs, 'on'): self.cs.on() else: self.cs.value = 1 # The data has this format: # 00 --> OC fault # 01 --> SCG fault # 02 --> SCV fault # 03 --> reserved # 04 -. --> LSB # 05 | # 06 | # 07 | # > reference # 08 | # 09 | # 10 | # 11 | # 12 | # 13 | # 14 | --> MSB # 15 -' --> sign # # 16 --> fault # 17 --> reserved # 18 -. --> LSB # 19 | # 20 | # 21 | # 22 | # 23 | # > temp # 24 | # 25 | # 26 | # 27 | # 28 | # 29 | # 30 | --> MSB # 31 -' --> sign if self.data[3] & 0x01: raise RuntimeError("thermocouple not connected") if self.data[3] & 0x02: raise RuntimeError("short circuit to ground") if self.data[3] & 0x04: raise RuntimeError("short circuit to power") if self.data[1] & 0x01: raise RuntimeError("faulty reading") temp, refer = ustruct.unpack('>hh', self.data) refer >>= 4 temp >>= 2 if raw: if internal: return temp, refer return temp if internal: return temp / 4, refer * 0.0625 return temp / 4
def parseData(self, data): return ustruct.unpack( '>f', ustruct.pack('>BBBB', data[0], data[1], data[2], data[3]))[0]
def pwm(self, index, on=None, off=None): if on is None or off is None: data = self.i2c.readfrom_mem(self.address, 0x06 + 4 * index, 4) return ustruct.unpack('<HH', data) data = ustruct.pack('<HH', on, off) self.i2c.writeto_mem(self.address, 0x06 + 4 * index, data)
def unpack(fmt, buf): return ustruct.unpack(_norm_fmt(fmt), buf)
while True: new_message = client.check_msg() time.sleep_us(1000) if mail_flag == 1: mail_flag = 0 result = ca.verify_hmac(json_message) ticks_2 = utime.ticks_ms() print(utime.ticks_diff(ticks_2, ticks_1)) if result: client.publish(b'Acknowledge', b'Successful Decryption') print("Authentication Passed. Decrypting") (d_iv, d_nodeid, d_data) = ca.decrypt() print("Successful Decryption") accel_val_x = ustruct.unpack("<h", d_data[0:2])[0] accel_val_y = ustruct.unpack("<h", d_data[2:4])[0] accel_val_z = ustruct.unpack("<h", d_data[4:6])[0] if abs(accel_val_x) > 1 or abs(accel_val_y) > 1 or abs( accel_val_z) > 1: led_r.value(1) else: led_r.value(0) curr_temp = twos_comp(int.from_bytes(d_data[6:8], 'big'), 16) * .0078 if curr_temp > (prev_temp + 1): pwm_g.freq(pwm_g.freq() + 5) else: client.publish(b'Acknowledge', b'Failed Authentication')
def deserialize(self, f): self.hash = deser_uint256(f) self.n = struct.unpack("<I", f.read(4))[0]