def _send_connect(self, keepalive): print("_send_connect") remaining_length = 2+6+1+1+2+2+len(self._client_id) #remaining_length = 2+len(protocol) + 1+1+2 + 2+len(self._client_id) connect_flags = 0 connect_flags = connect_flags | 0x02 if self._username: remaining_length = remaining_length + 2+len(self._username) connect_flags = connect_flags | 0x80 if self._password: connect_flags = connect_flags | 0x40 remaining_length = remaining_length + 2+len(self._password) command = CONNECT packet = bytearray() packet.extend(struct.pack("!B", command)) self._pack_remaining_length(packet, remaining_length) #packet.extend(struct.pack("!H"+str(len(protocol))+"sBBH", len(protocol), protocol, proto_ver, connect_flags, keepalive)) packet.extend(struct.pack("!H"+"6"+"sBBH", 6, b"MQIsdp", 3, connect_flags, keepalive)) self._pack_str16(packet, self._client_id) if self._username: self._pack_str16(packet, self._username) if self._password: self._pack_str16(packet, self._password) self._keepalive = keepalive return self._packet_queue(command, packet, 0, 0)
def _send_subscribe(self, dup, topics): print("_send_subscribe") remaining_length = 2 #topic_qos_list = [(topic.encode('utf-8'), qos)] - > [('test', 0)] #remaining_length = 2 + 2+ len('test') +1 --> 9 for t in topics: remaining_length = remaining_length + 2+len(t[0])+1 #SUBSCRIBE = const(0x80) - > 0b10000000 # According to spec the fixed header is 0b10000010 # According to spec the second byte is the remaining length = 2 bytes of varialbe header + payload # If QoS is zero the variable header is 0,0 or if > 1 would be some unique identifier # dup = 0 (I think) # 1<<1 -> 0b00000010 command = SUBSCRIBE | (dup<<3) | (1<<1) packet = bytearray() packet.extend(struct.pack("!B", command)) self._pack_remaining_length(packet, remaining_length) #operates on packet and extends it local_mid = self._mid_generate() packet.extend(struct.pack("!H", local_mid)) for t in topics: self._pack_str16(packet, t[0]) packet.extend(struct.pack("B", t[1])) return (self._packet_queue(command, packet, local_mid, 1), local_mid)
def _pack_str16(self, packet, data): print("_pack_str16") if isinstance(data, bytearray) or isinstance(data, bytes): packet.extend(struct.pack("!H", len(data))) packet.extend(data) elif isinstance(data, str): udata = data.encode('utf-8') pack_format = "!H" + str(len(udata)) + "s" packet.extend(struct.pack(pack_format, len(udata), udata)) else: raise TypeError
def __init__(self, conn, w, h, name): self.conn = conn[0] self.w = w self.h = h self.bpp = 32 self.depth = 24 self.big = True self.true = True self.masks = (255, 255, 255) self.shifts = (16, 8, 0) # HandShake self.send(b"RFB 003.003\n") if self.recv(True) != b"RFB 003.003\n": raise Exception("RFB rejected version proposal") # Security self.send(b"\x00\x00\x00\x01") # ignore instruction to disconnect other clients if self.recv(True)[0] not in (0, 1): print("2b") raise Exception("RFB rejected security none") # ServerInit self.send( pack( ">2H4B3H3B", w, h, self.bpp, self.depth, self.big, self.true, self.masks[0], self.masks[0], self.masks[0], self.shifts[0], self.shifts[1], self.shifts[2], ) + bytes(3) + pack(">L", len(name)) + name ) # we *may* be sent encodings (ignorred) and pixel format self.service_msg_queue()
def SetWriteWindow(self, PageStart, PageStop, ColStart, ColStop): if (PageStart < 0) or (PageStop > 7) or (PageStart > PageStop): return(-1) if (ColStart < 0) or (ColStop > 127) or (ColStart > ColStop): return(-1) self.SendCommand(pack("6B", 0x21, ColStart, ColStop, 0x22, PageStart, PageStop)) return(0)
def __start( self, addr ): """ Start a SPI transaction @ addr """ # Start new transaction self.ssel.value( 1 ) #sleep_ms( 1 ) # 1 Ms between SPI transaction seems right sleep_us( 10 ) self.ssel.value( 0 ) self.spi.write( ustruct.pack( '>H', addr) ) # Convert address in MSB and LSB
def gmtime(t=None): if t is None: t = time() t = int(t) a = ustruct.pack('i', t) tm_p = gmtime_(a) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36))
def _addSensorData(self, packet): #BinaryPayloadContainer ??? if self.getContainerId() == 17: packet.extend(self.getValue()) return if self.getValueType == "boolean": packet.append(0x01) if self.sensorValue["value"] == True else packet.append(0x00) return else: packet.append(0x00) if self.data['booleanMeterValue']: packet.append(0x01) else: packet.append(0x00) if not self.data['booleanMeterValue'] is None: return #ATT LIBRARY USING 'SHORT' where mentioning 'INT' !!!!! if self.data['integerMeterValue']: packet.append(0x01) packet.extend(pack('>h',self.data['integerMeterValue'])) return else: packet.append(0x00) if self.data['doubleMeterValue']: packet.append(0x01) packet.extend(pack('>f',self.data['doubleMeterValue'])) return elif self.data['accelerometerMeterValue']: packet.append(0x03) packet.extend(pack('>fff',self.data['accelerometerMeterValue']['x'], self.data['accelerometerMeterValue']['y'], self.data['accelerometerMeterValue']['z'])) return elif self.data['gpsMeterValue']: packet.append(0x04) packet.extend(pack('>ffff',self.data['gpsMeterValue']['latitude'], self.data['gpsMeterValue']['longitude'], self.data['gpsMeterValue']['altitude'], self.data['gpsMeterValue']['timestamp'])) return else: #Nothing left for now ... so shouldn't really be getting here. packet.append(0x00)
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 __init__(self, conn, w, h, name): self.conn, self.addr = conn self.w = w self.h = h self.bpp = 32 self.depth = 24 self.big = True self.true = True channel_mask = 2**(self.depth//3)-1 self.masks = (channel_mask, channel_mask, channel_mask) self.shifts = (16,8,0) self.name = name self._security = 1 # None/No Security self.encodings = [] # sent post init by client # HandShake self.send( b'RFB 003.003\n' ) if self.recv(True) != b'RFB 003.003\n': raise RfbSessionRejected('version proposal') # Security self.send( pack('>L', self.security) ) # ignore instruction to disconnect other clients if self.recv(True)[0] not in (0,1): raise RfbSessionRejected('no security') # ServerInit self.send( pack('>2H', w, h) \ + ServerSetPixelFormat( self.bpp, self.depth, self.big, self.true, self.masks, self.shifts ) \ + pack('>L', len(name)) \ + name ) # we *may* be sent encodings and pixel format # we *must* process these messages before # sending any rectangles, otherwise we don't # know what encodings or pixel format client # accepts self.service_msg_queue()
def pack_blob(b, encoding='utf-8'): """Pack a bytes, bytearray or tuple/list of ints into a binary OSC blob.""" if isinstance(b, (tuple, list)): b = bytearray(b) elif isinstance(b, str): b = bytes(b, encoding) blen = len(b) b = pack('>I', blen) + b return b + b'\0' * (((blen + 3) & ~0x03) - blen)
def colour_to_pixel(colour, bpp, depth, big, true, masks, shifts): if true: v = 0 for channel, mask, shift in zip(colour, masks, shifts): v += (channel & mask)<<shift return pack( ('>' if big else '<') + \ ('L' if bpp==32 else ('H' if bpp==16 else 'B')), v<<(bpp-depth) if big else v )
def ServerFrameBufferUpdate(rectangles): if rectangles: # empty list is False buffer = bytes() for idx, rect in enumerate(rectangles): b = rect.to_bytes() if b is None: # done with this rectangle del (rectangles[idx]) elif b is False: pass # no update required else: buffer += b return b"\x00\x00" + pack(">H", len(rectangles)) + buffer
def _check_keepalive(self): print("_check_keepalive") now = time.time() print("_check_keepalive: self._last_msg = ", self._last_msg) last_msg = self._last_msg if (self._sock is not None) and (now - last_msg >= self._keepalive): print("_check_keepalive: self._state =", self._state) if self._ping_t == 0: #self._send_pingreq() packet = struct.pack('!BB', PINGREQ, 0) self._packet_queue(PINGREQ, packet, 0, 0) self._last_msg = now
def pack_bundle(bundle): """Return bundle data packed into a binary string.""" data = [] for msg in bundle: if isinstance(msg, Bundle): msg = pack_bundle(msg) elif isinstance(msg, tuple): msg = create_message(*msg) data.append(pack('>I', len(msg)) + msg) return b'#bundle\0' + pack_timetag(bundle.timetag) + b''.join(data)
def to_bytes(self): b = b'' for rect in self.subrectangles: b += rect.to_bytes() return super().to_bytes() \ + pack('>L',len(self.subrectangles)) \ + colour_to_pixel( self.bgcolour, self.bpp, self.depth, self.big, self.true, self.masks, self.shifts ) + b
def to_bytes(self): # non-standard encoding ... don't call super() return colour_to_pixel( self.colour, self.bpp, self.depth, self.big, self.true, self.masks, self.shifts ) \ + pack('>4H', self.x, self.y, self.w, self.h )
def register(self, fd, eventmask=EPOLLIN|EPOLLPRI|EPOLLOUT, retval=None): "retval is extension to stdlib, value to use in results from .poll()." if retval is None: retval = fd s = struct.pack(epoll_event, eventmask, retval) r = epoll_ctl(self.epfd, EPOLL_CTL_ADD, fd, s) if r == -1 and os.errno_.get() == errno.EEXIST: r = epoll_ctl(self.epfd, EPOLL_CTL_MOD, fd, s) os.check_error(r) # We must keep reference to retval, or it may be GCed. And we must # keep mapping from fd to retval to be able to get rid of this retval # reference later. self.registry[fd] = retval
def _server_alive(self): c_time = int(time.time()) if self._m_time != c_time: self._m_time = c_time self._tx_count = 0 if self._wdt: self._wdt.feed() if self._last_hb_id != 0 and c_time - self._hb_time >= MAX_SOCK_TO: return False if c_time - self._hb_time >= HB_PERIOD and self.state == AUTHENTICATED: self._hb_time = c_time self._last_hb_id = self._new_msg_id() self._send(struct.pack(HDR_FMT, MSG_PING, self._last_hb_id, 0), True) return True
def _pack_remaining_length(self, packet, remaining_length): print("_pack_remaining_length") #from _send_subscribe and _send_connect #remaining_bytes = [] ? not used for anything while True: byte = remaining_length % 128 remaining_length = remaining_length // 128 # If there are more digits to encode, set the top bit of this digit if remaining_length > 0: byte = byte | 0x80 #remaining_bytes.append(byte) packet.extend(struct.pack("!B", byte)) if remaining_length == 0: # FIXME - this doesn't deal with incorrectly large payloads return packet
def slave(): 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[1]) nrf.open_rx_pipe(1, pipes[0]) nrf.start_listening() print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)') while True: if nrf.any(): while nrf.any(): buf = nrf.recv() millis, led_state = struct.unpack('ii', buf) print('received:', millis, led_state) for led in leds: if led_state & 1: led.on() else: led.off() led_state >>= 1 utime.sleep_ms(_RX_POLL_DELAY) # Give master time to get into receive mode. utime.sleep_ms(_SLAVE_SEND_DELAY) nrf.stop_listening() try: nrf.send(struct.pack('i', millis)) except OSError: pass print('sent response') nrf.start_listening()
def SendData(self, Data): Msg = pack("BB", self.Addr<<1, 0x40) + Data self.Bus.start() self.Bus.write(Msg) self.Bus.stop()
def pwm(self, index, on=None, off=None): if on is None or off is None: data = self.i2c.mem_read(self.address, 0x06 + 4 * index, 4) return ustruct.unpack('<HH', data) data = ustruct.pack('<HH', on, off) self.i2c.mem_write(data, self.address, 0x06 + 4 * index)
except: try: import struct except ImportError: print("SKIP") raise SystemExit print(struct.calcsize("<bI")) print(struct.unpack("<bI", b"\x80\0\0\x01\0")) print(struct.calcsize(">bI")) print(struct.unpack(">bI", b"\x80\0\0\x01\0")) # 32-bit little-endian specific #print(struct.unpack("bI", b"\x80\xaa\x55\xaa\0\0\x01\0")) print(struct.pack("<l", 1)) print(struct.pack(">l", 1)) print(struct.pack("<i", 1)) print(struct.pack(">i", 1)) print(struct.pack("<h", 1)) print(struct.pack(">h", 1)) print(struct.pack("<b", 1)) print(struct.pack(">b", 1)) print(struct.pack("<bI", -128, 256)) print(struct.pack(">bI", -128, 256)) print(struct.calcsize("100sI")) print(struct.calcsize("97sI")) print(struct.unpack("<6sH", b"foo\0\0\0\x12\x34")) print(struct.pack("<6sH", b"foo", 10000))
def encode(self, value): return pack("<f", value)
def ip32bit(self, target): import ustruct return ustruct.pack('4B', *(int(x) for x in target.split('.')))
def add_environmental_sensor_service(self): env_service_uuid = bytes( reversed([0x42, 0x82, 0x1a, 0x40, 0xe4, 0x77, 0x11, 0xe2, 0x82, 0xd0, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b])) temp_char_uuid = bytes( reversed([0xa3, 0x2e, 0x55, 0x20, 0xe4, 0x77, 0x11, 0xe2, 0xa9, 0xe3, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b])) press_char_uuid = bytes( reversed([0xcd, 0x20, 0xc4, 0x80, 0xe4, 0x8b, 0x11, 0xe2, 0x84, 0x0b, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b])) humidity_char_uuid = bytes( reversed([0x01, 0xc5, 0x0b, 0x60, 0xe4, 0x8c, 0x11, 0xe2, 0xa0, 0x73, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b])) char_format_struct = "<BBHBH" char_format_size = ustruct.calcsize(char_format_struct) max_attr_records = 6 result = self.aci_gatt_add_serv( service_uuid_type=UUID_TYPE_128, service_uuid=env_service_uuid, service_type=PRIMARY_SERVICE, max_attr_records=(1+3*max_attr_records)).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_serv status: {:02x}".format( result.status)) log.info("#env_serv_handle %04x", result.handle) self.env_serv_handle = result.handle # Temperature Characteristic result = self.aci_gatt_add_char( service_handle=self.env_serv_handle, char_uuid_type=UUID_TYPE_128, char_uuid=temp_char_uuid, char_value_len=2, char_properties=CHAR_PROP_NOTIFY|CHAR_PROP_READ, sec_permissions=ATTR_PERMISSION_NONE, gatt_evt_mask=GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char status: {:02x}".format( result.status)) self.temp_char_handle = result.handle log.info("#temp_char_handle: %04x", self.temp_char_handle) uuid16 = ustruct.pack( "<H", CHAR_FORMAT_DESC_UUID) char_format = ustruct.pack( char_format_struct, FORMAT_SINT16, -1, UNIT_TEMP_CELSIUS, 0, 0) result = self.aci_gatt_add_char_desc( service_handle=self.env_serv_handle, char_handle=self.temp_char_handle, desc_uuid_type=UUID_TYPE_16, uuid=uuid16, desc_value_max_len=char_format_size, desc_value_len=char_format_size, desc_value=char_format, sec_permissions=ATTR_PERMISSION_NONE, acc_permissions=ATTR_ACCESS_READ_ONLY, gatt_evt_mask=GATT_DONT_NOTIFY_EVENTS, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char_desc status: {:02x}".format( result.status)) log.debug("aci_gatt_add_char_desc %02x", result.status) # Pressure Characteristic result = self.aci_gatt_add_char( service_handle=self.env_serv_handle, char_uuid_type=UUID_TYPE_128, char_uuid=press_char_uuid, char_value_len=2, char_properties=CHAR_PROP_NOTIFY|CHAR_PROP_READ, sec_permissions=ATTR_PERMISSION_NONE, gatt_evt_mask=GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char status: {:02x}".format( result.status)) self.press_char_handle = result.handle log.info("#press_char_handle: %04x", self.press_char_handle) char_format = ustruct.pack( char_format_struct, FORMAT_SINT24, -5, UNIT_PRESSURE_BAR, 0, 0) result = self.aci_gatt_add_char_desc( service_handle=self.env_serv_handle, char_handle=self.press_char_handle, desc_uuid_type=UUID_TYPE_16, uuid=uuid16, desc_value_max_len=char_format_size, desc_value_len=char_format_size, desc_value=char_format, sec_permissions=ATTR_PERMISSION_NONE, acc_permissions=ATTR_ACCESS_READ_ONLY, gatt_evt_mask=GATT_DONT_NOTIFY_EVENTS, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char_desc status: {:02x}".format( result.status)) log.debug("aci_gatt_add_char_desc %02x", result.status) # Humidity Characteristic result = self.aci_gatt_add_char( service_handle=self.env_serv_handle, char_uuid_type=UUID_TYPE_128, char_uuid=humidity_char_uuid, char_value_len=2, char_properties=CHAR_PROP_NOTIFY|CHAR_PROP_READ, sec_permissions=ATTR_PERMISSION_NONE, gatt_evt_mask=GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char status: {:02x}".format( result.status)) self.humidity_char_handle = result.handle log.info("#humidity_char_handle: %04x", self.humidity_char_handle) char_format = ustruct.pack( char_format_struct, FORMAT_UINT16, -1, UNIT_UNITLESS, 0, 0) result = self.aci_gatt_add_char_desc( service_handle=self.env_serv_handle, char_handle=self.humidity_char_handle, desc_uuid_type=UUID_TYPE_16, uuid=uuid16, desc_value_max_len=char_format_size, desc_value_len=char_format_size, desc_value=char_format, sec_permissions=ATTR_PERMISSION_NONE, acc_permissions=ATTR_ACCESS_READ_ONLY, gatt_evt_mask=GATT_DONT_NOTIFY_EVENTS, encry_key_size=MAX_ENCRY_KEY_SIZE, is_variable=False).response_struct if result.status != BLE_STATUS_SUCCESS: raise ValueError("aci_gatt_add_char_desc status: {:02x}".format( result.status)) log.debug("aci_gatt_add_char_desc %02x", result.status)
def swab32(n): # endian swap: 32 bits return ustruct.unpack('>I', ustruct.pack('<I', n))[0]
def scroll(self, dy): self._scroll = (self._scroll + dy) % self.height self._write(_VSCRSADD, ustruct.pack(">H", self._scroll))
def _readblock(self, x0, y0, x1, y1): self._write(_CASET, ustruct.pack(">HH", x0, x1)) self._write(_PASET, ustruct.pack(">HH", y0, y1)) if data is None: return self._read(_RAMRD, (x1 - x0 + 1) * (y1 - y0 + 1) * 3)
def _writeblock(self, x0, y0, x1, y1, data=None): self._write(_CASET, ustruct.pack(">HH", x0, x1)) self._write(_PASET, ustruct.pack(">HH", y0, y1)) self._write(_RAMWR, data)
def hash143_preimage_hash(self, txi: TxInputType, pubkeyhash: bytes) -> bytes: h_preimage = HashWriter( blake2b( outlen=32, personal=b"ZcashSigHash" + struct.pack("<I", self.tx.branch_id), )) # 1. nVersion | fOverwintered write_uint32(h_preimage, self.tx.version | OVERWINTERED) # 2. nVersionGroupId write_uint32(h_preimage, self.tx.version_group_id) # 3. hashPrevouts write_bytes_fixed(h_preimage, get_tx_hash(self.h_prevouts), TX_HASH_SIZE) # 4. hashSequence write_bytes_fixed(h_preimage, get_tx_hash(self.h_sequence), TX_HASH_SIZE) # 5. hashOutputs write_bytes_fixed(h_preimage, get_tx_hash(self.h_outputs), TX_HASH_SIZE) if self.tx.version == 3: # 6. hashJoinSplits write_bytes_fixed(h_preimage, b"\x00" * TX_HASH_SIZE, TX_HASH_SIZE) # 7. nLockTime write_uint32(h_preimage, self.tx.lock_time) # 8. expiryHeight write_uint32(h_preimage, self.tx.expiry) # 9. nHashType write_uint32(h_preimage, self.get_hash_type()) elif self.tx.version == 4: zero_hash = b"\x00" * TX_HASH_SIZE # 6. hashJoinSplits write_bytes_fixed(h_preimage, zero_hash, TX_HASH_SIZE) # 7. hashShieldedSpends write_bytes_fixed(h_preimage, zero_hash, TX_HASH_SIZE) # 8. hashShieldedOutputs write_bytes_fixed(h_preimage, zero_hash, TX_HASH_SIZE) # 9. nLockTime write_uint32(h_preimage, self.tx.lock_time) # 10. expiryHeight write_uint32(h_preimage, self.tx.expiry) # 11. valueBalance write_uint64(h_preimage, 0) # 12. nHashType write_uint32(h_preimage, self.get_hash_type()) else: raise wire.DataError( "Unsupported version for overwintered transaction") # 10a /13a. outpoint write_bytes_reversed(h_preimage, txi.prev_hash, TX_HASH_SIZE) write_uint32(h_preimage, txi.prev_index) # 10b / 13b. scriptCode script_code = derive_script_code(txi, pubkeyhash) write_bytes_prefixed(h_preimage, script_code) # 10c / 13c. value write_uint64(h_preimage, txi.amount) # 10d / 13d. nSequence write_uint32(h_preimage, txi.sequence) return get_tx_hash(h_preimage)
def dumps_float(val): return ustruct.pack("!Bd", _CBOR_FLOAT64, val)
def __init__(self, scl, sda, addr): self.Bus = I2C(scl=Pin(scl), sda=Pin(sda), freq=400000) self.Addr = addr self.SendCommand(pack("26B", 0xAE,0xD5,0x80,0xA8,0x3F,0xD3,0x00,0x40,0x8D,0x14,0x20,0x01,0xA1,0xC8,0xDA,0x12,0x81,0xCF,0xD9,0xF1,0xDB,0x40,0x2E,0xA4,0xA6,0xAF))
# I2C with the Arduino as the master device and the OpenMV Cam as the slave. # # Please wire up your OpenMV Cam to your Arduino like this: # # OpenMV Cam Master I2C Data (P5) - Arduino Uno Data (A4) # OpenMV Cam Master I2C Clock (P4) - Arduino Uno Clock (A5) # OpenMV Cam Ground - Arduino Ground import pyb, ustruct text = "Hello World!\n" data = ustruct.pack("<%ds" % len(text), text) # Use "ustruct" to build data packets to send. # "<" puts the data in the struct in little endian order. # "%ds" puts a string in the data stream. E.g. "13s" for "Hello World!\n" (13 chars). # See https://docs.python.org/3/library/struct.html # READ ME!!! # # Please understand that when your OpenMV Cam is not the I2C master it may miss responding to # sending data as a I2C slave no matter if you call "i2c.send()" in an interupt callback or in the # main loop below. When this happens the Arduino will get a NAK and have to try reading from the # OpenMV Cam again. Note that both the Arduino and OpenMV Cam I2C drivers are not good at getting # unstuck after encountering any I2C errors. On the OpenMV Cam and Arduino you can recover by # de-initing and then re-initing the I2C peripherals. # The hardware I2C bus for your OpenMV Cam is always I2C bus 2. bus = pyb.I2C(2, pyb.I2C.SLAVE, addr=0x12) bus.deinit() # Fully reset I2C device... bus = pyb.I2C(2, pyb.I2C.SLAVE, addr=0x12) print("Waiting for Arduino...")
def xfp2str(xfp): # Standardized way to show an xpub's fingerprint... it's a 4-byte string # and not really an integer. Used to show as '0x%08x' but that's wrong endian. return b2a_hex(ustruct.pack('<I', xfp)).decode().upper()
def _decode_single(single): return ustruct.unpack("!f", ustruct.pack("!I", single))[0]
def _encode_pos(self, x, y): """Encode a postion into bytes.""" return struct.pack(_ENCODE_POS, x, y)
def set_memory_pointer(self, x, y): self._command(SET_RAM_X_ADDRESS_COUNTER) # x point must be the multiple of 8 or the last 3 bits will be ignored self._data(bytearray([(x >> 3) & 0xFF])) self._command(SET_RAM_Y_ADDRESS_COUNTER, ustruct.pack("<H", y)) self.wait_until_idle()
Important: This script should be copied to the OpenMV Cam as `main.py`. Source: https://github.com/openmv/openmv/blob/master/scripts/examples/02-Board-Control/usb_vcp.py """ import sensor import ustruct import pyb usb_vcp = pyb.USB_VCP() # Disable USB interrupt (CTRL-C by default) when sending raw data (i.e. images) # See: https://docs.openmv.io/library/pyb.USB_VCP.html#pyb.USB_VCP.setinterrupt usb_vcp.setinterrupt(-1) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.VGA) sensor.skip_frames(time=2000) # wait for settings to take effect! while True: command = usb_vcp.recv(4, timeout=5000) if command == b'snap': image = sensor.snapshot().compress() usb_vcp.send(ustruct.pack('<L', image.size())) usb_vcp.send(image)
def _write_register(self, reg, f): global i2c n = self.round_total_digits(f) fd = bytearray(ustruct.pack("f", n)) i2c.writeto_mem(self.address, reg, fd) time.sleep(10 / 1000.0)
def pack_temp(temp): """Temperature in 0.005 degrees as signed short""" temp_conv = round(round(temp, 2) / 0.005) return pack("!h", temp_conv)
import machine import time import ustruct pin = machine.Pin(25, machine.Pin.OUT) uart = machine.UART(1, 31250) notes = [60, 61, 62, 63, 64, 63, 62, 61] while True: for x in notes: pin.value(1) uart.write(ustruct.pack("bbb", 0x90, x, 0x40)) time.sleep(0.5) pin.value(0) time.sleep(0.5) uart.write(ustruct.pack("bbb", 0x90, x, 0x00))
def pack_humid(hum): """Humidity in 0.0025 percent as unsigned short""" hum_conv = round(round(hum, 2) / 0.0025) return pack("!H", hum_conv)
def switch_channel(self, channel): self.bus.writeto(self.address, ustruct.pack('B', 1 << channel))
_CBOR_TAG_DECIMAL = const(4) # [ 10^x exponent, number ] _CBOR_TAG_BIGFLOAT = const(5) # [ 2^x exponent, number ] _CBOR_TAG_BASE64URL = const(21) _CBOR_TAG_BASE64 = const(22) _CBOR_TAG_BASE16 = const(23) _CBOR_TAG_CBOR = const(24) # following byte string is embedded CBOR data _CBOR_TAG_URI = const(32) _CBOR_TAG_BASE64URL_STR = const(33) _CBOR_TAG_BASE64_STR = const(34) _CBOR_TAG_REGEX = const(35) _CBOR_TAG_MIME = const( 36) # following text is MIME message, headers, separators and all _CBOR_TAG_CBOR_FILEHEADER = const(55799) # can open a file with 0xd9d9f7 _CBOR_TAG_BIGNUM_BYTES = ustruct.pack('B', _CBOR_TAG | _CBOR_TAG_BIGNUM) _CBOR_TAG_NEGBIGNUM_BYTES = ustruct.pack('B', _CBOR_TAG | _CBOR_TAG_NEGBIGNUM) _MAX_DEPTH = const(100) def dumps_int(val): "return bytes representing int val in CBOR" cbor_type = _CBOR_UINT cbor_tag = _CBOR_TAG_BIGNUM_BYTES if val < 0: val = -1 - val cbor_type = _CBOR_NEGINT cbor_tag = _CBOR_TAG_NEGBIGNUM_BYTES if val <= 0x0ffffffffffffffff: #NOT BIGINT
def SendCommand(self, Cmd): Msg = pack("BB", self.Addr<<1, 0x00) + Cmd self.Bus.start() self.Bus.write(Msg) self.Bus.stop()
def encodeFixed(n, fmt='<f'): return struct.pack(fmt, n)
def swap16(i): return ustruct.unpack("<H", ustruct.pack(">H", i))[0]
def long_to_bytes(_int): # signed int return pack(">q", _int)
# test ustruct with a count specified before the type try: import ustruct as struct except: try: import struct except ImportError: import sys print("SKIP") sys.exit() print(struct.calcsize('0s')) print(struct.unpack('0s', b'')) print(struct.pack('0s', b'123')) print(struct.calcsize('2s')) print(struct.unpack('2s', b'12')) print(struct.pack('2s', b'123')) print(struct.calcsize('2H')) print(struct.unpack('<2H', b'1234')) print(struct.pack('<2H', 258, 515)) print(struct.calcsize('0s1s0H2H')) print(struct.unpack('<0s1s0H2H', b'01234')) print(struct.pack('<0s1s0H2H', b'abc', b'abc', 258, 515)) # check that unknown types raise an exception try: struct.unpack('z', b'1')
def short_to_bytes(_short): return pack('>b', _short)
def to_bytes(self): return pack('>4HL', self.x, self.y, self.w, self.h, self.encoding )
def signedchar_to_bytes(_signedchar): return pack('>b', _signedchar)
def _send_str(self, s): self.sock.write(struct.pack("!H", len(s))) self.sock.write(s)
def dumps_bool(b): return ustruct.pack('B', _CBOR_TRUE) if b else ustruct.pack( 'B', _CBOR_FALSE)
def _encode_pixel(self, color): """Encode a pixel color into bytes.""" return struct.pack(_ENCODE_PIXEL, color)
def int_to_bytes(_int): # signed int return pack(">i", _int)
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)