def test_fillwords(self): b = bytearray(range(8*4)) ref = b[:] self.assertEqual(b, ref) a = uctypes.addressof(b) self.assertEqual(a&3, 0) # word-aligned # A zero-length fill does nothing _fillwords(a+2*4, 0x12345678, 0) self.assertEqual(b, ref) # A negative-length fill does nothing _fillwords(a+2*4, 0x12345678, -1) self.assertEqual(b, ref) # Fills single word correctly ref = b[:] _fillwords(a+2*4, 0x79616b6f, 1) ref[4*2:4*(2+1)] = b'okay' self.assertEqual(b, ref) # Fills multiple words correctly b = bytearray(range(8*4)) a = uctypes.addressof(b) ref = b[:] _fillwords(a+2*4, 0x79616b6f, 3) ref[4*2:4*(2+3)] = b'okay' * 3 self.assertEqual(b, ref)
def execvp(f, args): import uctypes args_ = array.array("P", [0] * (len(args) + 1)) i = 0 for a in args: args_[i] = uctypes.addressof(a) i += 1 r = execvp_(f, uctypes.addressof(args_)) check_error(r)
def get_ch(self, ch): from uctypes import addressof relch = ch - self.firstchar if relch > self.nchars or relch < 0: raise ValueError('Character value {:} is unsupported.'.format(ch)) offset = self.get_idx(relch) delta = self.get_idx(relch + 1) - offset if self.monospaced: return addressof(self._font) + offse, self.bits_vert, delta, self.bits_horiz else: return addressof(self._font) + offset, self.bits_vert, delta, delta // self.bytes_vert
def frame_data_repeat(self, stage, use_old): self.asm_data[0] = addressof(self.image) self.asm_data[1] = addressof(self.image_old) if use_old else 0 start = pyb.millis() count = 0 while True: self.frame_data(stage) count +=1 if pyb.elapsed_millis(start) > self.factored_stage_time: break if self.verbose: print('frame_data_repeat count = {}'.format(count))
def test_movewords(self): b = bytearray(range(8*4)) ref = b[:] self.assertEqual(b, ref) a = uctypes.addressof(b) self.assertEqual(a&3, 0) # word-aligned # A zero-length move does nothing _movewords(a, a+3*4, 0) self.assertEqual(b, ref) # A negative-length move does nothing _movewords(a, a+3*4, -2) self.assertEqual(b, ref) # A move with dest=src does nothing _movewords(a+3*4, a+3*4, 0) self.assertEqual(b, ref) # A simple move down b = bytearray(range(8*4)) a = uctypes.addressof(b) ref = b[:] ref[0*4:2*4] = b[3*4:5*4] _movewords(a, a+3*4, 2) self.assertEqual(list(b), list(ref)) # A simple move up b = bytearray(range(8*4)) a = uctypes.addressof(b) ref = b[:] ref[3*4:5*4] = b[0*4:2*4] _movewords(a+3*4, a, 2) self.assertEqual(list(b), list(ref)) # An overlapping move down b = bytearray(range(8*4)) a = uctypes.addressof(b) ref = b[:] ref[0*4:6*4] = b[2*4:8*4] _movewords(a, a+2*4, 6) self.assertEqual(list(b), list(ref)) # An overlapping move up b = bytearray(range(8*4)) a = uctypes.addressof(b) ref = b[:] ref[2*4:8*4] = b[0*4:6*4] _movewords(a+2*4, a, 6) self.assertEqual(list(b), list(ref))
def printChar(self, c, bg_buf=None): # get the charactes pixel bitmap and dimensions if self.text_font: fmv, rows, cols = self.text_font.get_ch(c) else: raise AttributeError('No font selected') cbytes, cbits = divmod(cols, 8) # Not in packed format dcols = (cbytes + 1) * 8 if cbits else cbytes * 8 # cols for display pix_count = dcols * rows # number of bits in the char # test char fit if self.text_x + cols > self.text_width: # does the char fit on the screen? if self.text_scroll: self.printCR() # No, then CR self.printNewline(True) # NL: advance to the next line else: return 0 # Retrieve Background data if transparency is required if self.transparency: # in case of transpareny, the frame buffer content is needed if bg_buf is None: # buffer allocation needed? if len(self.bg_buf) < pix_count * 3: del(self.bg_buf) gc.collect() self.bg_buf = bytearray(pix_count * 3) # Make it bigger bg_buf = self.bg_buf self.setXY(self.text_x, self.text_y, self.text_x + dcols - 1, self.text_y + rows - 1) # set area TFT_io.tft_read_cmd_data_AS(0x2e, bg_buf, pix_count * 3) # read background data else: bg_buf = 0 # dummy assignment, since None is not accepted # Set XY range & print char self.setXY(self.text_x, self.text_y, self.text_x + dcols - 1, self.text_y + rows - 1) # set area TFT_io.displaySCR_charbitmap(addressof(fmv), pix_count, self.text_color, bg_buf) # display char! #advance pointer self.text_x += (cols + self.text_gap) return cols + self.text_gap
def sync(self, to=None): if to is None: self.spi.send(self.buf) else: short_buf = bytearray_at(addressof(self.buf), 3*4*to + 1) # extra byte t = short_buf[-1] short_buf[-1] = 0 self.spi.send(short_buf) short_buf[-1] = t
def __init__(self, length, popfunc=None, winfunc=None): bits = round(math.log(length)/math.log(2)) assert 2**bits == length, "Length must be an integer power of two" self.dboffset = 0 # Offset for dB calculation self._length = length self.popfunc = popfunc # Function to acquire data self.re = array.array('f', (0 for x in range(self._length))) self.im = array.array('f', (0 for x in range(self._length))) if winfunc is not None: # If a window function is provided, create and populate the array self.windata = array.array('f', (0 for x in range(self._length))) # of window coefficients for x in range(0, length): self.windata[x] = winfunc(x, length) else: self.windata = None COMPLEX_NOS = 7 # Size of complex buffer area before roots of unity ROOTSOFFSET = COMPLEX_NOS*2 # Word offset into complex array of roots of unity bits = round(math.log(self._length)/math.log(2)) self.ctrl = array.array('i', [0]*6) self.cmplx = array.array('f', [0.0]*((bits +1 +COMPLEX_NOS)*2)) self.ctrl[0] = self._length self.ctrl[1] = bits self.ctrl[2] = addressof(self.re) self.ctrl[3] = addressof(self.im) self.ctrl[4] = COMPLEX_NOS*8 # Byte offset into complex array of roots of unity self.ctrl[5] = addressof(self.cmplx) # Base address self.cmplx[0] = 1.0 # Initial value of u = [1 +j0] self.cmplx[1] = 0.0 # Intermediate values are used by fft() and not initialised self.cmplx[12] = 1.0/self._length # Default scaling multiply by 1/length self.cmplx[13] = 0.0 # ignored i = ROOTSOFFSET creal = -1 cimag = 0 self.cmplx[i] = creal # Complex roots of unity self.cmplx[i +1] = cimag i += 2 for x in range(bits): cimag = math.sqrt((1.0 - creal) / 2.0) # Imaginary part self.cmplx[i +1] = cimag creal = math.sqrt((1.0 + creal) / 2.0) # Real part self.cmplx[i] = creal i += 2
def get_ch(self, ch): from uctypes import addressof relch = ch - self.firstchar if relch > self.nchars or relch < 0: relch = 0 # instead of value error, typically this is space # raise ValueError('Character value {:} is unsupported.'.format(ch)) offset = relch * 2 # index is 2 bytes/char offset = self._index[offset] + (self._index[offset + 1] << 8) delta = (relch + 1) * 2 # index is 2 bytes/char delta = (self._index[delta] + (self._index[delta + 1] << 8)) - offset return addressof(self._font) + offset, self.bits_vert, (delta * 8) // self.bits_vert
def one_line_data(self, line, stage): mv_linebuf = memoryview(self.line_buffer) self.asm_data[2] = addressof(mv_linebuf) self.asm_data[3] = stage spi_send_byte = self.spi.send # send data self._SPI_send(b'\x70\x0a') self.Pin_EPD_CS.low() # CS low until end of line spi_send_byte(b'\x72\x00') # data bytes odd_pixels(self.asm_data, 0, line * BYTES_PER_LINE) offset = BYTES_PER_LINE offset = scan(self.line_buffer, line, offset) even_pixels(self.asm_data, offset, line * BYTES_PER_LINE) offset += BYTES_PER_LINE spi_send_byte(mv_linebuf[:offset]) # send the accumulated line buffer self.Pin_EPD_CS.high() self._SPI_send(b'\x70\x02\x72\x07') # output data to panel
def next(self): if self.subf: self.subf.skip() buf = self.f.read(512) if not buf: return None h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) # Empty block means end of archive if h.name[0] == 0: return None d = TarInfo() d.name = str(h.name, "utf-8").rstrip() d.size = int(bytes(h.size).rstrip(), 8) d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) return d
def _addressable(self, v): # This dance is so we create less garbage on the heap if isinstance(v, bytearray): pass elif isinstance(v, bytes): v = addressof(v) else: #vb = bytearray(iter(vb)) vb = self.set_led_buf # Reuse to minimise heap impact #print("vb starts as", vb, end=' ') try: for i in range(3): vb[i] = v[i] #print("vb is", vb, end=' ') except: it = iter(v) vb[0] = next(it) vb[1] = next(it) vb[2] = next(it) v = vb return v
return True if __name__ == "__main__": import urandom, time tSize = 96 src = bytearray(tSize) dst = bytearray(tSize) for i in range(tSize): src[i] = urandom.randint(1, 7) #src[i]= i % 255 # initialize DMA channel 11 , use timer 3 and set clock to 125MHz/15625 = 8000Hz dma = myDMA(11, timer=3, clock_MUL=1, clock_DIV=15625) start = time.ticks_us() # copy from src to dest dma.move(uctypes.addressof(src), uctypes.addressof(dst), tSize, start=True) end = time.ticks_us() print("src= ", src) print("\ndst= ", dst) # test that it worked for i in range(0, tSize): if src[i] != dst[i]: print('Copy error at', i) length_us = end - start if length_us > 0: print("\ntook {} us rate = {} bytes /sec\n".format( length_us, 1_000_000.0 * tSize / length_us))
import uctypes desc = { # arr is array at offset 0, of UINT8 elements, array size is 2 "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), } data = bytearray(b"01234567") S = uctypes.struct(desc, uctypes.addressof(data), uctypes.LITTLE_ENDIAN) print(uctypes.sizeof(S.arr)) assert uctypes.sizeof(S.arr) == 2 print(uctypes.sizeof(S.arr2)) assert uctypes.sizeof(S.arr2) == 2 print(uctypes.sizeof(S.arr3)) try: print(uctypes.sizeof(S.arr3[0])) except TypeError: print("TypeError")
# This program for an nRF52840 sends a one byte payload in a # packet once every second. #from micropython import const from micropython import const import machine # so can peek and poke different registers on the nRF5x import uctypes import utime radioBuffer = bytearray(100) # allocate IO buffer for use by nRF5x radio radioBuffer_address = uctypes.addressof(radioBuffer) my_prefixAddress = const(0xAA) my_baseAddress = const(0xDEADBEEF) NRF_POWER = const(0x40000000) DCDCEN = const(0x578) NRF_POWER___DCDCEN = const(NRF_POWER + DCDCEN) NRF_CLOCK = const(0x40000000) TASKS_HFCLKSTART = const(0) EVENTS_HFCLKSTARTED = const(0x100) NRF_CLOCK___TASKS_HFCLKSTART = const(NRF_CLOCK + TASKS_HFCLKSTART) NRF_CLOCK___EVENTS_HFCLKSTARTED = const(NRF_CLOCK + EVENTS_HFCLKSTARTED) NRF_RADIO = const(0x40001000) BASE0 = const(0x51C) PREFIX0 = const(0x524) FREQUENCY = const(0x508) PCNF1 = const(0x518) PCNF0 = const(0x514)
import uctypes ACCEL_CONFIG = { 'x_self_test' : uctypes.BFUINT8 | 0 | 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'y_self_test' : uctypes.BFUINT8 | 0 | 6 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'z_self_test' : uctypes.BFUINT8 | 0 | 5 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'range' : uctypes.BFUINT8 | 0 | 3 << uctypes.BF_POS | 2 << uctypes.BF_LEN, } buf = bytearray(1) buf[0] = 0xa8 print('buf[0] =', hex(buf[0])) accel_config = uctypes.struct(ACCEL_CONFIG, uctypes.addressof(buf)) print('x_self_test =', accel_config.x_self_test) print('y_self_test =', accel_config.y_self_test) print('z_self_test =', accel_config.z_self_test) print('range =', accel_config.range) accel_config.y_self_test = 1 print('buf[0] =', hex(buf[0]))
def _clearLEDs(buf, i, qty): # Clear qty LEDs in buffer starting at i a = addressof(buf) _fillwords(a + 4*3*i, 0x11111111, 3*qty)
def memcopy(ch, dest, src, size, enable=1): ch.CTRL_TRIG.EN = 0 ch.WRITE_ADDR = addressof(dest) ch.READ_ADDR = addressof(src) ch.TRANS_COUNT = size // (1 << ch.CTRL_TRIG.DATA_SIZE) ch.CTRL_TRIG.EN = enable
"arr7": (uctypes.ARRAY | 0, 1, { "l": uctypes.UINT32 | 0 }), "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, { "l": {} }), } data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc) # assign byte S.arr[0] = 0x11 print(hex(S.arr[0])) assert hex(S.arr[0]) == "0x11" # assign word S.arr3[0] = 0x2233 print(hex(S.arr3[0])) assert hex(S.arr3[0]) == "0x2233" # assign word, with index S.arr3[1] = 0x4455 print(hex(S.arr3[1])) assert hex(S.arr3[1]) == "0x4455"
def sony_nibblize35(dataIn_ba, roffset: int, dataOut_ba, woffset: int): dataIn = ptr8(addressof(dataIn_ba)) nib_ptr = ptr8(addressof(dataOut_ba)) s2d = ptr8(addressof(sony_to_disk_byte)) b1 = ptr8(addressof(nib1)) b2 = ptr8(addressof(nib2)) b3 = ptr8(addressof(nib3)) # Copy from the user's buffer to our buffer, while computing # the three-byte data checksum i = -12 # prepend 12 bytes of 0 j = 0 c1 = 0 c2 = 0 c3 = 0 while (True): # ROL.B c1 = (c1 & 0xFF) << 1 if (c1 & 0x0100) != 0: c1 += 1 val = 0 if i >= 0: val = dataIn[i + roffset] c3 += val i += 1 # ADDX? if (c1 & 0x0100) != 0: c3 += 1 c1 &= 0xFF b1[j] = val ^ c1 val = 0 if i >= 0: val = dataIn[i + roffset] c2 += val i += 1 if c3 > 0xFF: c2 += 1 c3 &= 0xFF b2[j] = val ^ c3 if i >= 512: break val = 0 if i >= 0: val = dataIn[i + roffset] c1 += val i += 1 if c2 > 0xFF: c1 += 1 c2 &= 0xFF b3[j] = val ^ c2 j += 1 c4 = ((c1 & 0xC0) >> 6) | ((c2 & 0xC0) >> 4) | ((c3 & 0xC0) >> 2) b3[174] = 0 j = woffset # offset writing to dataOut for i in range(0, 175): w1 = b1[i] & 0x3F w2 = b2[i] & 0x3F w3 = b3[i] & 0x3F w4 = (b1[i] & 0xC0) >> 2 w4 |= (b2[i] & 0xC0) >> 4 w4 |= (b3[i] & 0xC0) >> 6 nib_ptr[j] = s2d[w4] j += 1 nib_ptr[j] = s2d[w1] j += 1 nib_ptr[j] = s2d[w2] j += 1 if i != 174: nib_ptr[j] = s2d[w3] j += 1 # checksum at j=offset+699 nib_ptr[j] = s2d[c4 & 0x3F] j += 1 nib_ptr[j] = s2d[c3 & 0x3F] j += 1 nib_ptr[j] = s2d[c2 & 0x3F] j += 1 nib_ptr[j] = s2d[c1 & 0x3F]
j = int(i/32) k = i % 32 #print(j) #a[j] = a[j] & ~(1<<31-k) #a[j] = a[j] & ~(1<<31-k) a[j] = a[j] | 1<<31-k return a offset_n = 0 offset_z = 0 data = fill_array(offset_n, offset_z, False, True, True, True) data2 = fill_array(-1, -2, True, True, False, True) print(addressof(data)) print(addressof(data2)) print(bin(data[0])) print(bin(data2[0])) #for i in range(36*2): # if i!=35 and i!=36 and i!=71 and i!=72: # i = i*4+1 # #j, k = int(i/32), i % 32 # j = int(i/32) # k = i % 32 # #data[j] = data[j] | 1<<31-k
def sdr_response(buf): send_tms(0) # -> capture DR send_tms(0) # -> shift DR send_read_buf_lsb1st(buf, 1, addressof(buf)) send_tms0111() # -> select DR scan
def decrypt(self, ciphertext: bytearray) -> bytearray: # Decrypts ciphertext in-place. Returns a zero-copy bytearray up to where # the padding begins. self._decryptor.decrypt(ciphertext, ciphertext) n = PKCS7.verify(ciphertext, self.block_size) return uctypes.bytearray_at(uctypes.addressof(ciphertext), n)
def fifo16(i:int)->int: p16buf=ptr16(addressof(fifobuf16)) if p16buf[i]<0x8000: return p16buf[i] else: return p16buf[i]-0x10000
import sys import uctypes if sys.byteorder != "little": print("SKIP") sys.exit() desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
def get_icon(icon_index = 0, color_index = 0): return width, height, addressof(_icons[icon_index]), colors, addressof(colortable[color_index])
def make_struct(desc): desc_size = uctypes.sizeof(desc, uctypes.BIG_ENDIAN) buf = bytearray(desc_size) return buf, uctypes.struct(uctypes.addressof(buf), desc, uctypes.BIG_ENDIAN)
def draw(x, y, icon_index, draw_fct, color_index = 0): draw_fct(x - width//2, y - height // 2, width, height, addressof(_icons[icon_index]), colors, addressof(colortable[color_index]))
def a(i:int)->int: p32a=ptr32(addressof(acceli)) return p32a[i]>>4
#led = Pin(25, Pin.OUT) #led.off() chip = MCP3008(spi, cs) state = True offset_n = 0 offset_z = 0 t0 = ticks_ms() data = fill_array(offset_n, offset_z, True, True, True, True) ar_p = array("I", [0]) ar_p[0] = addressof(data) t1 = ticks_ms() print(ticks_diff(t1, t0)) @rp2.asm_pio( # zuendung, nockewelle, kurbelwelle, debug gggdfdf out_init=(rp2.PIO.OUT_HIGH, rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW), #out_init=(rp2.PIO.OUT_HIGH, rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW), #out_init=(rp2.PIO.OUT_LOW), out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=32, )
def write_block_data(self, command, values): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) values = values[:32] data.block = [len(values)] + values self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_BLOCK_DATA, data)
try: import uctypes except ImportError: print("SKIP") raise SystemExit desc = { "f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0, "uf64": uctypes.FLOAT64 | 2, # unaligned } data = bytearray(10) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) S.f32 = 12.34 print("%.4f" % S.f32) S.f64 = 12.34 print("%.4f" % S.f64) S.uf64 = 12.34 print("%.4f" % S.uf64)
def __repr__(self): return "<Pixel %d (%d, %d, %d) of chain 0x%x>" % \ (self.i//3, self.r, self.g, self.b, addressof(self.a))
raise SystemExit if sys.byteorder != "little": print("SKIP") raise SystemExit desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.NATIVE) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
# test machine module try: import machine except ImportError: print("SKIP") import sys sys.exit() import uctypes print(machine.mem8) buf = bytearray(8) addr = uctypes.addressof(buf) machine.mem8[addr] = 123 print(machine.mem8[addr]) machine.mem16[addr] = 12345 print(machine.mem16[addr]) machine.mem32[addr] = 123456789 print(machine.mem32[addr]) try: machine.mem16[1] except ValueError: print("ValueError") try:
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64): import utime import uselect import uctypes import usocket import ustruct import urandom # prepare packet assert size >= 16, "pkt size too small" pkt = b'Q' * size pkt_desc = { "type": uctypes.UINT8 | 0, "code": uctypes.UINT8 | 1, "checksum": uctypes.UINT16 | 2, "id": uctypes.UINT16 | 4, "seq": uctypes.INT16 | 6, "timestamp": uctypes.UINT64 | 8, } # packet header descriptor h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN) h.type = 8 # ICMP_ECHO_REQUEST h.code = 0 h.checksum = 0 h.id = 100 h.seq = 1 # init socket sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1) sock.setblocking(0) sock.settimeout(timeout / 1000) addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address sock.connect((addr, 1)) not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt))) seqs = list(range(1, count + 1)) # [1,2,...,count] c = 1 t = 0 n_trans = 0 n_recv = 0 finish = False while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq if h2.type == 0 and h2.id == h.id and ( seq in seqs): # 0: ICMP_ECHO_REPLY t_elasped = (utime.ticks_us() - h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print( "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" % (len(resp), addr, seq, ttl, t_elasped)) seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break utime.sleep_ms(1) t += 1 # close sock.close() ret = (n_trans, n_recv) not quiet and print("%u packets transmitted, %u packets received" % (n_trans, n_recv)) return (n_trans, n_recv)
import uctypes desc = { "f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0, } data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) S.f32 = 12.34 print('%.4f' % S.f32) S.f64 = 12.34 print('%.4f' % S.f64)
# test general errors with uctypes try: import uctypes except ImportError: print("SKIP") raise SystemExit data = bytearray(b"01234567") # del subscr not supported S = uctypes.struct(uctypes.addressof(data), {}) try: del S[0] except TypeError: print('TypeError') # list is an invalid descriptor S = uctypes.struct(uctypes.addressof(data), []) try: S.x except TypeError: print('TypeError') # can't access attribute with invalid descriptor S = uctypes.struct(uctypes.addressof(data), {'x':[]}) try: S.x except TypeError: print('TypeError')
# test general errors with uctypes try: import uctypes except ImportError: print("SKIP") raise SystemExit data = bytearray(b"01234567") # del subscr not supported S = uctypes.struct(uctypes.addressof(data), {}) try: del S[0] except TypeError: print("TypeError") # list is an invalid descriptor S = uctypes.struct(uctypes.addressof(data), []) try: S.x except TypeError: print("TypeError") # can't access attribute with invalid descriptor S = uctypes.struct(uctypes.addressof(data), {"x": []}) try: S.x except TypeError: print("TypeError")
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) #print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" #print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) try: S[0] assert False, "Can't index struct" except TypeError: print("TypeError") print("arr:", S.arr[0], S.arr[1])
# This test checks previously known problem values for 32-bit ports. # It's less useful for 64-bit ports. try: import uctypes except ImportError: import sys print("SKIP") sys.exit() buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, uctypes.LITTLE_ENDIAN ) struct.f32 = 0x7fffffff print(buf) struct.f32 = 0x80000000 print(buf) struct.f32 = 0xff010203 print(buf) struct.f64 = 0x80000000 print(buf) struct.f64 = 0x80000000 * 2 print(buf)
def overlay_struct(buf, desc): desc_size = uctypes.sizeof(desc, uctypes.BIG_ENDIAN) if desc_size > len(buf): raise ValueError('desc is too big (%d > %d)' % (desc_size, len(buf))) return uctypes.struct(uctypes.addressof(buf), desc, uctypes.BIG_ENDIAN)
except ValueError: print("SKIP") raise SystemExit class A(): pass # pack and unpack objects o = A() s = struct.pack("<O", o) o2 = struct.unpack("<O", s) print(o is o2[0]) # pack can accept less arguments than required for the format spec print(struct.pack('<2I', 1)) # pack and unpack pointer to a string # This requires uctypes to get the address of the string and instead of # putting this in a dedicated test that can be skipped we simply pass # if the import fails. try: import uctypes o = uctypes.addressof('abc') s = struct.pack("<S", o) o2 = struct.unpack("<S", s) assert o2[0] == 'abc' except ImportError: pass
def new(sdesc): buf = bytearray(uctypes.sizeof(sdesc)) s = uctypes.struct(uctypes.addressof(buf), sdesc, uctypes.NATIVE) return s
import uctypes desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, { "b": uctypes.UINT8 | 0 }), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(4) S = uctypes.struct(desc, uctypes.addressof(buf), uctypes.LITTLE_ENDIAN) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
def __enter__(self): self._acquire(uctypes.addressof(self.lock)) return self
import uctypes if sys.byteorder != "little": print("SKIP") sys.exit() desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc)) S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.NATIVE) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print (S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
def read_block_data(self, command, values): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) self._access(_I2C_SMBUS_READ, command, _I2C_SMBUS_BLOCK_DATA, data) return data.block
def read_byte(self): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) self._access(_I2C_SMBUS_READ, 0, _I2C_SMBUS_BYTE, data) return data.byte
def __init__(self, dev_port, show=Bus.SHOW_NONE): desc = { "model": uctypes.UINT16 | 0, "version": uctypes.UINT8 | 2, "dev_id": uctypes.UINT8 | 3, "baud_rate": uctypes.UINT8 | 4, "rdt": uctypes.UINT8 | 5, "num_adcs": uctypes.UINT8 | cfg.NUM_ADCS_OFFSET, "num_gpios": uctypes.UINT8 | cfg.NUM_GPIOS_OFFSET, "adc_pin": ( uctypes.ARRAY | cfg.ADC_PIN, cfg.NUM_ADCS, { "port": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "pin": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, }, ), "gpio_pin": ( uctypes.ARRAY | cfg.GPIO_PIN, cfg.NUM_GPIOS, { "port": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "pin": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, }, ), "gpio_cfg": ( uctypes.ARRAY | cfg.GPIO_CFG, cfg.NUM_GPIOS, { "dir": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 1 << uctypes.BF_LEN, "pu": uctypes.BFUINT8 | 0 | 1 << uctypes.BF_POS | 1 << uctypes.BF_LEN, "pd": uctypes.BFUINT8 | 0 | 2 << uctypes.BF_POS | 1 << uctypes.BF_LEN, "od": uctypes.BFUINT8 | 0 | 3 << uctypes.BF_POS | 1 << uctypes.BF_LEN, }, ), # End of persistent values "adc_value": (uctypes.ARRAY | cfg.ADC_VALUE, uctypes.UINT16 | cfg.NUM_ADCS), "gpio_set": uctypes.UINT32 | cfg.GPIO_SET, "gpio_clear": uctypes.UINT32 | cfg.GPIO_CLEAR, "gpio_odr": uctypes.UINT32 | cfg.GPIO_ODR, "gpio_idr": uctypes.UINT32 | cfg.GPIO_IDR, } initial_bytes = bytearray(cfg.NUM_CTL_BYTES) init = uctypes.struct(uctypes.addressof(initial_bytes), desc, uctypes.LITTLE_ENDIAN) init.model = 123 init.version = 1 init.dev_id = Device.INITIAL_DEV_ID init.baud_rate = Device.INITIAL_BAUD init.rdt = Device.INITIAL_RDT for idx in range(cfg.NUM_GPIOS): init.gpio_cfg[idx].dir = 1 ctl_bytes = bytearray(cfg.NUM_CTL_BYTES) self.ctl = uctypes.struct(uctypes.addressof(ctl_bytes), desc, uctypes.LITTLE_ENDIAN) notifications = ( (cfg.ADC_PIN, cfg.NUM_ADCS, self.adc_pin_updated), (cfg.GPIO_PIN, cfg.NUM_GPIOS, self.gpio_pin_updated), (cfg.GPIO_CFG, cfg.NUM_GPIOS, self.gpio_cfg_updated), (cfg.GPIO_SET, 4, self.gpio_set_updated), (cfg.GPIO_CLEAR, 4, self.gpio_clear_updated), (cfg.GPIO_ODR, 4, self.gpio_odr_updated), ) self.adc = [None] * cfg.NUM_ADCS self.gpio = [None] * cfg.NUM_GPIOS super().__init__(dev_port, cfg.PERSISTENT_BYTES, initial_bytes, ctl_bytes, notifications, show)
# aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc) # assign byte S.arr[0] = 0x11 print(hex(S.arr[0])) assert hex(S.arr[0]) == "0x11" # assign word S.arr3[0] = 0x2233 print(hex(S.arr3[0])) assert hex(S.arr3[0]) == "0x2233" # assign word, with index S.arr3[1] = 0x4455 print(hex(S.arr3[1])) assert hex(S.arr3[1]) == "0x4455"
def read_word_data(self, command): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) self._access(_I2C_SMBUS_READ, command, _I2C_SMBUS_WORD_DATA, data) return data.word
def write_word_data(self, command, value): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) data.word = value self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_WORD_DATA, data)
def test(self): # Nonblocking: try to acquire, return True if success. return self._attempt(uctypes.addressof(self.lock)) == 0
def process_call(self, command, value): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) data.word = value self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_PROC_CALL, data) return data.word