all: Reformat C and Python source code with tools/codeformat.py.

This is run with uncrustify 0.70.1, and black 19.10b0.
pull/5700/head
Damien George 2020-02-27 15:36:53 +11:00
rodzic 3f39d18c2b
commit 69661f3343
539 zmienionych plików z 10496 dodań i 8254 usunięć

Wyświetl plik

@ -6,6 +6,7 @@ try:
except:
from pyb import dht_readinto
class DHTBase:
def __init__(self, pin):
self.pin = pin
@ -14,9 +15,10 @@ class DHTBase:
def measure(self):
buf = self.buf
dht_readinto(self.pin, buf)
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]:
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xFF != buf[4]:
raise Exception("checksum error")
class DHT11(DHTBase):
def humidity(self):
return self.buf[0]
@ -24,12 +26,13 @@ class DHT11(DHTBase):
def temperature(self):
return self.buf[2]
class DHT22(DHTBase):
def humidity(self):
return (self.buf[0] << 8 | self.buf[1]) * 0.1
def temperature(self):
t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1
t = ((self.buf[2] & 0x7F) << 8 | self.buf[3]) * 0.1
if self.buf[2] & 0x80:
t = -t
return t

Wyświetl plik

@ -29,16 +29,17 @@ _uart_baud_table = {
460800: 8,
}
class LCD160CR:
def __init__(self, connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98):
if connect in ('X', 'Y', 'XY', 'YX'):
if connect in ("X", "Y", "XY", "YX"):
i = connect[-1]
j = connect[0]
y = j + '4'
elif connect == 'C':
y = j + "4"
elif connect == "C":
i = 2
j = 2
y = 'A7'
y = "A7"
else:
if pwr is None or i2c is None or spi is None:
raise ValueError('must specify valid "connect" or all of "pwr", "i2c" and "spi"')
@ -74,8 +75,8 @@ class LCD160CR:
# set default orientation and window
self.set_orient(PORTRAIT)
self._fcmd2b('<BBBBBB', 0x76, 0, 0, self.w, self.h) # viewport 'v'
self._fcmd2b('<BBBBBB', 0x79, 0, 0, self.w, self.h) # window 'y'
self._fcmd2b("<BBBBBB", 0x76, 0, 0, self.w, self.h) # viewport 'v'
self._fcmd2b("<BBBBBB", 0x79, 0, 0, self.w, self.h) # window 'y'
def _send(self, cmd):
i = self.i2c.writeto(self.i2c_addr, cmd)
@ -135,7 +136,7 @@ class LCD160CR:
@staticmethod
def rgb(r, g, b):
return ((b & 0xf8) << 8) | ((g & 0xfc) << 3) | (r >> 3)
return ((b & 0xF8) << 8) | ((g & 0xFC) << 3) | (r >> 3)
@staticmethod
def clip_line(c, w, h):
@ -207,43 +208,43 @@ class LCD160CR:
sleep_ms(15)
def set_orient(self, orient):
self._fcmd2('<BBB', 0x14, (orient & 3) + 4)
self._fcmd2("<BBB", 0x14, (orient & 3) + 4)
# update width and height variables
self.iflush()
self._send(b'\x02g0')
self._send(b"\x02g0")
self._waitfor(4, self.buf[5])
self.w = self.buf[5][1]
self.h = self.buf[5][2]
def set_brightness(self, value):
self._fcmd2('<BBB', 0x16, value)
self._fcmd2("<BBB", 0x16, value)
def set_i2c_addr(self, addr):
# 0x0e set i2c addr
if addr & 3:
raise ValueError('must specify mod 4 aligned address')
self._fcmd2('<BBW', 0x0e, 0x433249 | (addr << 24))
raise ValueError("must specify mod 4 aligned address")
self._fcmd2("<BBW", 0x0E, 0x433249 | (addr << 24))
def set_uart_baudrate(self, baudrate):
try:
baudrate = _uart_baud_table[baudrate]
except KeyError:
raise ValueError('invalid baudrate')
self._fcmd2('<BBB', 0x18, baudrate)
raise ValueError("invalid baudrate")
self._fcmd2("<BBB", 0x18, baudrate)
def set_startup_deco(self, value):
self._fcmd2('<BBB', 0x19, value)
self._fcmd2("<BBB", 0x19, value)
def save_to_flash(self):
self._send(b'\x02fn')
self._send(b"\x02fn")
#### PIXEL ACCESS ####
def set_pixel(self, x, y, c):
self._fcmd2b('<BBBBH', 0x41, x, y, c)
self._fcmd2b("<BBBBH", 0x41, x, y, c)
def get_pixel(self, x, y):
self._fcmd2('<BBBB', 0x61, x, y)
self._fcmd2("<BBBB", 0x61, x, y)
t = 1000
while t:
self.i2c.readfrom_into(self.i2c_addr, self.buf1)
@ -256,7 +257,7 @@ class LCD160CR:
def get_line(self, x, y, buf):
l = len(buf) // 2
self._fcmd2b('<BBBBB', 0x10, l, x, y)
self._fcmd2b("<BBBBB", 0x10, l, x, y)
l *= 2
t = 1000
while t:
@ -280,42 +281,47 @@ class LCD160CR:
# split line if more than 254 bytes needed
buflen = (w + 1) // 2
line = bytearray(2 * buflen + 1)
line2 = memoryview(line)[:2 * (w - buflen) + 1]
line2 = memoryview(line)[: 2 * (w - buflen) + 1]
for i in range(min(len(buf) // (2 * w), h)):
ix = i * w * 2
self.get_line(x, y + i, line)
buf[ix:ix + len(line) - 1] = memoryview(line)[1:]
buf[ix : ix + len(line) - 1] = memoryview(line)[1:]
ix += len(line) - 1
if line2:
self.get_line(x + buflen, y + i, line2)
buf[ix:ix + len(line2) - 1] = memoryview(line2)[1:]
buf[ix : ix + len(line2) - 1] = memoryview(line2)[1:]
ix += len(line2) - 1
def screen_load(self, buf):
l = self.w * self.h * 2+2
self._fcmd2b('<BBHBBB', 0x70, l, 16, self.w, self.h)
l = self.w * self.h * 2 + 2
self._fcmd2b("<BBHBBB", 0x70, l, 16, self.w, self.h)
n = 0
ar = memoryview(buf)
while n < len(buf):
if len(buf) - n >= 0x200:
self._send(ar[n:n + 0x200])
self._send(ar[n : n + 0x200])
n += 0x200
else:
self._send(ar[n:])
while n < self.w * self.h * 2:
self._send(b'\x00')
self._send(b"\x00")
n += 1
#### TEXT COMMANDS ####
def set_pos(self, x, y):
self._fcmd2('<BBBB', 0x58, x, y)
self._fcmd2("<BBBB", 0x58, x, y)
def set_text_color(self, fg, bg):
self._fcmd2('<BBHH', 0x63, fg, bg)
self._fcmd2("<BBHH", 0x63, fg, bg)
def set_font(self, font, scale=0, bold=0, trans=0, scroll=0):
self._fcmd2('<BBBB', 0x46, (scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xf), scale & 0xff)
self._fcmd2(
"<BBBB",
0x46,
(scroll << 7) | (trans << 6) | ((font & 3) << 4) | (bold & 0xF),
scale & 0xFF,
)
def write(self, s):
# TODO: eventually check for room in LCD input queue
@ -324,14 +330,14 @@ class LCD160CR:
#### PRIMITIVE DRAWING COMMANDS ####
def set_pen(self, line, fill):
self._fcmd2('<BBHH', 0x50, line, fill)
self._fcmd2("<BBHH", 0x50, line, fill)
def erase(self):
self._send(b'\x02\x45')
self._send(b"\x02\x45")
def dot(self, x, y):
if 0 <= x < self.w and 0 <= y < self.h:
self._fcmd2('<BBBB', 0x4b, x, y)
self._fcmd2("<BBBB", 0x4B, x, y)
def rect(self, x, y, w, h, cmd=0x72):
if x + w <= 0 or y + h <= 0 or x >= self.w or y >= self.h:
@ -348,19 +354,19 @@ class LCD160CR:
y = 0
if cmd == 0x51 or cmd == 0x72:
# draw interior
self._fcmd2b('<BBBBBB', 0x51, x, y, min(w, 255), min(h, 255))
self._fcmd2b("<BBBBBB", 0x51, x, y, min(w, 255), min(h, 255))
if cmd == 0x57 or cmd == 0x72:
# draw outline
if left:
self._fcmd2b('<BBBBBB', 0x57, x, y, 1, min(h, 255))
self._fcmd2b("<BBBBBB", 0x57, x, y, 1, min(h, 255))
if top:
self._fcmd2b('<BBBBBB', 0x57, x, y, min(w, 255), 1)
self._fcmd2b("<BBBBBB", 0x57, x, y, min(w, 255), 1)
if x + w < self.w:
self._fcmd2b('<BBBBBB', 0x57, x + w, y, 1, min(h, 255))
self._fcmd2b("<BBBBBB", 0x57, x + w, y, 1, min(h, 255))
if y + h < self.h:
self._fcmd2b('<BBBBBB', 0x57, x, y + h, min(w, 255), 1)
self._fcmd2b("<BBBBBB", 0x57, x, y + h, min(w, 255), 1)
else:
self._fcmd2b('<BBBBBB', cmd, x, y, min(w, 255), min(h, 255))
self._fcmd2b("<BBBBBB", cmd, x, y, min(w, 255), min(h, 255))
def rect_outline(self, x, y, w, h):
self.rect(x, y, w, h, 0x57)
@ -375,48 +381,48 @@ class LCD160CR:
ar4[2] = x2
ar4[3] = y2
if self.clip_line(ar4, self.w, self.h):
self._fcmd2b('<BBBBBB', 0x4c, ar4[0], ar4[1], ar4[2], ar4[3])
self._fcmd2b("<BBBBBB", 0x4C, ar4[0], ar4[1], ar4[2], ar4[3])
def dot_no_clip(self, x, y):
self._fcmd2('<BBBB', 0x4b, x, y)
self._fcmd2("<BBBB", 0x4B, x, y)
def rect_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x72, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x72, x, y, w, h)
def rect_outline_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x57, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x57, x, y, w, h)
def rect_interior_no_clip(self, x, y, w, h):
self._fcmd2b('<BBBBBB', 0x51, x, y, w, h)
self._fcmd2b("<BBBBBB", 0x51, x, y, w, h)
def line_no_clip(self, x1, y1, x2, y2):
self._fcmd2b('<BBBBBB', 0x4c, x1, y1, x2, y2)
self._fcmd2b("<BBBBBB", 0x4C, x1, y1, x2, y2)
def poly_dot(self, data):
if len(data) & 1:
raise ValueError('must specify even number of bytes')
self._fcmd2('<BBB', 0x71, len(data) // 2)
raise ValueError("must specify even number of bytes")
self._fcmd2("<BBB", 0x71, len(data) // 2)
self._send(data)
def poly_line(self, data):
if len(data) & 1:
raise ValueError('must specify even number of bytes')
self._fcmd2('<BBB', 0x78, len(data) // 2)
raise ValueError("must specify even number of bytes")
self._fcmd2("<BBB", 0x78, len(data) // 2)
self._send(data)
#### TOUCH COMMANDS ####
def touch_config(self, calib=False, save=False, irq=None):
self._fcmd2('<BBBB', 0x7a, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7)
self._fcmd2("<BBBB", 0x7A, (irq is not None) << 2 | save << 1 | calib, bool(irq) << 7)
def is_touched(self):
self._send(b'\x02T')
self._send(b"\x02T")
b = self.buf[4]
self._waitfor(3, b)
return b[1] >> 7 != 0
def get_touch(self):
self._send(b'\x02T') # implicit LCD output flush
self._send(b"\x02T") # implicit LCD output flush
b = self.buf[4]
self._waitfor(3, b)
return b[1] >> 7, b[2], b[3]
@ -424,11 +430,13 @@ class LCD160CR:
#### ADVANCED COMMANDS ####
def set_spi_win(self, x, y, w, h):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xffff)
pack_into(
"<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, 10, x, y, x + w - 1, y + h - 1, 0, 0, 0, 0xFFFF
)
self._send(self.buf19)
def fast_spi(self, flush=True):
self._send(b'\x02\x12')
self._send(b"\x02\x12")
if flush:
self.oflush()
return self.spi
@ -437,27 +445,27 @@ class LCD160CR:
self.fast_spi().write(buf)
def set_scroll(self, on):
self._fcmd2('<BBB', 0x15, on)
self._fcmd2("<BBB", 0x15, on)
def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0):
pack_into('<BBBHHHHHHHH', self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
def set_scroll_win(self, win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07E0, color=0):
pack_into("<BBBHHHHHHHH", self.buf19, 0, 2, 0x55, win, x, y, w, h, vec, pat, fill, color)
self._send(self.buf19)
def set_scroll_win_param(self, win, param, value):
self._fcmd2b('<BBBBH', 0x75, win, param, value)
self._fcmd2b("<BBBBH", 0x75, win, param, value)
def set_scroll_buf(self, s):
l = len(s)
if l > 32:
raise ValueError('length must be 32 or less')
self._fcmd2('<BBB', 0x11, l)
raise ValueError("length must be 32 or less")
self._fcmd2("<BBB", 0x11, l)
self._send(s)
def jpeg_start(self, l):
if l > 0xffff:
raise ValueError('length must be 65535 or less')
if l > 0xFFFF:
raise ValueError("length must be 65535 or less")
self.oflush()
self._fcmd2('<BBH', 0x6a, l)
self._fcmd2("<BBH", 0x6A, l)
def jpeg_data(self, buf):
self._send(buf)
@ -467,8 +475,8 @@ class LCD160CR:
self.jpeg_data(buf)
def feed_wdt(self):
self._send(b'\x02\x17')
self._send(b"\x02\x17")
def reset(self):
self._send(b'\x02Y\xef\xbe\xad\xde')
self._send(b"\x02Y\xef\xbe\xad\xde")
sleep_ms(15)

Wyświetl plik

@ -3,11 +3,13 @@
import time, math, framebuf, lcd160cr
def get_lcd(lcd):
if type(lcd) is str:
lcd = lcd160cr.LCD160CR(lcd)
return lcd
def show_adc(lcd, adc):
data = [adc.read_core_temp(), adc.read_core_vbat(), 3.3]
try:
@ -21,24 +23,26 @@ def show_adc(lcd, adc):
lcd.set_pos(0, 100 + i * 16)
else:
lcd.set_font(2, trans=1)
lcd.set_pos(0, lcd.h-60 + i * 16)
lcd.write('%4s: ' % ('TEMP', 'VBAT', 'VREF')[i])
lcd.set_pos(0, lcd.h - 60 + i * 16)
lcd.write("%4s: " % ("TEMP", "VBAT", "VREF")[i])
if i > 0:
s = '%6.3fV' % data[i]
s = "%6.3fV" % data[i]
else:
s = '%5.1f°C' % data[i]
s = "%5.1f°C" % data[i]
if lcd.h == 160:
lcd.set_font(1, bold=0, scale=1)
else:
lcd.set_font(1, bold=0, scale=1, trans=1)
lcd.set_pos(45, lcd.h-60 + i * 16)
lcd.set_pos(45, lcd.h - 60 + i * 16)
lcd.write(s)
def test_features(lcd, orient=lcd160cr.PORTRAIT):
# if we run on pyboard then use ADC and RTC features
try:
import pyb
adc = pyb.ADCAll(12, 0xf0000)
adc = pyb.ADCAll(12, 0xF0000)
rtc = pyb.RTC()
except:
adc = None
@ -53,7 +57,7 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# create M-logo
mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
mlogo.fill(0)
mlogo.fill_rect(1, 1, 15, 15, 0xffffff)
mlogo.fill_rect(1, 1, 15, 15, 0xFFFFFF)
mlogo.vline(4, 4, 12, 0)
mlogo.vline(8, 1, 12, 0)
mlogo.vline(12, 4, 12, 0)
@ -80,15 +84,18 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
tx, ty = tx2, ty2
else:
tx = (tx + 1) % w
ty = (ty + 1) % h
tx = (tx + 1) % w
ty = (ty + 1) % h
# create and show the inline framebuf
fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
fbuf.line(w // 2, h // 2,
fbuf.line(
w // 2,
h // 2,
w // 2 + int(40 * math.cos(0.2 * i)),
h // 2 + int(40 * math.sin(0.2 * i)),
lcd.rgb(128, 255, 64))
lcd.rgb(128, 255, 64),
)
fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
@ -97,9 +104,12 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
fbuf.blit(mlogo, x, y)
for j in range(-3, 3):
fbuf.text('MicroPython',
5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j))
fbuf.text(
"MicroPython",
5,
h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
lcd.rgb(128 + 10 * j, 0, 128 - 10 * j),
)
lcd.show_framebuf(fbuf)
# show results from the ADC
@ -111,7 +121,10 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
lcd.set_pos(2, 0)
lcd.set_font(1)
t = rtc.datetime()
lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000))
lcd.write(
"%4d-%02d-%02d %2d:%02d:%02d.%01d"
% (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)
)
# compute the frame rate
t1 = time.ticks_us()
@ -120,13 +133,14 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
# show the frame rate
lcd.set_pos(2, 9)
lcd.write('%.2f fps' % (1000000 / dt))
lcd.write("%.2f fps" % (1000000 / dt))
def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
# set orientation and clear screen
lcd = get_lcd(lcd)
lcd.set_orient(orient)
lcd.set_pen(0, 0xffff)
lcd.set_pen(0, 0xFFFF)
lcd.erase()
# function to compute Mandelbrot pixels
@ -148,24 +162,26 @@ def test_mandel(lcd, orient=lcd160cr.PORTRAIT):
spi = lcd.fast_spi()
# draw the Mandelbrot set line-by-line
hh = ((h - 1) / 3.2)
ww = ((w - 1) / 2.4)
hh = (h - 1) / 3.2
ww = (w - 1) / 2.4
for v in range(h):
for u in range(w):
c = in_set((v / hh - 2.3) + (u / ww - 1.2) * 1j)
if c < 16:
rgb = c << 12 | c << 6
else:
rgb = 0xf800 | c << 6
rgb = 0xF800 | c << 6
line[2 * u] = rgb
line[2 * u + 1] = rgb >> 8
spi.write(line)
def test_all(lcd, orient=lcd160cr.PORTRAIT):
lcd = get_lcd(lcd)
test_features(lcd, orient)
test_mandel(lcd, orient)
print('To run all tests: test_all(<lcd>)')
print('Individual tests are: test_features, test_mandel')
print("To run all tests: test_all(<lcd>)")
print("Individual tests are: test_features, test_mandel")
print('<lcd> argument should be a connection, eg "X", or an LCD160CR object')

Wyświetl plik

@ -5,23 +5,23 @@ import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)
# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
@ -37,27 +37,37 @@ class SSD1306(framebuf.FrameBuffer):
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR, 0x00, # horizontal
SET_MEM_ADDR,
0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO,
self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET,
0x00,
SET_COM_PIN_CFG,
0x02 if self.height == 32 else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV, 0x80,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc
SET_DISP_CLK_DIV,
0x80,
SET_PRECHARGE,
0x22 if self.external_vcc else 0xF1,
SET_VCOM_DESEL,
0x30, # 0.83*Vcc
# display
SET_CONTRAST, 0xff, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
SET_CONTRAST,
0xFF, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01): # on
SET_CHARGE_PUMP,
0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01,
): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
@ -92,15 +102,15 @@ class SSD1306(framebuf.FrameBuffer):
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
self.write_list = [b'\x40', None] # Co=0, D/C#=1
self.write_list = [b"\x40", None] # Co=0, D/C#=1
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
@ -120,6 +130,7 @@ class SSD1306_SPI(SSD1306):
self.res = res
self.cs = cs
import time
self.res(1)
time.sleep_ms(1)
self.res(0)

Wyświetl plik

@ -5,49 +5,50 @@ from micropython import const
import utime
# nRF24L01+ registers
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0a)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0A)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
FIFO_STATUS = const(0x17)
DYNPD = const(0x1c)
DYNPD = const(0x1C)
# CONFIG register
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
# RF_SETUP register
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
# STATUS register
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
# FIFO_STATUS register
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
# constants for instructions
R_RX_PL_WID = const(0x60) # read RX payload width
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xa0) # write TX payload
FLUSH_TX = const(0xe1) # flush TX FIFO
FLUSH_RX = const(0xe2) # flush RX FIFO
NOP = const(0xff) # use to read STATUS register
R_RX_PL_WID = const(0x60) # read RX payload width
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xA0) # write TX payload
FLUSH_TX = const(0xE1) # flush TX FIFO
FLUSH_RX = const(0xE2) # flush RX FIFO
NOP = const(0xFF) # use to read STATUS register
class NRF24L01:
def __init__(self, spi, cs, ce, channel=46, payload_size=16):
@ -84,7 +85,7 @@ class NRF24L01:
self.reg_write(SETUP_RETR, (6 << 4) | 8)
# set rf power and speed
self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links
self.set_power_speed(POWER_3, SPEED_250K) # Best for point to point links
# init CRC
self.set_crc(2)
@ -218,7 +219,7 @@ class NRF24L01:
start = utime.ticks_ms()
result = None
while result is None and utime.ticks_diff(utime.ticks_ms(), start) < timeout:
result = self.send_done() # 1 == success, 2 == fail
result = self.send_done() # 1 == success, 2 == fail
if result == 2:
raise OSError("send failed")
@ -232,18 +233,18 @@ class NRF24L01:
self.spi.readinto(self.buf, W_TX_PAYLOAD)
self.spi.write(buf)
if len(buf) < self.payload_size:
self.spi.write(b'\x00' * (self.payload_size - len(buf))) # pad out data
self.spi.write(b"\x00" * (self.payload_size - len(buf))) # pad out data
self.cs(1)
# enable the chip so it can send the data
self.ce(1)
utime.sleep_us(15) # needs to be >10us
utime.sleep_us(15) # needs to be >10us
self.ce(0)
# returns None if send still in progress, 1 for success, 2 for fail
def send_done(self):
if not (self.reg_read(STATUS) & (TX_DS | MAX_RT)):
return None # tx not finished
return None # tx not finished
# either finished or failed: get and clear status flags, power down
status = self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)

Wyświetl plik

@ -14,27 +14,28 @@ _RX_POLL_DELAY = const(15)
# master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
_SLAVE_SEND_DELAY = const(10)
if sys.platform == 'pyboard':
cfg = {'spi': 2, 'miso': 'Y7', 'mosi': 'Y8', 'sck': 'Y6', 'csn': 'Y5', 'ce': 'Y4'}
elif sys.platform == 'esp8266': # Hardware SPI
cfg = {'spi': 1, 'miso': 12, 'mosi': 13, 'sck': 14, 'csn': 4, 'ce': 5}
elif sys.platform == 'esp32': # Software SPI
cfg = {'spi': -1, 'miso': 32, 'mosi': 33, 'sck': 25, 'csn': 26, 'ce': 27}
if sys.platform == "pyboard":
cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"}
elif sys.platform == "esp8266": # Hardware SPI
cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5}
elif sys.platform == "esp32": # Software SPI
cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27}
else:
raise ValueError('Unsupported platform {}'.format(sys.platform))
raise ValueError("Unsupported platform {}".format(sys.platform))
# Addresses are in little-endian format. They correspond to big-endian
# 0xf0f0f0f0e1, 0xf0f0f0f0d2
pipes = (b'\xe1\xf0\xf0\xf0\xf0', b'\xd2\xf0\xf0\xf0\xf0')
pipes = (b"\xe1\xf0\xf0\xf0\xf0", b"\xd2\xf0\xf0\xf0\xf0")
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']))
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 = NRF24L01(SPI(cfg["spi"]), csn, ce, payload_size=8)
nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
@ -45,16 +46,16 @@ def master():
num_failures = 0
led_state = 0
print('NRF24L01 master mode, sending %d packets...' % num_needed)
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)
led_state = max(1, (led_state << 1) & 0x0F)
print("sending:", millis, led_state)
try:
nrf.send(struct.pack('ii', millis, led_state))
nrf.send(struct.pack("ii", millis, led_state))
except OSError:
pass
@ -69,43 +70,50 @@ def master():
timeout = True
if timeout:
print('failed, response timed out')
print("failed, response timed out")
num_failures += 1
else:
# recv packet
got_millis, = struct.unpack('i', nrf.recv())
(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)')
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))
print("master finished sending; successes=%d, failures=%d" % (num_successes, num_failures))
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']))
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 = 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)')
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)
millis, led_state = struct.unpack("ii", buf)
print("received:", millis, led_state)
for led in leds:
if led_state & 1:
led.on()
@ -118,23 +126,25 @@ def slave():
utime.sleep_ms(_SLAVE_SEND_DELAY)
nrf.stop_listening()
try:
nrf.send(struct.pack('i', millis))
nrf.send(struct.pack("i", millis))
except OSError:
pass
print('sent response')
print("sent response")
nrf.start_listening()
try:
import pyb
leds = [pyb.LED(i + 1) for i in range(4)]
except:
leds = []
print('NRF24L01 test module loaded')
print('NRF24L01 pinout for test:')
print(' CE on', cfg['ce'])
print(' CSN on', cfg['csn'])
print(' SCK on', cfg['sck'])
print(' MISO on', cfg['miso'])
print(' MOSI on', cfg['mosi'])
print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master')
print("NRF24L01 test module loaded")
print("NRF24L01 pinout for test:")
print(" CE on", cfg["ce"])
print(" CSN on", cfg["csn"])
print(" SCK on", cfg["sck"])
print(" MISO on", cfg["miso"])
print(" MOSI on", cfg["mosi"])
print("run nrf24l01test.slave() on slave, then nrf24l01test.master() on master")

Wyświetl plik

@ -4,8 +4,9 @@
from micropython import const
_CONVERT = const(0x44)
_RD_SCRATCH = const(0xbe)
_WR_SCRATCH = const(0x4e)
_RD_SCRATCH = const(0xBE)
_WR_SCRATCH = const(0x4E)
class DS18X20:
def __init__(self, onewire):
@ -26,7 +27,7 @@ class DS18X20:
self.ow.writebyte(_RD_SCRATCH)
self.ow.readinto(self.buf)
if self.ow.crc8(self.buf):
raise Exception('CRC error')
raise Exception("CRC error")
return self.buf
def write_scratch(self, rom, buf):
@ -40,12 +41,12 @@ class DS18X20:
if rom[0] == 0x10:
if buf[1]:
t = buf[0] >> 1 | 0x80
t = -((~t + 1) & 0xff)
t = -((~t + 1) & 0xFF)
else:
t = buf[0] >> 1
return t - 0.25 + (buf[7] - buf[6]) / buf[7]
else:
t = buf[1] << 8 | buf[0]
if t & 0x8000: # sign bit set
t = -((t ^ 0xffff) + 1)
if t & 0x8000: # sign bit set
t = -((t ^ 0xFFFF) + 1)
return t / 16

Wyświetl plik

@ -4,13 +4,15 @@
from micropython import const
import _onewire as _ow
class OneWireError(Exception):
pass
class OneWire:
SEARCH_ROM = const(0xf0)
SEARCH_ROM = const(0xF0)
MATCH_ROM = const(0x55)
SKIP_ROM = const(0xcc)
SKIP_ROM = const(0xCC)
def __init__(self, pin):
self.pin = pin
@ -51,7 +53,7 @@ class OneWire:
devices = []
diff = 65
rom = False
for i in range(0xff):
for i in range(0xFF):
rom, diff = self._search_rom(rom, diff)
if rom:
devices += [rom]
@ -73,10 +75,10 @@ class OneWire:
for bit in range(8):
b = self.readbit()
if self.readbit():
if b: # there are no devices or there is an error on the bus
if b: # there are no devices or there is an error on the bus
return None, 0
else:
if not b: # collision, two devices with different bit meaning
if not b: # collision, two devices with different bit meaning
if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
b = 1
next_diff = i

Wyświetl plik

@ -27,15 +27,15 @@ import time
_CMD_TIMEOUT = const(100)
_R1_IDLE_STATE = const(1 << 0)
#R1_ERASE_RESET = const(1 << 1)
# R1_ERASE_RESET = const(1 << 1)
_R1_ILLEGAL_COMMAND = const(1 << 2)
#R1_COM_CRC_ERROR = const(1 << 3)
#R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
#R1_ADDRESS_ERROR = const(1 << 5)
#R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xfc)
_TOKEN_STOP_TRAN = const(0xfd)
_TOKEN_DATA = const(0xfe)
# R1_COM_CRC_ERROR = const(1 << 3)
# R1_ERASE_SEQUENCE_ERROR = const(1 << 4)
# R1_ADDRESS_ERROR = const(1 << 5)
# R1_PARAMETER_ERROR = const(1 << 6)
_TOKEN_CMD25 = const(0xFC)
_TOKEN_STOP_TRAN = const(0xFD)
_TOKEN_DATA = const(0xFE)
class SDCard:
@ -47,7 +47,7 @@ class SDCard:
self.dummybuf = bytearray(512)
self.tokenbuf = bytearray(1)
for i in range(512):
self.dummybuf[i] = 0xff
self.dummybuf[i] = 0xFF
self.dummybuf_memoryview = memoryview(self.dummybuf)
# initialise the card
@ -72,7 +72,7 @@ class SDCard:
# clock card at least 100 cycles with cs high
for i in range(16):
self.spi.write(b'\xff')
self.spi.write(b"\xff")
# CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
for _ in range(5):
@ -82,7 +82,7 @@ class SDCard:
raise OSError("no SD card")
# CMD8: determine card version
r = self.cmd(8, 0x01aa, 0x87, 4)
r = self.cmd(8, 0x01AA, 0x87, 4)
if r == _R1_IDLE_STATE:
self.init_card_v2()
elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
@ -96,15 +96,15 @@ class SDCard:
raise OSError("no response from SD card")
csd = bytearray(16)
self.readinto(csd)
if csd[0] & 0xc0 == 0x40: # CSD version 2.0
if csd[0] & 0xC0 == 0x40: # CSD version 2.0
self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
elif csd[0] & 0xc0 == 0x00: # CSD version 1.0 (old, <=2GB)
elif csd[0] & 0xC0 == 0x00: # CSD version 1.0 (old, <=2GB)
c_size = csd[6] & 0b11 | csd[7] << 2 | (csd[8] & 0b11000000) << 4
c_size_mult = ((csd[9] & 0b11) << 1) | csd[10] >> 7
self.sectors = (c_size + 1) * (2 ** (c_size_mult + 2))
else:
raise OSError("SD card CSD format not supported")
#print('sectors', self.sectors)
# print('sectors', self.sectors)
# CMD16: set block length to 512 bytes
if self.cmd(16, 512, 0) != 0:
@ -118,7 +118,7 @@ class SDCard:
self.cmd(55, 0, 0)
if self.cmd(41, 0, 0) == 0:
self.cdv = 512
#print("[SDCard] v1 card")
# print("[SDCard] v1 card")
return
raise OSError("timeout waiting for v1 card")
@ -130,7 +130,7 @@ class SDCard:
if self.cmd(41, 0x40000000, 0) == 0:
self.cmd(58, 0, 0, 4)
self.cdv = 1
#print("[SDCard] v2 card")
# print("[SDCard] v2 card")
return
raise OSError("timeout waiting for v2 card")
@ -148,24 +148,24 @@ class SDCard:
self.spi.write(buf)
if skip1:
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
# wait for the response (response[7] == 0)
for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
response = self.tokenbuf[0]
if not (response & 0x80):
# this could be a big-endian integer that we are getting here
for j in range(final):
self.spi.write(b'\xff')
self.spi.write(b"\xff")
if release:
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return response
# timeout
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return -1
def readinto(self, buf):
@ -173,7 +173,7 @@ class SDCard:
# read until start byte (0xff)
for i in range(_CMD_TIMEOUT):
self.spi.readinto(self.tokenbuf, 0xff)
self.spi.readinto(self.tokenbuf, 0xFF)
if self.tokenbuf[0] == _TOKEN_DATA:
break
else:
@ -183,15 +183,15 @@ class SDCard:
# read data
mv = self.dummybuf_memoryview
if len(buf) != len(mv):
mv = mv[:len(buf)]
mv = mv[: len(buf)]
self.spi.write_readinto(mv, buf)
# read checksum
self.spi.write(b'\xff')
self.spi.write(b'\xff')
self.spi.write(b"\xff")
self.spi.write(b"\xff")
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def write(self, token, buf):
self.cs(0)
@ -199,42 +199,42 @@ class SDCard:
# send: start of block, data, checksum
self.spi.read(1, token)
self.spi.write(buf)
self.spi.write(b'\xff')
self.spi.write(b'\xff')
self.spi.write(b"\xff")
self.spi.write(b"\xff")
# check the response
if (self.spi.read(1, 0xff)[0] & 0x1f) != 0x05:
if (self.spi.read(1, 0xFF)[0] & 0x1F) != 0x05:
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
return
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0:
while self.spi.read(1, 0xFF)[0] == 0:
pass
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def write_token(self, token):
self.cs(0)
self.spi.read(1, token)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
# wait for write to finish
while self.spi.read(1, 0xff)[0] == 0x00:
while self.spi.read(1, 0xFF)[0] == 0x00:
pass
self.cs(1)
self.spi.write(b'\xff')
self.spi.write(b"\xff")
def readblocks(self, block_num, buf):
nblocks = len(buf) // 512
assert nblocks and not len(buf) % 512, 'Buffer length is invalid'
assert nblocks and not len(buf) % 512, "Buffer length is invalid"
if nblocks == 1:
# CMD17: set read address for single block
if self.cmd(17, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
raise OSError(5) # EIO
# receive the data and release card
self.readinto(buf)
else:
@ -242,7 +242,7 @@ class SDCard:
if self.cmd(18, block_num * self.cdv, 0, release=False) != 0:
# release the card
self.cs(1)
raise OSError(5) # EIO
raise OSError(5) # EIO
offset = 0
mv = memoryview(buf)
while nblocks:
@ -250,23 +250,23 @@ class SDCard:
self.readinto(mv[offset : offset + 512])
offset += 512
nblocks -= 1
if self.cmd(12, 0, 0xff, skip1=True):
raise OSError(5) # EIO
if self.cmd(12, 0, 0xFF, skip1=True):
raise OSError(5) # EIO
def writeblocks(self, block_num, buf):
nblocks, err = divmod(len(buf), 512)
assert nblocks and not err, 'Buffer length is invalid'
assert nblocks and not err, "Buffer length is invalid"
if nblocks == 1:
# CMD24: set write address for single block
if self.cmd(24, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
raise OSError(5) # EIO
# send the data
self.write(_TOKEN_DATA, buf)
else:
# CMD25: set write address for first block
if self.cmd(25, block_num * self.cdv, 0) != 0:
raise OSError(5) # EIO
raise OSError(5) # EIO
# send the data
offset = 0
mv = memoryview(buf)
@ -277,5 +277,5 @@ class SDCard:
self.write_token(_TOKEN_STOP_TRAN)
def ioctl(self, op, arg):
if op == 4: # get number of blocks
if op == 4: # get number of blocks
return self.sectors

Wyświetl plik

@ -2,59 +2,60 @@
# Peter hinch 30th Jan 2016
import os, sdcard, machine
def sdtest():
spi = machine.SPI(1)
spi.init() # Ensure right baudrate
sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
vfs = os.VfsFat(sd)
os.mount(vfs, '/fc')
print('Filesystem check')
print(os.listdir('/fc'))
os.mount(vfs, "/fc")
print("Filesystem check")
print(os.listdir("/fc"))
line = 'abcdefghijklmnopqrstuvwxyz\n'
lines = line * 200 # 5400 chars
short = '1234567890\n'
line = "abcdefghijklmnopqrstuvwxyz\n"
lines = line * 200 # 5400 chars
short = "1234567890\n"
fn = '/fc/rats.txt'
fn = "/fc/rats.txt"
print()
print('Multiple block read/write')
with open(fn,'w') as f:
print("Multiple block read/write")
with open(fn, "w") as f:
n = f.write(lines)
print(n, 'bytes written')
print(n, "bytes written")
n = f.write(short)
print(n, 'bytes written')
print(n, "bytes written")
n = f.write(lines)
print(n, 'bytes written')
print(n, "bytes written")
with open(fn,'r') as f:
with open(fn, "r") as f:
result1 = f.read()
print(len(result1), 'bytes read')
print(len(result1), "bytes read")
fn = '/fc/rats1.txt'
fn = "/fc/rats1.txt"
print()
print('Single block read/write')
with open(fn,'w') as f:
n = f.write(short) # one block
print(n, 'bytes written')
print("Single block read/write")
with open(fn, "w") as f:
n = f.write(short) # one block
print(n, "bytes written")
with open(fn,'r') as f:
with open(fn, "r") as f:
result2 = f.read()
print(len(result2), 'bytes read')
print(len(result2), "bytes read")
os.umount('/fc')
os.umount("/fc")
print()
print('Verifying data read back')
print("Verifying data read back")
success = True
if result1 == ''.join((lines, short, lines)):
print('Large file Pass')
if result1 == "".join((lines, short, lines)):
print("Large file Pass")
else:
print('Large file Fail')
print("Large file Fail")
success = False
if result2 == short:
print('Small file Pass')
print("Small file Pass")
else:
print('Small file Fail')
print("Small file Fail")
success = False
print()
print('Tests', 'passed' if success else 'failed')
print("Tests", "passed" if success else "failed")

Wyświetl plik

@ -8,18 +8,18 @@
import pyb
pyb.LED(3).on() # indicate we are waiting for switch press
pyb.delay(2000) # wait for user to maybe press the switch
switch_value = pyb.Switch()() # sample the switch at end of delay
pyb.LED(3).off() # indicate that we finished waiting for the switch
pyb.LED(3).on() # indicate we are waiting for switch press
pyb.delay(2000) # wait for user to maybe press the switch
switch_value = pyb.Switch()() # sample the switch at end of delay
pyb.LED(3).off() # indicate that we finished waiting for the switch
pyb.LED(4).on() # indicate that we are selecting the mode
pyb.LED(4).on() # indicate that we are selecting the mode
if switch_value:
pyb.usb_mode('VCP+MSC')
pyb.main('cardreader.py') # if switch was pressed, run this
pyb.usb_mode("VCP+MSC")
pyb.main("cardreader.py") # if switch was pressed, run this
else:
pyb.usb_mode('VCP+HID')
pyb.main('datalogger.py') # if switch wasn't pressed, run this
pyb.usb_mode("VCP+HID")
pyb.main("datalogger.py") # if switch wasn't pressed, run this
pyb.LED(4).off() # indicate that we finished selecting the mode
pyb.LED(4).off() # indicate that we finished selecting the mode

Wyświetl plik

@ -17,17 +17,17 @@ while True:
# start if switch is pressed
if switch():
pyb.delay(200) # delay avoids detection of multiple presses
blue.on() # blue LED indicates file open
log = open('/sd/log.csv', 'w') # open file on SD (SD: '/sd/', flash: '/flash/)
pyb.delay(200) # delay avoids detection of multiple presses
blue.on() # blue LED indicates file open
log = open("/sd/log.csv", "w") # open file on SD (SD: '/sd/', flash: '/flash/)
# until switch is pressed again
while not switch():
t = pyb.millis() # get time
x, y, z = accel.filtered_xyz() # get acceleration data
log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file
t = pyb.millis() # get time
x, y, z = accel.filtered_xyz() # get acceleration data
log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
# end after switch is pressed again
log.close() # close file
blue.off() # blue LED indicates file closed
pyb.delay(200) # delay avoids detection of multiple presses
log.close() # close file
blue.off() # blue LED indicates file closed
pyb.delay(200) # delay avoids detection of multiple presses

Wyświetl plik

@ -17,10 +17,10 @@ accel_pwr.value(1)
i2c = I2C(1, baudrate=100000)
addrs = i2c.scan()
print("Scanning devices:", [hex(x) for x in addrs])
if 0x4c not in addrs:
if 0x4C not in addrs:
print("Accelerometer is not detected")
ACCEL_ADDR = 0x4c
ACCEL_ADDR = 0x4C
ACCEL_AXIS_X_REG = 0
ACCEL_MODE_REG = 7

Wyświetl plik

@ -2,19 +2,19 @@
import pyb
accel = pyb.Accel() # create object of accelerometer
blue = pyb.LED(4) # create object of blue LED
accel = pyb.Accel() # create object of accelerometer
blue = pyb.LED(4) # create object of blue LED
# open file to write data - /sd/ is the SD-card, /flash/ the internal memory
log = open('/sd/log.csv', 'w')
log = open("/sd/log.csv", "w")
blue.on() # turn on blue LED
blue.on() # turn on blue LED
# do 100 times (if the board is connected via USB, you can't write longer because the PC tries to open the filesystem which messes up your file.)
for i in range(100):
t = pyb.millis() # get time since reset
x, y, z = accel.filtered_xyz() # get acceleration data
log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file
t = pyb.millis() # get time since reset
x, y, z = accel.filtered_xyz() # get acceleration data
log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
log.close() # close file
blue.off() # turn off LED
log.close() # close file
blue.off() # turn off LED

Wyświetl plik

@ -2,8 +2,8 @@
# this version is overly verbose and uses word stores
@micropython.asm_thumb
def flash_led(r0):
movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xffff)
movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7fff)
movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xFFFF)
movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7FFF)
movw(r2, 1 << 13)
movt(r2, 0)
movw(r3, 0)
@ -17,8 +17,8 @@ def flash_led(r0):
str(r2, [r1, 0])
# delay for a bit
movw(r4, 5599900 & 0xffff)
movt(r4, (5599900 >> 16) & 0xffff)
movw(r4, 5599900 & 0xFFFF)
movt(r4, (5599900 >> 16) & 0xFFFF)
label(delay_on)
sub(r4, r4, 1)
cmp(r4, 0)
@ -28,8 +28,8 @@ def flash_led(r0):
str(r3, [r1, 0])
# delay for a bit
movw(r4, 5599900 & 0xffff)
movt(r4, (5599900 >> 16) & 0xffff)
movw(r4, 5599900 & 0xFFFF)
movt(r4, (5599900 >> 16) & 0xFFFF)
label(delay_off)
sub(r4, r4, 1)
cmp(r4, 0)
@ -41,6 +41,7 @@ def flash_led(r0):
cmp(r0, 0)
bgt(loop1)
# flash LED #2 using inline assembler
# this version uses half-word sortes, and the convenience assembler operation 'movwt'
@micropython.asm_thumb
@ -81,5 +82,6 @@ def flash_led_v2(r0):
cmp(r0, 0)
bgt(loop1)
flash_led(5)
flash_led_v2(5)

Wyświetl plik

@ -22,6 +22,7 @@ def asm_sum_words(r0, r1):
mov(r0, r2)
@micropython.asm_thumb
def asm_sum_bytes(r0, r1):
@ -46,12 +47,13 @@ def asm_sum_bytes(r0, r1):
mov(r0, r2)
import array
b = array.array('l', (100, 200, 300, 400))
b = array.array("l", (100, 200, 300, 400))
n = asm_sum_words(len(b), b)
print(b, n)
b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80))
b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80))
n = asm_sum_bytes(len(b), b)
print(b, n)

Wyświetl plik

@ -26,9 +26,12 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No
def _append(adv_type, value):
nonlocal payload
payload += struct.pack('BB', len(value) + 1, adv_type) + value
payload += struct.pack("BB", len(value) + 1, adv_type) + value
_append(_ADV_TYPE_FLAGS, struct.pack('B', (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)))
_append(
_ADV_TYPE_FLAGS,
struct.pack("B", (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)),
)
if name:
_append(_ADV_TYPE_NAME, name)
@ -44,7 +47,7 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No
_append(_ADV_TYPE_UUID128_COMPLETE, b)
# See org.bluetooth.characteristic.gap.appearance.xml
_append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance))
_append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance))
return payload
@ -54,32 +57,36 @@ def decode_field(payload, adv_type):
result = []
while i + 1 < len(payload):
if payload[i + 1] == adv_type:
result.append(payload[i + 2:i + payload[i] + 1])
result.append(payload[i + 2 : i + payload[i] + 1])
i += 1 + payload[i]
return result
def decode_name(payload):
n = decode_field(payload, _ADV_TYPE_NAME)
return str(n[0], 'utf-8') if n else ''
return str(n[0], "utf-8") if n else ""
def decode_services(payload):
services = []
for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE):
services.append(bluetooth.UUID(struct.unpack('<h', u)[0]))
services.append(bluetooth.UUID(struct.unpack("<h", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE):
services.append(bluetooth.UUID(struct.unpack('<d', u)[0]))
services.append(bluetooth.UUID(struct.unpack("<d", u)[0]))
for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE):
services.append(bluetooth.UUID(u))
return services
def demo():
payload = advertising_payload(name='micropython', services=[bluetooth.UUID(0x181A), bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')])
payload = advertising_payload(
name="micropython",
services=[bluetooth.UUID(0x181A), bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")],
)
print(payload)
print(decode_name(payload))
print(decode_services(payload))
if __name__ == '__main__':
if __name__ == "__main__":
demo()

Wyświetl plik

@ -10,26 +10,36 @@ import time
from ble_advertising import advertising_payload
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
# org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bluetooth.UUID(0x181A)
# org.bluetooth.characteristic.temperature
_TEMP_CHAR = (bluetooth.UUID(0x2A6E), bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,)
_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),)
_TEMP_CHAR = (
bluetooth.UUID(0x2A6E),
bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
_ENV_SENSE_SERVICE = (
_ENV_SENSE_UUID,
(_TEMP_CHAR,),
)
# org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
class BLETemperature:
def __init__(self, ble, name='mpy-temp'):
def __init__(self, ble, name="mpy-temp"):
self._ble = ble
self._ble.active(True)
self._ble.irq(handler=self._irq)
((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,))
self._connections = set()
self._payload = advertising_payload(name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER)
self._payload = advertising_payload(
name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER
)
self._advertise()
def _irq(self, event, data):
@ -46,7 +56,7 @@ class BLETemperature:
def set_temperature(self, temp_deg_c, notify=False):
# Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
# Write the local value, ready for a central to read.
self._ble.gatts_write(self._handle, struct.pack('<h', int(temp_deg_c * 100)))
self._ble.gatts_write(self._handle, struct.pack("<h", int(temp_deg_c * 100)))
if notify:
for conn_handle in self._connections:
# Notify connected centrals to issue a read.
@ -72,5 +82,5 @@ def demo():
time.sleep_ms(1000)
if __name__ == '__main__':
if __name__ == "__main__":
demo()

Wyświetl plik

@ -9,33 +9,41 @@ import micropython
from ble_advertising import decode_services, decode_name
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2)
_IRQ_GATTS_READ_REQUEST = const(1 << 3)
_IRQ_SCAN_RESULT = const(1 << 4)
_IRQ_SCAN_COMPLETE = const(1 << 5)
_IRQ_PERIPHERAL_CONNECT = const(1 << 6)
_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
_IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10)
_IRQ_GATTC_READ_RESULT = const(1 << 11)
_IRQ_GATTC_WRITE_STATUS = const(1 << 12)
_IRQ_GATTC_NOTIFY = const(1 << 13)
_IRQ_GATTC_INDICATE = const(1 << 14)
_IRQ_ALL = const(0xffff)
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2)
_IRQ_GATTS_READ_REQUEST = const(1 << 3)
_IRQ_SCAN_RESULT = const(1 << 4)
_IRQ_SCAN_COMPLETE = const(1 << 5)
_IRQ_PERIPHERAL_CONNECT = const(1 << 6)
_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7)
_IRQ_GATTC_SERVICE_RESULT = const(1 << 8)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10)
_IRQ_GATTC_READ_RESULT = const(1 << 11)
_IRQ_GATTC_WRITE_STATUS = const(1 << 12)
_IRQ_GATTC_NOTIFY = const(1 << 13)
_IRQ_GATTC_INDICATE = const(1 << 14)
_IRQ_ALL = const(0xFFFF)
# org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bluetooth.UUID(0x181A)
# org.bluetooth.characteristic.temperature
_TEMP_UUID = bluetooth.UUID(0x2A6E)
_TEMP_CHAR = (_TEMP_UUID, bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,)
_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),)
_TEMP_CHAR = (
_TEMP_UUID,
bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
)
_ENV_SENSE_SERVICE = (
_ENV_SENSE_UUID,
(_TEMP_CHAR,),
)
# org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)
class BLETemperatureCentral:
def __init__(self, ble):
self._ble = ble
@ -72,8 +80,10 @@ class BLETemperatureCentral:
if connectable and _ENV_SENSE_UUID in decode_services(adv_data):
# Found a potential device, remember it and stop scanning.
self._addr_type = addr_type
self._addr = bytes(addr) # Note: addr buffer is owned by caller so need to copy it.
self._name = decode_name(adv_data) or '?'
self._addr = bytes(
addr
) # Note: addr buffer is owned by caller so need to copy it.
self._name = decode_name(adv_data) or "?"
self._ble.gap_scan(None)
elif event == _IRQ_SCAN_COMPLETE:
@ -104,7 +114,9 @@ class BLETemperatureCentral:
# Connected device returned a service.
conn_handle, start_handle, end_handle, uuid = data
if conn_handle == self._conn_handle and uuid == _ENV_SENSE_UUID:
self._ble.gattc_discover_characteristics(self._conn_handle, start_handle, end_handle)
self._ble.gattc_discover_characteristics(
self._conn_handle, start_handle, end_handle
)
elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Connected device returned a characteristic.
@ -132,7 +144,6 @@ class BLETemperatureCentral:
if self._notify_callback:
self._notify_callback(self._value)
# Returns true if we've successfully connected and discovered characteristics.
def is_connected(self):
return self._conn_handle is not None and self._value_handle is not None
@ -174,7 +185,7 @@ class BLETemperatureCentral:
def _update_value(self, data):
# Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius.
self._value = struct.unpack('<h', data)[0] / 100
self._value = struct.unpack("<h", data)[0] / 100
return self._value
def value(self):
@ -189,12 +200,12 @@ def demo():
def on_scan(addr_type, addr, name):
if addr_type is not None:
print('Found sensor:', addr_type, addr, name)
print("Found sensor:", addr_type, addr, name)
central.connect()
else:
nonlocal not_found
not_found = True
print('No sensor found.')
print("No sensor found.")
central.scan(callback=on_scan)
@ -204,7 +215,7 @@ def demo():
if not_found:
return
print('Connected')
print("Connected")
# Explicitly issue reads, using "print" as the callback.
while central.is_connected():
@ -216,7 +227,8 @@ def demo():
# print(central.value())
# time.sleep_ms(2000)
print('Disconnected')
print("Disconnected")
if __name__ == '__main__':
if __name__ == "__main__":
demo()

Wyświetl plik

@ -4,24 +4,37 @@ import bluetooth
from ble_advertising import advertising_payload
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2)
_UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
_UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_NOTIFY,)
_UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,)
_UART_SERVICE = (_UART_UUID, (_UART_TX, _UART_RX,),)
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
_IRQ_GATTS_WRITE = const(1 << 2)
_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (
bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
bluetooth.FLAG_NOTIFY,
)
_UART_RX = (
bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
bluetooth.FLAG_WRITE,
)
_UART_SERVICE = (
_UART_UUID,
(_UART_TX, _UART_RX,),
)
# org.bluetooth.characteristic.gap.appearance.xml
_ADV_APPEARANCE_GENERIC_COMPUTER = const(128)
class BLEUART:
def __init__(self, ble, name='mpy-uart', rxbuf=100):
def __init__(self, ble, name="mpy-uart", rxbuf=100):
self._ble = ble
self._ble.active(True)
self._ble.irq(handler=self._irq)
((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services((_UART_SERVICE,))
((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services(
(_UART_SERVICE,)
)
# Increase the size of the rx buffer and enable append mode.
self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True)
self._connections = set()
@ -82,7 +95,7 @@ def demo():
uart = BLEUART(ble)
def on_rx():
print('rx: ', uart.read().decode().strip())
print("rx: ", uart.read().decode().strip())
uart.irq(handler=on_rx)
nums = [4, 8, 15, 16, 23, 42]
@ -90,7 +103,7 @@ def demo():
try:
while True:
uart.write(str(nums[i]) + '\n')
uart.write(str(nums[i]) + "\n")
i = (i + 1) % len(nums)
time.sleep_ms(1000)
except KeyboardInterrupt:
@ -99,5 +112,5 @@ def demo():
uart.close()
if __name__ == '__main__':
if __name__ == "__main__":
demo()

Wyświetl plik

@ -15,7 +15,7 @@ _MP_STREAM_POLL = const(3)
_MP_STREAM_POLL_RD = const(0x0001)
# TODO: Remove this when STM32 gets machine.Timer.
if hasattr(machine, 'Timer'):
if hasattr(machine, "Timer"):
_timer = machine.Timer(-1)
else:
_timer = None
@ -24,11 +24,13 @@ else:
def schedule_in(handler, delay_ms):
def _wrap(_arg):
handler()
if _timer:
_timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap)
else:
micropython.schedule(_wrap, None)
# Simple buffering stream to support the dupterm requirements.
class BLEUARTStream(io.IOBase):
def __init__(self, uart):
@ -38,7 +40,7 @@ class BLEUARTStream(io.IOBase):
def _on_rx(self):
# Needed for ESP32.
if hasattr(os, 'dupterm_notify'):
if hasattr(os, "dupterm_notify"):
os.dupterm_notify(None)
def read(self, sz=None):
@ -74,7 +76,7 @@ class BLEUARTStream(io.IOBase):
def start():
ble = bluetooth.BLE()
uart = BLEUART(ble, name='mpy-repl')
uart = BLEUART(ble, name="mpy-repl")
stream = BLEUARTStream(uart)
os.dupterm(stream)

Wyświetl plik

@ -1,46 +1,51 @@
#import essential libraries
# import essential libraries
import pyb
lcd = pyb.LCD('x')
lcd = pyb.LCD("x")
lcd.light(1)
# do 1 iteration of Conway's Game of Life
def conway_step():
for x in range(128): # loop over x coordinates
for y in range(32): # loop over y coordinates
for x in range(128): # loop over x coordinates
for y in range(32): # loop over y coordinates
# count number of neighbours
num_neighbours = (lcd.get(x - 1, y - 1) +
lcd.get(x, y - 1) +
lcd.get(x + 1, y - 1) +
lcd.get(x - 1, y) +
lcd.get(x + 1, y) +
lcd.get(x + 1, y + 1) +
lcd.get(x, y + 1) +
lcd.get(x - 1, y + 1))
num_neighbours = (
lcd.get(x - 1, y - 1)
+ lcd.get(x, y - 1)
+ lcd.get(x + 1, y - 1)
+ lcd.get(x - 1, y)
+ lcd.get(x + 1, y)
+ lcd.get(x + 1, y + 1)
+ lcd.get(x, y + 1)
+ lcd.get(x - 1, y + 1)
)
# check if the centre cell is alive or not
self = lcd.get(x, y)
# apply the rules of life
if self and not (2 <= num_neighbours <= 3):
lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies
lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies
elif not self and num_neighbours == 3:
lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born
lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born
# randomise the start
def conway_rand():
lcd.fill(0) # clear the LCD
for x in range(128): # loop over x coordinates
for y in range(32): # loop over y coordinates
lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly
lcd.fill(0) # clear the LCD
for x in range(128): # loop over x coordinates
for y in range(32): # loop over y coordinates
lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly
# loop for a certain number of frames, doing iterations of Conway's Game of Life
def conway_go(num_frames):
for i in range(num_frames):
conway_step() # do 1 iteration
lcd.show() # update the LCD
conway_step() # do 1 iteration
lcd.show() # update the LCD
pyb.delay(50)
# testing
conway_rand()
conway_go(100)

Wyświetl plik

@ -4,14 +4,16 @@ from hwconfig import LED, BUTTON
# machine.time_pulse_us() function demo
print("""\
print(
"""\
Let's play an interesting game:
You click button as fast as you can, and I tell you how slow you are.
Ready? Cliiiiick!
""")
"""
)
while 1:
delay = machine.time_pulse_us(BUTTON, 1, 10*1000*1000)
delay = machine.time_pulse_us(BUTTON, 1, 10 * 1000 * 1000)
if delay < 0:
print("Well, you're *really* slow")
else:

Wyświetl plik

@ -1,7 +1,6 @@
# This is hwconfig for "emulation" for cases when there's no real hardware.
# It just prints information to console.
class LEDClass:
def __init__(self, id):
self.id = "LED(%d):" % id

Wyświetl plik

@ -1,13 +1,13 @@
from machine import Pin, Signal
# Red LED on pin LED_RED also kown as A13
LED = Signal('LED_RED', Pin.OUT)
LED = Signal("LED_RED", Pin.OUT)
# Green LED on pin LED_GREEN also known as A14
LED2 = Signal('LED_GREEN', Pin.OUT)
LED2 = Signal("LED_GREEN", Pin.OUT)
# Yellow LED on pin LED_YELLOW also known as A15
LED3 = Signal('LED_YELLOW', Pin.OUT)
LED3 = Signal("LED_YELLOW", Pin.OUT)
# Blue LED on pin LED_BLUE also known as B4
LED4 = Signal('LED_BLUE', Pin.OUT)
LED4 = Signal("LED_BLUE", Pin.OUT)

Wyświetl plik

@ -1,5 +1,6 @@
import pyb
def led_angle(seconds_to_run_for):
# make LED objects
l1 = pyb.LED(1)

Wyświetl plik

@ -3,13 +3,14 @@ try:
except:
pass
def mandelbrot():
# returns True if c, complex, is in the Mandelbrot set
#@micropython.native
# @micropython.native
def in_set(c):
z = 0
for i in range(40):
z = z*z + c
z = z * z + c
if abs(z) > 60:
return False
return True
@ -21,7 +22,9 @@ def mandelbrot():
lcd.set(u, v)
lcd.show()
# PC testing
import lcd
lcd = lcd.LCD(128, 32)
mandelbrot()

Wyświetl plik

@ -2,7 +2,9 @@
# Dummy function decorators
def nodecor(x):
return x
bytecode = native = viper = nodecor

Wyświetl plik

@ -2,20 +2,22 @@
import array
def isclose(a, b):
return abs(a - b) < 1e-3
def test():
tests = [
isclose(add(0.1, 0.2), 0.3),
isclose(add_f(0.1, 0.2), 0.3),
]
ar = array.array('f', [1, 2, 3.5])
ar = array.array("f", [1, 2, 3.5])
productf(ar)
tests.append(isclose(ar[0], 7))
if 'add_d' in globals():
if "add_d" in globals():
tests.append(isclose(add_d(0.1, 0.2), 0.3))
print(tests)
@ -23,4 +25,5 @@ def test():
if not all(tests):
raise SystemExit(1)
test()

Wyświetl plik

@ -10,6 +10,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main(micropython_optimize=False):
s = socket.socket()

Wyświetl plik

@ -12,6 +12,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main():
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)

Wyświetl plik

@ -20,6 +20,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main():
s = socket.socket()

Wyświetl plik

@ -1,4 +1,5 @@
import ubinascii as binascii
try:
import usocket as socket
except:
@ -9,30 +10,32 @@ import ussl as ssl
# This self-signed key/cert pair is randomly generated and to be used for
# testing/demonstration only. You should always generate your own key/cert.
key = binascii.unhexlify(
b'3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef'
b'610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f'
b'872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0'
b'd05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d'
b'd9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86'
b'8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483'
b'02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102'
b'2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044'
b'6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f')
b"3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef"
b"610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f"
b"872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0"
b"d05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d"
b"d9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86"
b"8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483"
b"02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102"
b"2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044"
b"6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f"
)
cert = binascii.unhexlify(
b'308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355'
b'0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504'
b'070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106'
b'0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61'
b'6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075'
b'310b30090603550406130258583114301206035504080c0b54686550726f76696e636531'
b'10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958'
b'595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468'
b'65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20'
b'643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18'
b'a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a'
b'864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8'
b'e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef'
b'979b57f0b3')
b"308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355"
b"0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504"
b"070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106"
b"0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61"
b"6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075"
b"310b30090603550406130258583114301206035504080c0b54686550726f76696e636531"
b"10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958"
b"595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468"
b"65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20"
b"643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18"
b"a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a"
b"864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8"
b"e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef"
b"979b57f0b3"
)
CONTENT = b"""\
@ -41,6 +44,7 @@ HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main(use_stream=True):
s = socket.socket()

Wyświetl plik

@ -4,6 +4,7 @@
import pyb
import pins_af
def af():
max_name_width = 0
max_af_width = 0
@ -13,21 +14,22 @@ def af():
max_af_width = max(max_af_width, len(af_entry[1]))
for pin_entry in pins_af.PINS_AF:
pin_name = pin_entry[0]
print('%-*s ' % (max_name_width, pin_name), end='')
print("%-*s " % (max_name_width, pin_name), end="")
for af_entry in pin_entry[1:]:
print('%2d: %-*s ' % (af_entry[0], max_af_width, af_entry[1]), end='')
print('')
print("%2d: %-*s " % (af_entry[0], max_af_width, af_entry[1]), end="")
print("")
def pins():
mode_str = { pyb.Pin.IN : 'IN',
pyb.Pin.OUT_PP : 'OUT_PP',
pyb.Pin.OUT_OD : 'OUT_OD',
pyb.Pin.AF_PP : 'AF_PP',
pyb.Pin.AF_OD : 'AF_OD',
pyb.Pin.ANALOG : 'ANALOG' }
pull_str = { pyb.Pin.PULL_NONE : '',
pyb.Pin.PULL_UP : 'PULL_UP',
pyb.Pin.PULL_DOWN : 'PULL_DOWN' }
mode_str = {
pyb.Pin.IN: "IN",
pyb.Pin.OUT_PP: "OUT_PP",
pyb.Pin.OUT_OD: "OUT_OD",
pyb.Pin.AF_PP: "AF_PP",
pyb.Pin.AF_OD: "AF_OD",
pyb.Pin.ANALOG: "ANALOG",
}
pull_str = {pyb.Pin.PULL_NONE: "", pyb.Pin.PULL_UP: "PULL_UP", pyb.Pin.PULL_DOWN: "PULL_DOWN"}
width = [0, 0, 0, 0]
rows = []
for pin_entry in pins_af.PINS_AF:
@ -42,17 +44,17 @@ def pins():
pin_af = pin.af()
for af_entry in pin_entry[1:]:
if pin_af == af_entry[0]:
af_str = '%d: %s' % (pin_af, af_entry[1])
af_str = "%d: %s" % (pin_af, af_entry[1])
break
else:
af_str = '%d' % pin_af
af_str = "%d" % pin_af
else:
af_str = ''
af_str = ""
row.append(af_str)
for col in range(len(width)):
width[col] = max(width[col], len(row[col]))
rows.append(row)
for row in rows:
for col in range(len(width)):
print('%-*s ' % (width[col], row[col]), end='')
print('')
print("%-*s " % (width[col], row[col]), end="")
print("")

Wyświetl plik

@ -1,17 +1,22 @@
# pyboard testing functions for CPython
import time
def delay(n):
#time.sleep(float(n) / 1000)
# time.sleep(float(n) / 1000)
pass
rand_seed = 1
def rng():
global rand_seed
# for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure"
rand_seed = (rand_seed * 653276) % 8388593
return rand_seed
# LCD testing object for PC
# uses double buffering
class LCD:
@ -30,12 +35,12 @@ class LCD:
self.buf1[y][x] = self.buf2[y][x] = value
def show(self):
print('') # blank line to separate frames
print("") # blank line to separate frames
for y in range(self.height):
for x in range(self.width):
self.buf1[y][x] = self.buf2[y][x]
for y in range(self.height):
row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)])
row = "".join(["*" if self.buf1[y][x] else " " for x in range(self.width)])
print(row)
def get(self, x, y):

Wyświetl plik

@ -24,6 +24,7 @@ orange_led = pyb.LED(3)
blue_led = pyb.LED(4)
all_leds = (red_led, green_led, orange_led, blue_led)
def run_loop(leds=all_leds):
"""
Start the loop.
@ -31,15 +32,16 @@ def run_loop(leds=all_leds):
:param `leds`: Which LEDs to light up upon switch press.
:type `leds`: sequence of LED objects
"""
print('Loop started.\nPress Ctrl+C to break out of the loop.')
print("Loop started.\nPress Ctrl+C to break out of the loop.")
while 1:
try:
if switch():
[led.on() for led in leds]
else:
[led.off() for led in leds]
except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
break
if __name__ == '__main__':
if __name__ == "__main__":
run_loop()

Wyświetl plik

@ -24,12 +24,14 @@ print("errno value:", errno.get())
perror("perror after error")
print()
def cmp(pa, pb):
a = uctypes.bytearray_at(pa, 1)
b = uctypes.bytearray_at(pb, 1)
print("cmp:", a, b)
return a[0] - b[0]
cmp_cb = ffi.callback("i", cmp, "PP")
print("callback:", cmp_cb)

Wyświetl plik

@ -6,4 +6,4 @@
import umachine as machine
print(hex(machine.mem16[0xc0000]))
print(hex(machine.mem16[0xC0000]))

Wyświetl plik

@ -183,7 +183,7 @@ STATIC int mp_hal_i2c_read_byte(machine_i2c_obj_t *self, uint8_t *val, int nack)
// >=0 - success; for read it's 0, for write it's number of acks received
// <0 - error, with errno being the negative of the return value
int mp_machine_soft_i2c_transfer(mp_obj_base_t *self_in, uint16_t addr, size_t n, mp_machine_i2c_buf_t *bufs, unsigned int flags) {
machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
// start the I2C transaction
int ret = mp_hal_i2c_start(self);
@ -267,7 +267,7 @@ int mp_machine_i2c_transfer_adaptor(mp_obj_base_t *self, uint16_t addr, size_t n
}
}
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
int ret = i2c_p->transfer_single(self, addr, len, buf, flags);
if (n > 1) {
@ -286,15 +286,15 @@ int mp_machine_i2c_transfer_adaptor(mp_obj_base_t *self, uint16_t addr, size_t n
}
STATIC int mp_machine_i2c_readfrom(mp_obj_base_t *self, uint16_t addr, uint8_t *dest, size_t len, bool stop) {
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
mp_machine_i2c_buf_t buf = {.len = len, .buf = dest};
unsigned int flags = MP_MACHINE_I2C_FLAG_READ | (stop ? MP_MACHINE_I2C_FLAG_STOP : 0);
return i2c_p->transfer(self, addr, 1, &buf, flags);
}
STATIC int mp_machine_i2c_writeto(mp_obj_base_t *self, uint16_t addr, const uint8_t *src, size_t len, bool stop) {
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_machine_i2c_buf_t buf = {.len = len, .buf = (uint8_t*)src};
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
mp_machine_i2c_buf_t buf = {.len = len, .buf = (uint8_t *)src};
unsigned int flags = stop ? MP_MACHINE_I2C_FLAG_STOP : 0;
return i2c_p->transfer(self, addr, 1, &buf, flags);
}
@ -364,8 +364,8 @@ STATIC mp_obj_t machine_i2c_scan(mp_obj_t self_in) {
MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_scan_obj, machine_i2c_scan);
STATIC mp_obj_t machine_i2c_start(mp_obj_t self_in) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
if (i2c_p->start == NULL) {
mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
}
@ -378,8 +378,8 @@ STATIC mp_obj_t machine_i2c_start(mp_obj_t self_in) {
MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_start_obj, machine_i2c_start);
STATIC mp_obj_t machine_i2c_stop(mp_obj_t self_in) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
if (i2c_p->stop == NULL) {
mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
}
@ -392,8 +392,8 @@ STATIC mp_obj_t machine_i2c_stop(mp_obj_t self_in) {
MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_stop_obj, machine_i2c_stop);
STATIC mp_obj_t machine_i2c_readinto(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
if (i2c_p->read == NULL) {
mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
}
@ -416,8 +416,8 @@ STATIC mp_obj_t machine_i2c_readinto(size_t n_args, const mp_obj_t *args) {
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readinto_obj, 2, 3, machine_i2c_readinto);
STATIC mp_obj_t machine_i2c_write(mp_obj_t self_in, mp_obj_t buf_in) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
if (i2c_p->write == NULL) {
mp_raise_msg(&mp_type_OSError, "I2C operation not supported");
}
@ -438,12 +438,12 @@ STATIC mp_obj_t machine_i2c_write(mp_obj_t self_in, mp_obj_t buf_in) {
MP_DEFINE_CONST_FUN_OBJ_2(machine_i2c_write_obj, machine_i2c_write);
STATIC mp_obj_t machine_i2c_readfrom(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_int_t addr = mp_obj_get_int(args[1]);
vstr_t vstr;
vstr_init_len(&vstr, mp_obj_get_int(args[2]));
bool stop = (n_args == 3) ? true : mp_obj_is_true(args[3]);
int ret = mp_machine_i2c_readfrom(self, addr, (uint8_t*)vstr.buf, vstr.len, stop);
int ret = mp_machine_i2c_readfrom(self, addr, (uint8_t *)vstr.buf, vstr.len, stop);
if (ret < 0) {
mp_raise_OSError(-ret);
}
@ -452,7 +452,7 @@ STATIC mp_obj_t machine_i2c_readfrom(size_t n_args, const mp_obj_t *args) {
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_obj, 3, 4, machine_i2c_readfrom);
STATIC mp_obj_t machine_i2c_readfrom_into(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_int_t addr = mp_obj_get_int(args[1]);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE);
@ -466,7 +466,7 @@ STATIC mp_obj_t machine_i2c_readfrom_into(size_t n_args, const mp_obj_t *args) {
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_into_obj, 3, 4, machine_i2c_readfrom_into);
STATIC mp_obj_t machine_i2c_writeto(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_int_t addr = mp_obj_get_int(args[1]);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
@ -481,13 +481,13 @@ STATIC mp_obj_t machine_i2c_writeto(size_t n_args, const mp_obj_t *args) {
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_writeto_obj, 3, 4, machine_i2c_writeto);
STATIC mp_obj_t machine_i2c_writevto(size_t n_args, const mp_obj_t *args) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_int_t addr = mp_obj_get_int(args[1]);
// Get the list of data buffer(s) to write
size_t nitems;
const mp_obj_t *items;
mp_obj_get_array(args[2], &nitems, (mp_obj_t**)&items);
mp_obj_get_array(args[2], &nitems, (mp_obj_t **)&items);
// Get the stop argument
bool stop = (n_args == 3) ? true : mp_obj_is_true(args[3]);
@ -513,7 +513,7 @@ STATIC mp_obj_t machine_i2c_writevto(size_t n_args, const mp_obj_t *args) {
}
// Do the I2C transfer
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
int ret = i2c_p->transfer(self, addr, nbufs, bufs, stop ? MP_MACHINE_I2C_FLAG_STOP : 0);
mp_local_free(bufs);
@ -527,7 +527,7 @@ STATIC mp_obj_t machine_i2c_writevto(size_t n_args, const mp_obj_t *args) {
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_writevto_obj, 3, 4, machine_i2c_writevto);
STATIC int read_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, uint8_t *buf, size_t len) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
uint8_t memaddr_buf[4];
size_t memaddr_len = 0;
for (int16_t i = addrsize - 8; i >= 0; i -= 8) {
@ -543,7 +543,7 @@ STATIC int read_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t a
}
STATIC int write_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, const uint8_t *buf, size_t len) {
mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in);
// Create buffer with memory address
size_t memaddr_len = 0;
@ -555,11 +555,11 @@ STATIC int write_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t
// Create partial write buffers
mp_machine_i2c_buf_t bufs[2] = {
{.len = memaddr_len, .buf = memaddr_buf},
{.len = len, .buf = (uint8_t*)buf},
{.len = len, .buf = (uint8_t *)buf},
};
// Do I2C transfer
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol;
mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol;
return i2c_p->transfer(self, addr, 2, bufs, MP_MACHINE_I2C_FLAG_STOP);
}
@ -582,7 +582,7 @@ STATIC mp_obj_t machine_i2c_readfrom_mem(size_t n_args, const mp_obj_t *pos_args
// do the transfer
int ret = read_mem(pos_args[0], args[ARG_addr].u_int, args[ARG_memaddr].u_int,
args[ARG_addrsize].u_int, (uint8_t*)vstr.buf, vstr.len);
args[ARG_addrsize].u_int, (uint8_t *)vstr.buf, vstr.len);
if (ret < 0) {
mp_raise_OSError(-ret);
}
@ -658,7 +658,7 @@ STATIC const mp_rom_map_elem_t machine_i2c_locals_dict_table[] = {
MP_DEFINE_CONST_DICT(mp_machine_soft_i2c_locals_dict, machine_i2c_locals_dict_table);
int mp_machine_soft_i2c_read(mp_obj_base_t *self_in, uint8_t *dest, size_t len, bool nack) {
machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
while (len--) {
int ret = mp_hal_i2c_read_byte(self, dest++, nack && (len == 0));
if (ret != 0) {
@ -669,7 +669,7 @@ int mp_machine_soft_i2c_read(mp_obj_base_t *self_in, uint8_t *dest, size_t len,
}
int mp_machine_soft_i2c_write(mp_obj_base_t *self_in, const uint8_t *src, size_t len) {
machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in;
machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in;
int num_acks = 0;
while (len--) {
int ret = mp_hal_i2c_write_byte(self, *src++);
@ -685,8 +685,8 @@ int mp_machine_soft_i2c_write(mp_obj_base_t *self_in, const uint8_t *src, size_t
}
STATIC const mp_machine_i2c_p_t mp_machine_soft_i2c_p = {
.start = (int(*)(mp_obj_base_t*))mp_hal_i2c_start,
.stop = (int(*)(mp_obj_base_t*))mp_hal_i2c_stop,
.start = (int (*)(mp_obj_base_t *))mp_hal_i2c_start,
.stop = (int (*)(mp_obj_base_t *))mp_hal_i2c_stop,
.read = mp_machine_soft_i2c_read,
.write = mp_machine_soft_i2c_write,
.transfer = mp_machine_soft_i2c_transfer,
@ -697,7 +697,7 @@ const mp_obj_type_t machine_i2c_type = {
.name = MP_QSTR_I2C,
.make_new = machine_i2c_make_new,
.protocol = &mp_machine_soft_i2c_p,
.locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict,
.locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict,
};
#endif // MICROPY_PY_MACHINE_I2C

Wyświetl plik

@ -71,9 +71,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va
uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size);
uint32_t val;
switch (self->elem_size) {
case 1: val = (*(uint8_t*)addr); break;
case 2: val = (*(uint16_t*)addr); break;
default: val = (*(uint32_t*)addr); break;
case 1:
val = (*(uint8_t *)addr);
break;
case 2:
val = (*(uint16_t *)addr);
break;
default:
val = (*(uint32_t *)addr);
break;
}
return mp_obj_new_int(val);
} else {
@ -81,9 +87,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va
uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size);
uint32_t val = mp_obj_get_int_truncated(value);
switch (self->elem_size) {
case 1: (*(uint8_t*)addr) = val; break;
case 2: (*(uint16_t*)addr) = val; break;
default: (*(uint32_t*)addr) = val; break;
case 1:
(*(uint8_t *)addr) = val;
break;
case 2:
(*(uint16_t *)addr) = val;
break;
default:
(*(uint32_t *)addr) = val;
break;
}
return mp_const_none;
}

Wyświetl plik

@ -50,8 +50,8 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t
mp_pin_p_t *pin_p = NULL;
if (n_args > 0 && mp_obj_is_obj(args[0])) {
mp_obj_base_t *pin_base = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
pin_p = (mp_pin_p_t*)pin_base->type->protocol;
mp_obj_base_t *pin_base = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
pin_p = (mp_pin_p_t *)pin_base->type->protocol;
}
if (pin_p == NULL) {
@ -90,8 +90,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t
pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args);
mp_local_free(pin_args);
}
else
} else
#endif
// Otherwise there should be 1 or 2 args
{
@ -180,7 +179,7 @@ const mp_obj_type_t machine_signal_type = {
.make_new = signal_make_new,
.call = signal_call,
.protocol = &signal_pin_p,
.locals_dict = (void*)&signal_locals_dict,
.locals_dict = (void *)&signal_locals_dict,
};
#endif // MICROPY_PY_MACHINE

Wyświetl plik

@ -64,16 +64,16 @@ mp_obj_t mp_machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_
}
STATIC mp_obj_t machine_spi_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
spi_p->init(s, n_args - 1, args + 1, kw_args);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_spi_init_obj, 1, machine_spi_init);
STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) {
mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
if (spi_p->deinit != NULL) {
spi_p->deinit(s);
}
@ -82,8 +82,8 @@ STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_spi_deinit_obj, machine_spi_deinit);
STATIC void mp_machine_spi_transfer(mp_obj_t self, size_t len, const void *src, void *dest) {
mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol;
mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self);
mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol;
spi_p->transfer(s, len, src, dest);
}
@ -108,7 +108,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_readinto_obj, 2, 3, mp_machin
STATIC mp_obj_t mp_machine_spi_write(mp_obj_t self, mp_obj_t wr_buf) {
mp_buffer_info_t src;
mp_get_buffer_raise(wr_buf, &src, MP_BUFFER_READ);
mp_machine_spi_transfer(self, src.len, (const uint8_t*)src.buf, NULL);
mp_machine_spi_transfer(self, src.len, (const uint8_t *)src.buf, NULL);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_spi_write_obj, mp_machine_spi_write);
@ -223,7 +223,7 @@ STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n
}
STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in;
enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_sck, ARG_mosi, ARG_miso };
static const mp_arg_t allowed_args[] = {
@ -261,7 +261,7 @@ STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, cons
}
STATIC void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in;
mp_soft_spi_transfer(&self->spi, len, src, dest);
}
@ -277,7 +277,7 @@ const mp_obj_type_t mp_machine_soft_spi_type = {
.print = mp_machine_soft_spi_print,
.make_new = mp_machine_spi_make_new, // delegate to master constructor
.protocol = &mp_machine_soft_spi_p,
.locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict,
.locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
};
#endif // MICROPY_PY_MACHINE_SPI

Wyświetl plik

@ -107,7 +107,7 @@ STATIC mp_obj_t bluetooth_uuid_make_new(const mp_obj_type_t *type, size_t n_args
self->type = MP_BLUETOOTH_UUID_TYPE_128;
int uuid_i = 32;
for (int i = 0; i < uuid_bufinfo.len; i++) {
char c = ((char*)uuid_bufinfo.buf)[i];
char c = ((char *)uuid_bufinfo.buf)[i];
if (c == '-') {
continue;
}
@ -121,10 +121,10 @@ STATIC mp_obj_t bluetooth_uuid_make_new(const mp_obj_type_t *type, size_t n_args
}
if (uuid_i % 2 == 0) {
// lower nibble
self->data[uuid_i/2] |= c;
self->data[uuid_i / 2] |= c;
} else {
// upper nibble
self->data[uuid_i/2] = c << 4;
self->data[uuid_i / 2] = c << 4;
}
}
if (uuid_i > 0) {
@ -143,7 +143,8 @@ STATIC mp_obj_t bluetooth_uuid_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
// Use the QSTR hash function.
return MP_OBJ_NEW_SMALL_INT(qstr_compute_hash(self->data, self->type));
}
default: return MP_OBJ_NULL; // op not supported
default:
return MP_OBJ_NULL; // op not supported
}
}
@ -323,7 +324,7 @@ STATIC mp_obj_t bluetooth_ble_config(size_t n_args, const mp_obj_t *args, mp_map
// Get old buffer sizes and pointers
uint8_t *old_ringbuf_buf = self->ringbuf.buf;
size_t old_ringbuf_alloc = self->ringbuf.size;
uint8_t *old_irq_data_buf = (uint8_t*)self->irq_data_data.data;
uint8_t *old_irq_data_buf = (uint8_t *)self->irq_data_data.data;
size_t old_irq_data_alloc = self->irq_data_data_alloc;
// Atomically update the ringbuf and irq data
@ -355,7 +356,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bluetooth_ble_config_obj, 1, bluetooth_ble_con
STATIC mp_obj_t bluetooth_ble_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_handler, ARG_trigger };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_handler, MP_ARG_OBJ|MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_handler, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_trigger, MP_ARG_INT, {.u_int = MP_BLUETOOTH_IRQ_ALL} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
@ -367,7 +368,7 @@ STATIC mp_obj_t bluetooth_ble_irq(size_t n_args, const mp_obj_t *pos_args, mp_ma
// Update the callback.
MICROPY_PY_BLUETOOTH_ENTER
mp_obj_bluetooth_ble_t* o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth));
mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth));
o->irq_handler = callback;
o->irq_trigger = args[ARG_trigger].u_int;
MICROPY_PY_BLUETOOTH_EXIT
@ -426,7 +427,7 @@ STATIC int bluetooth_gatts_register_service(mp_obj_t uuid_in, mp_obj_t character
mp_obj_t characteristic_obj;
// Lists of characteristic uuids and flags.
mp_obj_bluetooth_uuid_t **characteristic_uuids = m_new(mp_obj_bluetooth_uuid_t*, len);
mp_obj_bluetooth_uuid_t **characteristic_uuids = m_new(mp_obj_bluetooth_uuid_t *, len);
uint8_t *characteristic_flags = m_new(uint8_t, len);
// Flattened list of descriptor uuids and flags. Grows (realloc) as more descriptors are encountered.
@ -471,7 +472,7 @@ STATIC int bluetooth_gatts_register_service(mp_obj_t uuid_in, mp_obj_t character
}
// Grow the flattened uuids and flags arrays with this many more descriptors.
descriptor_uuids = m_renew(mp_obj_bluetooth_uuid_t*, descriptor_uuids, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
descriptor_uuids = m_renew(mp_obj_bluetooth_uuid_t *, descriptor_uuids, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
descriptor_flags = m_renew(uint8_t, descriptor_flags, descriptor_index, descriptor_index + num_descriptors[characteristic_index]);
// Also grow the handles array.
@ -520,7 +521,7 @@ STATIC mp_obj_t bluetooth_ble_gatts_register_services(mp_obj_t self_in, mp_obj_t
mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(len, NULL));
uint16_t **handles = m_new0(uint16_t*, len);
uint16_t **handles = m_new0(uint16_t *, len);
size_t *num_handles = m_new0(size_t, len);
// TODO: Add a `append` kwarg (defaulting to False) to make this behavior optional.
@ -622,7 +623,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gap_disconnect_obj, bluetooth_ble
STATIC mp_obj_t bluetooth_ble_gatts_read(mp_obj_t self_in, mp_obj_t value_handle_in) {
size_t len = 0;
uint8_t* buf;
uint8_t *buf;
mp_bluetooth_gatts_read(mp_obj_get_int(value_handle_in), &buf, &len);
return mp_obj_new_bytes(buf, len);
}
@ -756,7 +757,7 @@ STATIC const mp_obj_type_t bluetooth_ble_type = {
{ &mp_type_type },
.name = MP_QSTR_BLE,
.make_new = bluetooth_ble_make_new,
.locals_dict = (void*)&bluetooth_ble_locals_dict,
.locals_dict = (void *)&bluetooth_ble_locals_dict,
};
STATIC const mp_rom_map_elem_t mp_module_bluetooth_globals_table[] = {
@ -772,14 +773,14 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_bluetooth_globals, mp_module_bluetooth_glo
const mp_obj_module_t mp_module_ubluetooth = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_bluetooth_globals,
.globals = (mp_obj_dict_t *)&mp_module_bluetooth_globals,
};
// Helpers
#include <stdio.h>
STATIC void ringbuf_extract(ringbuf_t* ringbuf, mp_obj_tuple_t *data_tuple, size_t n_u16, size_t n_u8, mp_obj_str_t *bytes_addr, size_t n_b, size_t n_i8, mp_obj_bluetooth_uuid_t *uuid, mp_obj_str_t *bytes_data) {
STATIC void ringbuf_extract(ringbuf_t *ringbuf, mp_obj_tuple_t *data_tuple, size_t n_u16, size_t n_u8, mp_obj_str_t *bytes_addr, size_t n_b, size_t n_i8, mp_obj_bluetooth_uuid_t *uuid, mp_obj_str_t *bytes_data) {
assert(ringbuf_avail(ringbuf) >= n_u16 * 2 + n_u8 + (bytes_addr ? 6 : 0) + n_b + n_i8 + (uuid ? 1 : 0) + (bytes_data ? 1 : 0));
int j = 0;
@ -793,7 +794,7 @@ STATIC void ringbuf_extract(ringbuf_t* ringbuf, mp_obj_tuple_t *data_tuple, size
bytes_addr->len = 6;
for (int i = 0; i < bytes_addr->len; ++i) {
// cast away const, this is actually bt->irq_addr_bytes.
((uint8_t*)bytes_addr->data)[i] = ringbuf_get(ringbuf);
((uint8_t *)bytes_addr->data)[i] = ringbuf_get(ringbuf);
}
data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_addr);
}
@ -815,7 +816,7 @@ STATIC void ringbuf_extract(ringbuf_t* ringbuf, mp_obj_tuple_t *data_tuple, size
bytes_data->len = ringbuf_get(ringbuf);
for (int i = 0; i < bytes_data->len; ++i) {
// cast away const, this is actually bt->irq_data_bytes.
((uint8_t*)bytes_data->data)[i] = ringbuf_get(ringbuf);
((uint8_t *)bytes_data->data)[i] = ringbuf_get(ringbuf);
}
data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_data);
}

Wyświetl plik

@ -47,36 +47,36 @@
#define DEBUG_EVENT_printf(...) //printf(__VA_ARGS__)
STATIC int8_t ble_hs_err_to_errno_table[] = {
[BLE_HS_EAGAIN] = MP_EAGAIN,
[BLE_HS_EALREADY] = MP_EALREADY,
[BLE_HS_EINVAL] = MP_EINVAL,
[BLE_HS_EMSGSIZE] = MP_EIO,
[BLE_HS_ENOENT] = MP_ENOENT,
[BLE_HS_ENOMEM] = MP_ENOMEM,
[BLE_HS_ENOTCONN] = MP_ENOTCONN,
[BLE_HS_ENOTSUP] = MP_EOPNOTSUPP,
[BLE_HS_EAPP] = MP_EIO,
[BLE_HS_EBADDATA] = MP_EIO,
[BLE_HS_EOS] = MP_EIO,
[BLE_HS_ECONTROLLER] = MP_EIO,
[BLE_HS_ETIMEOUT] = MP_ETIMEDOUT,
[BLE_HS_EDONE] = MP_EIO, // TODO: Maybe should be MP_EISCONN (connect uses this for "already connected").
[BLE_HS_EBUSY] = MP_EBUSY,
[BLE_HS_EREJECT] = MP_EIO,
[BLE_HS_EUNKNOWN] = MP_EIO,
[BLE_HS_EROLE] = MP_EIO,
[BLE_HS_ETIMEOUT_HCI] = MP_EIO,
[BLE_HS_ENOMEM_EVT] = MP_EIO,
[BLE_HS_ENOADDR] = MP_EIO,
[BLE_HS_ENOTSYNCED] = MP_EIO,
[BLE_HS_EAUTHEN] = MP_EIO,
[BLE_HS_EAUTHOR] = MP_EIO,
[BLE_HS_EENCRYPT] = MP_EIO,
[BLE_HS_EENCRYPT_KEY_SZ] = MP_EIO,
[BLE_HS_ESTORE_CAP] = MP_EIO,
[BLE_HS_ESTORE_FAIL] = MP_EIO,
[BLE_HS_EPREEMPTED] = MP_EIO,
[BLE_HS_EDISABLED] = MP_EIO,
[BLE_HS_EAGAIN] = MP_EAGAIN,
[BLE_HS_EALREADY] = MP_EALREADY,
[BLE_HS_EINVAL] = MP_EINVAL,
[BLE_HS_EMSGSIZE] = MP_EIO,
[BLE_HS_ENOENT] = MP_ENOENT,
[BLE_HS_ENOMEM] = MP_ENOMEM,
[BLE_HS_ENOTCONN] = MP_ENOTCONN,
[BLE_HS_ENOTSUP] = MP_EOPNOTSUPP,
[BLE_HS_EAPP] = MP_EIO,
[BLE_HS_EBADDATA] = MP_EIO,
[BLE_HS_EOS] = MP_EIO,
[BLE_HS_ECONTROLLER] = MP_EIO,
[BLE_HS_ETIMEOUT] = MP_ETIMEDOUT,
[BLE_HS_EDONE] = MP_EIO, // TODO: Maybe should be MP_EISCONN (connect uses this for "already connected").
[BLE_HS_EBUSY] = MP_EBUSY,
[BLE_HS_EREJECT] = MP_EIO,
[BLE_HS_EUNKNOWN] = MP_EIO,
[BLE_HS_EROLE] = MP_EIO,
[BLE_HS_ETIMEOUT_HCI] = MP_EIO,
[BLE_HS_ENOMEM_EVT] = MP_EIO,
[BLE_HS_ENOADDR] = MP_EIO,
[BLE_HS_ENOTSYNCED] = MP_EIO,
[BLE_HS_EAUTHEN] = MP_EIO,
[BLE_HS_EAUTHOR] = MP_EIO,
[BLE_HS_EENCRYPT] = MP_EIO,
[BLE_HS_EENCRYPT_KEY_SZ] = MP_EIO,
[BLE_HS_ESTORE_CAP] = MP_EIO,
[BLE_HS_ESTORE_FAIL] = MP_EIO,
[BLE_HS_EPREEMPTED] = MP_EIO,
[BLE_HS_EDISABLED] = MP_EIO,
};
STATIC int ble_hs_err_to_errno(int err) {
@ -88,22 +88,22 @@ STATIC int ble_hs_err_to_errno(int err) {
}
// Note: modbluetooth UUIDs store their data in LE.
STATIC ble_uuid_t* create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid) {
STATIC ble_uuid_t *create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid) {
if (uuid->type == MP_BLUETOOTH_UUID_TYPE_16) {
ble_uuid16_t *result = m_new(ble_uuid16_t, 1);
result->u.type = BLE_UUID_TYPE_16;
result->value = (uuid->data[1] << 8) | uuid->data[0];
return (ble_uuid_t*)result;
return (ble_uuid_t *)result;
} else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_32) {
ble_uuid32_t *result = m_new(ble_uuid32_t, 1);
result->u.type = BLE_UUID_TYPE_32;
result->value = (uuid->data[1] << 24) | (uuid->data[1] << 16) | (uuid->data[1] << 8) | uuid->data[0];
return (ble_uuid_t*)result;
return (ble_uuid_t *)result;
} else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_128) {
ble_uuid128_t *result = m_new(ble_uuid128_t, 1);
result->u.type = BLE_UUID_TYPE_128;
memcpy(result->value, uuid->data, 16);
return (ble_uuid_t*)result;
return (ble_uuid_t *)result;
} else {
return NULL;
}
@ -139,7 +139,7 @@ STATIC mp_obj_bluetooth_uuid_t create_mp_uuid(const ble_uuid_any_t *uuid) {
// modbluetooth (and the layers above it) work in BE for addresses, Nimble works in LE.
STATIC void reverse_addr_byte_order(uint8_t *addr_out, const uint8_t *addr_in) {
for (int i = 0; i < 6; ++i) {
addr_out[i] = addr_in[5-i];
addr_out[i] = addr_in[5 - i];
}
}
@ -196,7 +196,7 @@ STATIC void sync_cb(void) {
}
if (MP_BLUETOOTH_MAX_ATTR_SIZE > 20) {
rc = ble_att_set_preferred_mtu(MP_BLUETOOTH_MAX_ATTR_SIZE+3);
rc = ble_att_set_preferred_mtu(MP_BLUETOOTH_MAX_ATTR_SIZE + 3);
assert(rc == 0);
}
@ -244,7 +244,7 @@ STATIC void gatts_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg) {
create_gatts_db_entry(ctxt->dsc.handle);
// Unlike characteristics, we have to manually provide a way to get the handle back to the register method.
*((uint16_t*)ctxt->dsc.dsc_def->arg) = ctxt->dsc.handle;
*((uint16_t *)ctxt->dsc.dsc_def->arg) = ctxt->dsc.handle;
break;
default:
@ -622,7 +622,7 @@ STATIC void gattc_on_data_available(uint16_t event, uint16_t conn_handle, uint16
len = mp_bluetooth_gattc_on_data_available_start(event, conn_handle, value_handle, len);
while (len > 0 && om != NULL) {
size_t n = MIN(om->om_len, len);
mp_bluetooth_gattc_on_data_available_chunk(OS_MBUF_DATA(om, const uint8_t*), n);
mp_bluetooth_gattc_on_data_available_chunk(OS_MBUF_DATA(om, const uint8_t *), n);
len -= n;
om = SLIST_NEXT(om, om_next);
}
@ -642,7 +642,7 @@ STATIC int gap_scan_cb(struct ble_gap_event *event, void *arg) {
return 0;
}
if (event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND || event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_NONCONN_IND) {
if (event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND || event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_NONCONN_IND) {
bool connectable = event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND;
uint8_t addr[6];
reverse_addr_byte_order(addr, event->disc.addr.val);

Wyświetl plik

@ -57,9 +57,9 @@ STATIC const mp_obj_type_t btree_type;
#endif
#define CHECK_ERROR(res) \
if (res == RET_ERROR) { \
mp_raise_OSError(errno); \
}
if (res == RET_ERROR) { \
mp_raise_OSError(errno); \
}
void __dbpanic(DB *db) {
mp_printf(&mp_plat_print, "__dbpanic(%p)\n", db);
@ -97,8 +97,8 @@ STATIC mp_obj_t btree_put(size_t n_args, const mp_obj_t *args) {
(void)n_args;
mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]);
DBT key, val;
key.data = (void*)mp_obj_str_get_data(args[1], &key.size);
val.data = (void*)mp_obj_str_get_data(args[2], &val.size);
key.data = (void *)mp_obj_str_get_data(args[1], &key.size);
val.data = (void *)mp_obj_str_get_data(args[2], &val.size);
return MP_OBJ_NEW_SMALL_INT(__bt_put(self->db, &key, &val, 0));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put);
@ -106,7 +106,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put);
STATIC mp_obj_t btree_get(size_t n_args, const mp_obj_t *args) {
mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]);
DBT key, val;
key.data = (void*)mp_obj_str_get_data(args[1], &key.size);
key.data = (void *)mp_obj_str_get_data(args[1], &key.size);
int res = __bt_get(self->db, &key, &val, 0);
if (res == RET_SPECIAL) {
if (n_args > 2) {
@ -125,7 +125,7 @@ STATIC mp_obj_t btree_seq(size_t n_args, const mp_obj_t *args) {
int flags = MP_OBJ_SMALL_INT_VALUE(args[1]);
DBT key, val;
if (n_args > 2) {
key.data = (void*)mp_obj_str_get_data(args[2], &key.size);
key.data = (void *)mp_obj_str_get_data(args[2], &key.size);
}
int res = __bt_seq(self->db, &key, &val, flags);
@ -200,7 +200,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) {
if (self->start_key != MP_OBJ_NULL) {
int flags = R_FIRST;
if (self->start_key != mp_const_none) {
key.data = (void*)mp_obj_str_get_data(self->start_key, &key.size);
key.data = (void *)mp_obj_str_get_data(self->start_key, &key.size);
flags = R_CURSOR;
} else if (desc) {
flags = R_LAST;
@ -218,7 +218,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) {
if (self->end_key != mp_const_none) {
DBT end_key;
end_key.data = (void*)mp_obj_str_get_data(self->end_key, &end_key.size);
end_key.data = (void *)mp_obj_str_get_data(self->end_key, &end_key.size);
BTREE *t = self->db->internal;
int cmp = t->bt_cmp(&key, &end_key);
if (desc) {
@ -253,7 +253,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
if (value == MP_OBJ_NULL) {
// delete
DBT key;
key.data = (void*)mp_obj_str_get_data(index, &key.size);
key.data = (void *)mp_obj_str_get_data(index, &key.size);
int res = __bt_delete(self->db, &key, 0);
if (res == RET_SPECIAL) {
mp_raise_type(&mp_type_KeyError);
@ -263,7 +263,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
} else if (value == MP_OBJ_SENTINEL) {
// load
DBT key, val;
key.data = (void*)mp_obj_str_get_data(index, &key.size);
key.data = (void *)mp_obj_str_get_data(index, &key.size);
int res = __bt_get(self->db, &key, &val, 0);
if (res == RET_SPECIAL) {
mp_raise_type(&mp_type_KeyError);
@ -273,8 +273,8 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
} else {
// store
DBT key, val;
key.data = (void*)mp_obj_str_get_data(index, &key.size);
val.data = (void*)mp_obj_str_get_data(value, &val.size);
key.data = (void *)mp_obj_str_get_data(index, &key.size);
val.data = (void *)mp_obj_str_get_data(value, &val.size);
int res = __bt_put(self->db, &key, &val, 0);
CHECK_ERROR(res);
return mp_const_none;
@ -286,7 +286,7 @@ STATIC mp_obj_t btree_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs
switch (op) {
case MP_BINARY_OP_CONTAINS: {
DBT key, val;
key.data = (void*)mp_obj_str_get_data(rhs_in, &key.size);
key.data = (void *)mp_obj_str_get_data(rhs_in, &key.size);
int res = __bt_get(self->db, &key, &val, 0);
CHECK_ERROR(res);
return mp_obj_new_bool(res != RET_SPECIAL);
@ -320,7 +320,7 @@ STATIC const mp_obj_type_t btree_type = {
.iternext = btree_iternext,
.binary_op = btree_binary_op,
.subscr = btree_subscr,
.locals_dict = (void*)&btree_locals_dict,
.locals_dict = (void *)&btree_locals_dict,
};
#endif
@ -350,14 +350,14 @@ STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t
mp_arg_val_t minkeypage;
} args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
BTREEINFO openinfo = {0};
openinfo.flags = args.flags.u_int;
openinfo.cachesize = args.cachesize.u_int;
openinfo.psize = args.pagesize.u_int;
openinfo.minkeypage = args.minkeypage.u_int;
DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/0);
DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0);
if (db == NULL) {
mp_raise_OSError(errno);
}
@ -376,7 +376,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_btree_globals, mp_module_btree_globals_tab
const mp_obj_module_t mp_module_btree = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_btree_globals,
.globals = (mp_obj_dict_t *)&mp_module_btree_globals,
};
#endif

Wyświetl plik

@ -45,8 +45,8 @@ typedef struct _mp_obj_framebuf_t {
STATIC const mp_obj_type_t mp_type_framebuf;
#endif
typedef void (*setpixel_t)(const mp_obj_framebuf_t*, int, int, uint32_t);
typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t*, int, int);
typedef void (*setpixel_t)(const mp_obj_framebuf_t *, int, int, uint32_t);
typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t *, int, int);
typedef void (*fill_rect_t)(const mp_obj_framebuf_t *, int, int, int, int, uint32_t);
typedef struct _mp_framebuf_p_t {
@ -69,20 +69,20 @@ typedef struct _mp_framebuf_p_t {
STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
size_t index = (x + y * fb->stride) >> 3;
int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07);
((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
}
STATIC uint32_t mono_horiz_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
size_t index = (x + y * fb->stride) >> 3;
int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07);
return (((uint8_t*)fb->buf)[index] >> (offset)) & 0x01;
return (((uint8_t *)fb->buf)[index] >> (offset)) & 0x01;
}
STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
int reverse = fb->format == FRAMEBUF_MHMSB;
int advance = fb->stride >> 3;
while (w--) {
uint8_t *b = &((uint8_t*)fb->buf)[(x >> 3) + y * advance];
uint8_t *b = &((uint8_t *)fb->buf)[(x >> 3) + y * advance];
int offset = reverse ? x & 7 : 7 - (x & 7);
for (int hh = h; hh; --hh) {
*b = (*b & ~(0x01 << offset)) | ((col != 0) << offset);
@ -97,16 +97,16 @@ STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int
STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
size_t index = (y >> 3) * fb->stride + x;
uint8_t offset = y & 0x07;
((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset);
}
STATIC uint32_t mvlsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
return (((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01;
return (((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01;
}
STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
while (h--) {
uint8_t *b = &((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x];
uint8_t *b = &((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x];
uint8_t offset = y & 0x07;
for (int ww = w; ww; --ww) {
*b = (*b & ~(0x01 << offset)) | ((col != 0) << offset);
@ -119,15 +119,15 @@ STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, in
// Functions for RGB565 format
STATIC void rgb565_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
((uint16_t*)fb->buf)[x + y * fb->stride] = col;
((uint16_t *)fb->buf)[x + y * fb->stride] = col;
}
STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
return ((uint16_t*)fb->buf)[x + y * fb->stride];
return ((uint16_t *)fb->buf)[x + y * fb->stride];
}
STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
uint16_t *b = &((uint16_t*)fb->buf)[x + y * fb->stride];
uint16_t *b = &((uint16_t *)fb->buf)[x + y * fb->stride];
while (h--) {
for (int ww = w; ww; --ww) {
*b++ = col;
@ -139,7 +139,7 @@ STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, i
// Functions for GS2_HMSB format
STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2];
uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2];
uint8_t shift = (x & 0x3) << 1;
uint8_t mask = 0x3 << shift;
uint8_t color = (col & 0x3) << shift;
@ -147,14 +147,14 @@ STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_
}
STATIC uint32_t gs2_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
uint8_t pixel = ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2];
uint8_t pixel = ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2];
uint8_t shift = (x & 0x3) << 1;
return (pixel >> shift) & 0x3;
}
STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
for (int xx=x; xx < x+w; xx++) {
for (int yy=y; yy < y+h; yy++) {
for (int xx = x; xx < x + w; xx++) {
for (int yy = y; yy < y + h; yy++) {
gs2_hmsb_setpixel(fb, xx, yy, col);
}
}
@ -163,7 +163,7 @@ STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w,
// Functions for GS4_HMSB format
STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1];
uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1];
if (x % 2) {
*pixel = ((uint8_t)col & 0x0f) | (*pixel & 0xf0);
@ -174,15 +174,15 @@ STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_
STATIC uint32_t gs4_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
if (x % 2) {
return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f;
return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f;
}
return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] >> 4;
return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] >> 4;
}
STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
col &= 0x0f;
uint8_t *pixel_pair = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1];
uint8_t *pixel_pair = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1];
uint8_t col_shifted_left = col << 4;
uint8_t col_pixel_pair = col_shifted_left | col;
int pixel_count_till_next_line = (fb->stride - w) >> 1;
@ -214,16 +214,16 @@ STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w,
// Functions for GS8 format
STATIC void gs8_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) {
uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)];
uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)];
*pixel = col & 0xff;
}
STATIC uint32_t gs8_getpixel(const mp_obj_framebuf_t *fb, int x, int y) {
return ((uint8_t*)fb->buf)[(x + y * fb->stride)];
return ((uint8_t *)fb->buf)[(x + y * fb->stride)];
}
STATIC void gs8_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) {
uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)];
uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)];
while (h--) {
memset(pixel, col, w);
pixel += fb->stride;
@ -397,9 +397,9 @@ STATIC mp_obj_t framebuf_rect(size_t n_args, const mp_obj_t *args) {
mp_int_t col = mp_obj_get_int(args[5]);
fill_rect(self, x, y, w, 1, col);
fill_rect(self, x, y + h- 1, w, 1, col);
fill_rect(self, x, y + h - 1, w, 1, col);
fill_rect(self, x, y, 1, h, col);
fill_rect(self, x + w- 1, y, 1, h, col);
fill_rect(self, x + w - 1, y, 1, h, col);
return mp_const_none;
}
@ -436,9 +436,15 @@ STATIC mp_obj_t framebuf_line(size_t n_args, const mp_obj_t *args) {
bool steep;
if (dy > dx) {
mp_int_t temp;
temp = x1; x1 = y1; y1 = temp;
temp = dx; dx = dy; dy = temp;
temp = sx; sx = sy; sy = temp;
temp = x1;
x1 = y1;
y1 = temp;
temp = dx;
dx = dy;
dy = temp;
temp = sx;
sx = sy;
sy = temp;
steep = true;
} else {
steep = false;
@ -491,7 +497,7 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) {
(y >= self->height) ||
(-x >= source->width) ||
(-y >= source->height)
) {
) {
// Out of bounds, no-op.
return mp_const_none;
}
@ -565,7 +571,7 @@ STATIC mp_obj_t framebuf_text(size_t n_args, const mp_obj_t *args) {
// loop over chars
for (; *str; ++str) {
// get char and make sure its in range of font
int chr = *(uint8_t*)str;
int chr = *(uint8_t *)str;
if (chr < 32 || chr > 127) {
chr = 127;
}
@ -609,7 +615,7 @@ STATIC const mp_obj_type_t mp_type_framebuf = {
.name = MP_QSTR_FrameBuffer,
.make_new = framebuf_make_new,
.buffer_p = { .get_buffer = framebuf_get_buffer },
.locals_dict = (mp_obj_dict_t*)&framebuf_locals_dict,
.locals_dict = (mp_obj_dict_t *)&framebuf_locals_dict,
};
#endif
@ -654,7 +660,7 @@ STATIC MP_DEFINE_CONST_DICT(framebuf_module_globals, framebuf_module_globals_tab
const mp_obj_module_t mp_module_framebuf = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&framebuf_module_globals,
.globals = (mp_obj_dict_t *)&framebuf_module_globals,
};
#endif

Wyświetl plik

@ -103,7 +103,7 @@ void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg);
void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg);
STATIC void slip_lwip_poll(void *netif) {
slipif_poll((struct netif*)netif);
slipif_poll((struct netif *)netif);
}
STATIC const mp_obj_type_t lwip_slip_type;
@ -152,7 +152,7 @@ STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw,
struct netif *n = &lwip_slip_obj.lwip_netif;
if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) {
mp_raise_ValueError("out of memory");
mp_raise_ValueError("out of memory");
}
netif_set_up(n);
netif_set_default(n);
@ -178,7 +178,7 @@ STATIC const mp_obj_type_t lwip_slip_type = {
{ &mp_type_type },
.name = MP_QSTR_slip,
.make_new = lwip_slip_make_new,
.locals_dict = (mp_obj_dict_t*)&lwip_slip_locals_dict,
.locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict,
};
#endif // MICROPY_PY_LWIP_SLIP
@ -190,7 +190,7 @@ STATIC const mp_obj_type_t lwip_slip_type = {
// lwIP 2 changed LWIP_VERSION and it can no longer be used in macros,
// so we define our own equivalent version that can.
#define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \
| LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC)
| LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC)
// Extension to lwIP error codes
#define _ERR_BADF -16
@ -313,11 +313,11 @@ typedef struct _lwip_socket_obj_t {
} lwip_socket_obj_t;
static inline void poll_sockets(void) {
#ifdef MICROPY_EVENT_POLL_HOOK
#ifdef MICROPY_EVENT_POLL_HOOK
MICROPY_EVENT_POLL_HOOK;
#else
#else
mp_hal_delay_ms(1);
#endif
#endif
}
STATIC struct tcp_pcb *volatile *lwip_socket_incoming_array(lwip_socket_obj_t *socket) {
@ -370,7 +370,7 @@ STATIC u8_t _lwip_raw_incoming(void *arg, struct raw_pcb *pcb, struct pbuf *p, i
STATIC u8_t _lwip_raw_incoming(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr)
#endif
{
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
if (socket->incoming.pbuf != NULL) {
pbuf_free(p);
@ -390,7 +390,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p,
STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
#endif
{
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
if (socket->incoming.pbuf != NULL) {
// That's why they call it "unreliable". No room in the inn, drop the packet.
@ -404,7 +404,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p,
// Callback for general tcp errors.
STATIC void _lwip_tcp_error(void *arg, err_t err) {
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
// Free any incoming buffers or connections that are stored
lwip_socket_free_incoming(socket);
@ -416,7 +416,7 @@ STATIC void _lwip_tcp_error(void *arg, err_t err) {
// Callback for tcp connection requests. Error code err is unused. (See tcp.h)
STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) {
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
socket->state = STATE_CONNECTED;
return ERR_OK;
@ -425,15 +425,15 @@ STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) {
// Handle errors (eg connection aborted) on TCP PCBs that have been put on the
// accept queue but are not yet actually accepted.
STATIC void _lwip_tcp_err_unaccepted(void *arg, err_t err) {
struct tcp_pcb *pcb = (struct tcp_pcb*)arg;
struct tcp_pcb *pcb = (struct tcp_pcb *)arg;
// The ->connected entry is repurposed to store the parent socket; this is safe
// because it's only ever used by lwIP if tcp_connect is called on the TCP PCB.
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)pcb->connected;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)pcb->connected;
// Array is not volatile because thiss callback is executed within the lwIP context
uint8_t alloc = socket->incoming.connection.alloc;
struct tcp_pcb **tcp_array = (struct tcp_pcb**)lwip_socket_incoming_array(socket);
struct tcp_pcb **tcp_array = (struct tcp_pcb **)lwip_socket_incoming_array(socket);
// Search for PCB on the accept queue of the parent socket
struct tcp_pcb **shift_down = NULL;
@ -475,7 +475,7 @@ STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) {
return ERR_OK;
}
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
tcp_recv(newpcb, _lwip_tcp_recv_unaccepted);
// Search for an empty slot to store the new connection
@ -494,7 +494,7 @@ STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) {
// have a chance to take it off the accept queue.
// The ->connected entry is repurposed to store the parent socket; this is safe
// because it's only ever used by lwIP if tcp_connect is called on the TCP PCB.
newpcb->connected = (void*)socket;
newpcb->connected = (void *)socket;
tcp_arg(newpcb, newpcb);
tcp_err(newpcb, _lwip_tcp_err_unaccepted);
@ -507,7 +507,7 @@ STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) {
// Callback for inbound tcp packets.
STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) {
lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg;
lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg;
if (p == NULL) {
// Other side has closed connection.
@ -600,7 +600,9 @@ STATIC mp_uint_t lwip_raw_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_u
if (socket->timeout != -1) {
for (mp_uint_t retries = socket->timeout / 100; retries--;) {
mp_hal_delay_ms(100);
if (socket->incoming.pbuf != NULL) break;
if (socket->incoming.pbuf != NULL) {
break;
}
}
if (socket->incoming.pbuf == NULL) {
*_errno = MP_ETIMEDOUT;
@ -633,20 +635,20 @@ STATIC mp_uint_t lwip_raw_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_u
// For use in stream virtual methods
#define STREAM_ERROR_CHECK(socket) \
if (socket->state < 0) { \
*_errno = error_lookup_table[-socket->state]; \
return MP_STREAM_ERROR; \
} \
assert(socket->pcb.tcp);
if (socket->state < 0) { \
*_errno = error_lookup_table[-socket->state]; \
return MP_STREAM_ERROR; \
} \
assert(socket->pcb.tcp);
// Version of above for use when lock is held
#define STREAM_ERROR_CHECK_WITH_LOCK(socket) \
if (socket->state < 0) { \
*_errno = error_lookup_table[-socket->state]; \
MICROPY_PY_LWIP_EXIT \
return MP_STREAM_ERROR; \
} \
assert(socket->pcb.tcp);
if (socket->state < 0) { \
*_errno = error_lookup_table[-socket->state]; \
MICROPY_PY_LWIP_EXIT \
return MP_STREAM_ERROR; \
} \
assert(socket->pcb.tcp);
// Helper function for send/sendto to handle TCP packets
@ -772,7 +774,7 @@ STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_
len = remaining;
}
memcpy(buf, (byte*)p->payload + socket->recv_offset, len);
memcpy(buf, (byte *)p->payload + socket->recv_offset, len);
remaining -= len;
if (remaining == 0) {
@ -837,7 +839,8 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s
break;
}
#endif
default: mp_raise_OSError(MP_EINVAL);
default:
mp_raise_OSError(MP_EINVAL);
}
if (socket->pcb.tcp == NULL) {
@ -847,7 +850,7 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s
switch (socket->type) {
case MOD_NETWORK_SOCK_STREAM: {
// Register the socket object as our callback argument.
tcp_arg(socket->pcb.tcp, (void*)socket);
tcp_arg(socket->pcb.tcp, (void *)socket);
// Register our error callback.
tcp_err(socket->pcb.tcp, _lwip_tcp_error);
break;
@ -855,14 +858,14 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s
case MOD_NETWORK_SOCK_DGRAM: {
// Register our receive callback now. Since UDP sockets don't require binding or connection
// before use, there's no other good time to do it.
udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void*)socket);
udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket);
break;
}
#if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW: {
// Register our receive callback now. Since raw sockets don't require binding or connection
// before use, there's no other good time to do it.
raw_recv(socket->pcb.raw, _lwip_raw_incoming, (void*)socket);
raw_recv(socket->pcb.raw, _lwip_raw_incoming, (void *)socket);
break;
}
#endif
@ -926,7 +929,7 @@ STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) {
socket->incoming.connection.tcp.item = NULL;
} else {
socket->incoming.connection.alloc = backlog;
socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb*, backlog);
socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb *, backlog);
}
socket->incoming.connection.iget = 0;
socket->incoming.connection.iput = 0;
@ -1010,7 +1013,7 @@ STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) {
socket2->state = STATE_CONNECTED;
socket2->recv_offset = 0;
socket2->callback = MP_OBJ_NULL;
tcp_arg(socket2->pcb.tcp, (void*)socket2);
tcp_arg(socket2->pcb.tcp, (void *)socket2);
tcp_err(socket2->pcb.tcp, _lwip_tcp_error);
tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv);
@ -1073,7 +1076,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
if (socket->timeout != -1) {
for (mp_uint_t retries = socket->timeout / 100; retries--;) {
mp_hal_delay_ms(100);
if (socket->state != STATE_CONNECTING) break;
if (socket->state != STATE_CONNECTING) {
break;
}
}
if (socket->state == STATE_CONNECTING) {
mp_raise_OSError(MP_EINPROGRESS);
@ -1084,9 +1089,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
}
}
if (socket->state == STATE_CONNECTED) {
err = ERR_OK;
err = ERR_OK;
} else {
err = socket->state;
err = socket->state;
}
break;
}
@ -1162,14 +1167,14 @@ STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) {
mp_uint_t ret = 0;
switch (socket->type) {
case MOD_NETWORK_SOCK_STREAM: {
ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno);
ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno);
break;
}
case MOD_NETWORK_SOCK_DGRAM:
#if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW:
#endif
ret = lwip_raw_udp_receive(socket, (byte*)vstr.buf, len, NULL, NULL, &_errno);
ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno);
break;
}
if (ret == -1) {
@ -1234,14 +1239,14 @@ STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) {
case MOD_NETWORK_SOCK_STREAM: {
memcpy(ip, &socket->peer, sizeof(socket->peer));
port = (mp_uint_t) socket->peer_port;
ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno);
ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno);
break;
}
case MOD_NETWORK_SOCK_DGRAM:
#if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW:
#endif
ret = lwip_raw_udp_receive(socket, (byte*)vstr.buf, len, ip, &port, &_errno);
ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno);
break;
}
if (ret == -1) {
@ -1289,7 +1294,7 @@ STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) {
mp_raise_OSError(_errno);
}
bufinfo.len -= ret;
bufinfo.buf = (char*)bufinfo.buf + ret;
bufinfo.buf = (char *)bufinfo.buf + ret;
}
break;
}
@ -1367,7 +1372,7 @@ STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) {
}
// POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa
err_t err = igmp_joingroup((ip_addr_t*)bufinfo.buf + 1, bufinfo.buf);
err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf);
if (err != ERR_OK) {
mp_raise_OSError(error_lookup_table[-err]);
}
@ -1514,9 +1519,13 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_
}
break;
}
case MOD_NETWORK_SOCK_DGRAM: udp_remove(socket->pcb.udp); break;
case MOD_NETWORK_SOCK_DGRAM:
udp_remove(socket->pcb.udp);
break;
#if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break;
case MOD_NETWORK_SOCK_RAW:
raw_remove(socket->pcb.raw);
break;
#endif
}
@ -1570,7 +1579,7 @@ STATIC const mp_obj_type_t lwip_socket_type = {
.print = lwip_socket_print,
.make_new = lwip_socket_make_new,
.protocol = &lwip_socket_stream_p,
.locals_dict = (mp_obj_dict_t*)&lwip_socket_locals_dict,
.locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict,
};
/******************************************************************************/
@ -1590,18 +1599,18 @@ void sys_arch_unprotect(sys_prot_t state) {
// itself a "list" but isn't; we only support a single interface.
typedef struct nic_poll {
void (* poll)(void *arg);
void (*poll)(void *arg);
void *poll_arg;
} nic_poll_t;
STATIC nic_poll_t lwip_poll_list;
void mod_lwip_register_poll(void (* poll)(void *arg), void *poll_arg) {
void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) {
lwip_poll_list.poll = poll;
lwip_poll_list.poll_arg = poll_arg;
}
void mod_lwip_deregister_poll(void (* poll)(void *arg), void *poll_arg) {
void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) {
lwip_poll_list.poll = NULL;
}
@ -1668,9 +1677,9 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) {
}
}
if (!((family == 0 || family == MOD_NETWORK_AF_INET)
&& (type == 0 || type == MOD_NETWORK_SOCK_STREAM)
&& proto == 0
&& flags == 0)) {
&& (type == 0 || type == MOD_NETWORK_SOCK_STREAM)
&& proto == 0
&& flags == 0)) {
mp_warning(MP_WARN_CAT(RuntimeWarning), "unsupported getaddrinfo constraints");
}
}
@ -1679,7 +1688,7 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) {
state.status = 0;
MICROPY_PY_LWIP_ENTER
err_t ret = dns_gethostbyname(host, (ip_addr_t*)&state.ipaddr, lwip_getaddrinfo_cb, &state);
err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state);
MICROPY_PY_LWIP_EXIT
switch (ret) {
@ -1707,8 +1716,8 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) {
tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM);
tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0);
tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_);
tuple->items[4] = netutils_format_inet_addr((uint8_t*)&state.ipaddr, port, NETUTILS_BIG);
return mp_obj_new_list(1, (mp_obj_t*)&tuple);
tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG);
return mp_obj_new_list(1, (mp_obj_t *)&tuple);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo);
@ -1730,9 +1739,9 @@ STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) },
// objects
{ MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) },
#ifdef MICROPY_PY_LWIP_SLIP
#ifdef MICROPY_PY_LWIP_SLIP
{ MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) },
#endif
#endif
// class constants
{ MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) },
{ MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) },
@ -1754,7 +1763,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table
const mp_obj_module_t mp_module_lwip = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_lwip_globals,
.globals = (mp_obj_dict_t *)&mp_module_lwip_globals,
};
#endif // MICROPY_PY_LWIP

Wyświetl plik

@ -126,7 +126,7 @@ STATIC mp_obj_t onewire_crc8(mp_obj_t data) {
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
uint8_t crc = 0;
for (size_t i = 0; i < bufinfo.len; ++i) {
uint8_t byte = ((uint8_t*)bufinfo.buf)[i];
uint8_t byte = ((uint8_t *)bufinfo.buf)[i];
for (int b = 0; b < 8; ++b) {
uint8_t fb_bit = (crc ^ byte) & 0x01;
if (fb_bit == 0x01) {
@ -158,5 +158,5 @@ STATIC MP_DEFINE_CONST_DICT(onewire_module_globals, onewire_module_globals_table
const mp_obj_module_t mp_module_onewire = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&onewire_module_globals,
.globals = (mp_obj_dict_t *)&onewire_module_globals,
};

Wyświetl plik

@ -53,7 +53,7 @@ mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) {
sep = mp_obj_str_get_str(args[1]);
}
vstr_init_len(&vstr, out_len);
byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
for (mp_uint_t i = bufinfo.len; i--;) {
byte d = (*in >> 4);
if (d > 9) {
@ -82,7 +82,7 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) {
}
vstr_t vstr;
vstr_init_len(&vstr, bufinfo.len / 2);
byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
byte hex_byte = 0;
for (mp_uint_t i = bufinfo.len; i--;) {
byte hex_ch = *in++;
@ -172,7 +172,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1);
// First pass, we convert input buffer to numeric base 64 values
byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
mp_uint_t i;
for (i = bufinfo.len; i >= 3; i -= 3) {
*out++ = (in[0] & 0xFC) >> 2;
@ -186,8 +186,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
if (i == 2) {
*out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4;
*out++ = (in[1] & 0x0F) << 2;
}
else {
} else {
*out++ = (in[0] & 0x03) << 4;
*out++ = 64;
}
@ -195,7 +194,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
}
// Second pass, we convert number base 64 values to actual base64 ascii encoding
out = (byte*)vstr.buf;
out = (byte *)vstr.buf;
for (mp_uint_t j = vstr.len - 1; j--;) {
if (*out < 26) {
*out += 'A';
@ -204,7 +203,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
} else if (*out < 62) {
*out += '0' - 52;
} else if (*out == 62) {
*out ='+';
*out = '+';
} else if (*out == 63) {
*out = '/';
} else {
@ -247,7 +246,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_binascii_globals, mp_module_binascii_globa
const mp_obj_module_t mp_module_ubinascii = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_binascii_globals,
.globals = (mp_obj_dict_t *)&mp_module_binascii_globals,
};
#endif //MICROPY_PY_UBINASCII

Wyświetl plik

@ -82,11 +82,11 @@ struct mbedtls_aes_ctx_with_key {
typedef struct _mp_obj_aes_t {
mp_obj_base_t base;
AES_CTX_IMPL ctx;
uint8_t block_mode: 6;
uint8_t block_mode : 6;
#define AES_KEYTYPE_NONE 0
#define AES_KEYTYPE_ENC 1
#define AES_KEYTYPE_DEC 2
uint8_t key_type: 2;
uint8_t key_type : 2;
} mp_obj_aes_t;
static inline bool is_ctr_mode(int block_mode) {
@ -99,7 +99,7 @@ static inline bool is_ctr_mode(int block_mode) {
static inline struct ctr_params *ctr_params_from_aes(mp_obj_aes_t *o) {
// ctr_params follows aes object struct
return (struct ctr_params*)&o[1];
return (struct ctr_params *)&o[1];
}
#if MICROPY_SSL_AXTLS
@ -117,7 +117,7 @@ STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) {
STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) {
memcpy(out, in, 16);
// We assume that out (vstr.buf or given output buffer) is uint32_t aligned
uint32_t *p = (uint32_t*)out;
uint32_t *p = (uint32_t *)out;
// axTLS likes it weird and complicated with byteswaps
for (int i = 0; i < 4; i++) {
p[i] = MP_HTOBE32(p[i]);
@ -289,7 +289,7 @@ STATIC mp_obj_t aes_process(size_t n_args, const mp_obj_t *args, bool encrypt) {
out_buf_ptr = out_bufinfo.buf;
} else {
vstr_init_len(&vstr, in_bufinfo.len);
out_buf_ptr = (uint8_t*)vstr.buf;
out_buf_ptr = (uint8_t *)vstr.buf;
}
if (AES_KEYTYPE_NONE == self->key_type) {
@ -353,26 +353,26 @@ STATIC const mp_obj_type_t ucryptolib_aes_type = {
{ &mp_type_type },
.name = MP_QSTR_aes,
.make_new = ucryptolib_aes_make_new,
.locals_dict = (void*)&ucryptolib_aes_locals_dict,
.locals_dict = (void *)&ucryptolib_aes_locals_dict,
};
STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) },
{ MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) },
#if MICROPY_PY_UCRYPTOLIB_CONSTS
#if MICROPY_PY_UCRYPTOLIB_CONSTS
{ MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) },
{ MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) },
#if MICROPY_PY_UCRYPTOLIB_CTR
{ MP_ROM_QSTR(MP_QSTR_MODE_CTR), MP_ROM_INT(UCRYPTOLIB_MODE_CTR) },
#endif
#endif
#endif
};
STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table);
const mp_obj_module_t mp_module_ucryptolib = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals,
.globals = (mp_obj_dict_t *)&mp_module_ucryptolib_globals,
};
#endif //MICROPY_PY_UCRYPTOLIB

Wyświetl plik

@ -124,7 +124,7 @@ STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args
mp_arg_check_num(n_args, n_kw, 2, 3, false);
mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
o->base.type = type;
o->addr = (void*)(uintptr_t)mp_obj_int_get_truncated(args[0]);
o->addr = (void *)(uintptr_t)mp_obj_int_get_truncated(args[0]);
o->desc = args[1];
o->flags = LAYOUT_NATIVE;
if (n_args == 3) {
@ -138,18 +138,22 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p
mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
const char *typen = "unk";
if (mp_obj_is_type(self->desc, &mp_type_dict)
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
|| mp_obj_is_type(self->desc, &mp_type_ordereddict)
#endif
) {
#endif
) {
typen = "STRUCT";
} else if (mp_obj_is_type(self->desc, &mp_type_tuple)) {
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc);
mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
switch (agg_type) {
case PTR: typen = "PTR"; break;
case ARRAY: typen = "ARRAY"; break;
case PTR:
typen = "PTR";
break;
case ARRAY:
typen = "ARRAY";
break;
}
} else {
typen = "ERROR";
@ -180,10 +184,10 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_
case STRUCT:
return uctypes_struct_size(t->items[1], layout_type, max_field_size);
case PTR:
if (sizeof(void*) > *max_field_size) {
*max_field_size = sizeof(void*);
if (sizeof(void *) > *max_field_size) {
*max_field_size = sizeof(void *);
}
return sizeof(void*);
return sizeof(void *);
case ARRAY: {
mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]);
uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS);
@ -211,12 +215,12 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_
STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) {
if (!mp_obj_is_type(desc_in, &mp_type_dict)
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
&& !mp_obj_is_type(desc_in, &mp_type_ordereddict)
#endif
) {
#endif
) {
if (mp_obj_is_type(desc_in, &mp_type_tuple)) {
return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size);
return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size);
} else if (mp_obj_is_small_int(desc_in)) {
// We allow sizeof on both type definitions and structures/structure fields,
// but scalar structure field is lowered into native Python int, so all
@ -311,11 +315,11 @@ static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_
static inline mp_uint_t get_aligned_basic(uint val_type, void *p) {
switch (val_type) {
case UINT8:
return *(uint8_t*)p;
return *(uint8_t *)p;
case UINT16:
return *(uint16_t*)p;
return *(uint16_t *)p;
case UINT32:
return *(uint32_t*)p;
return *(uint32_t *)p;
}
assert(0);
return 0;
@ -324,11 +328,14 @@ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) {
static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) {
switch (val_type) {
case UINT8:
*(uint8_t*)p = (uint8_t)v; return;
*(uint8_t *)p = (uint8_t)v;
return;
case UINT16:
*(uint16_t*)p = (uint16_t)v; return;
*(uint16_t *)p = (uint16_t)v;
return;
case UINT32:
*(uint32_t*)p = (uint32_t)v; return;
*(uint32_t *)p = (uint32_t)v;
return;
}
assert(0);
}
@ -336,26 +343,26 @@ static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) {
STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) {
switch (val_type) {
case UINT8:
return MP_OBJ_NEW_SMALL_INT(((uint8_t*)p)[index]);
return MP_OBJ_NEW_SMALL_INT(((uint8_t *)p)[index]);
case INT8:
return MP_OBJ_NEW_SMALL_INT(((int8_t*)p)[index]);
return MP_OBJ_NEW_SMALL_INT(((int8_t *)p)[index]);
case UINT16:
return MP_OBJ_NEW_SMALL_INT(((uint16_t*)p)[index]);
return MP_OBJ_NEW_SMALL_INT(((uint16_t *)p)[index]);
case INT16:
return MP_OBJ_NEW_SMALL_INT(((int16_t*)p)[index]);
return MP_OBJ_NEW_SMALL_INT(((int16_t *)p)[index]);
case UINT32:
return mp_obj_new_int_from_uint(((uint32_t*)p)[index]);
return mp_obj_new_int_from_uint(((uint32_t *)p)[index]);
case INT32:
return mp_obj_new_int(((int32_t*)p)[index]);
return mp_obj_new_int(((int32_t *)p)[index]);
case UINT64:
return mp_obj_new_int_from_ull(((uint64_t*)p)[index]);
return mp_obj_new_int_from_ull(((uint64_t *)p)[index]);
case INT64:
return mp_obj_new_int_from_ll(((int64_t*)p)[index]);
return mp_obj_new_int_from_ll(((int64_t *)p)[index]);
#if MICROPY_PY_BUILTINS_FLOAT
case FLOAT32:
return mp_obj_new_float(((float*)p)[index]);
return mp_obj_new_float(((float *)p)[index]);
case FLOAT64:
return mp_obj_new_float(((double*)p)[index]);
return mp_obj_new_float(((double *)p)[index]);
#endif
default:
assert(0);
@ -368,9 +375,9 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) {
if (val_type == FLOAT32 || val_type == FLOAT64) {
mp_float_t v = mp_obj_get_float(val);
if (val_type == FLOAT32) {
((float*)p)[index] = v;
((float *)p)[index] = v;
} else {
((double*)p)[index] = v;
((double *)p)[index] = v;
}
return;
}
@ -378,21 +385,27 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) {
mp_int_t v = mp_obj_get_int_truncated(val);
switch (val_type) {
case UINT8:
((uint8_t*)p)[index] = (uint8_t)v; return;
((uint8_t *)p)[index] = (uint8_t)v;
return;
case INT8:
((int8_t*)p)[index] = (int8_t)v; return;
((int8_t *)p)[index] = (int8_t)v;
return;
case UINT16:
((uint16_t*)p)[index] = (uint16_t)v; return;
((uint16_t *)p)[index] = (uint16_t)v;
return;
case INT16:
((int16_t*)p)[index] = (int16_t)v; return;
((int16_t *)p)[index] = (int16_t)v;
return;
case UINT32:
((uint32_t*)p)[index] = (uint32_t)v; return;
((uint32_t *)p)[index] = (uint32_t)v;
return;
case INT32:
((int32_t*)p)[index] = (int32_t)v; return;
((int32_t *)p)[index] = (int32_t)v;
return;
case INT64:
case UINT64:
if (sizeof(mp_int_t) == 8) {
((uint64_t*)p)[index] = (uint64_t)v;
((uint64_t *)p)[index] = (uint64_t)v;
} else {
// TODO: Doesn't offer atomic store semantics, but should at least try
set_unaligned(val_type, p, MP_ENDIANNESS_BIG, val);
@ -407,11 +420,11 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set
mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
if (!mp_obj_is_type(self->desc, &mp_type_dict)
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
&& !mp_obj_is_type(self->desc, &mp_type_ordereddict)
#endif
) {
mp_raise_TypeError("struct: no fields");
#endif
) {
mp_raise_TypeError("struct: no fields");
}
mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr));
@ -593,7 +606,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_ob
}
} else if (agg_type == PTR) {
byte *p = *(void**)self->addr;
byte *p = *(void **)self->addr;
if (mp_obj_is_small_int(t->items[1])) {
uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS);
return get_aligned(val_type, p, index);
@ -623,13 +636,14 @@ STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
if (agg_type == PTR) {
byte *p = *(void**)self->addr;
byte *p = *(void **)self->addr;
return mp_obj_new_int((mp_int_t)(uintptr_t)p);
}
}
/* fallthru */
/* fallthru */
default: return MP_OBJ_NULL; // op not supported
default:
return MP_OBJ_NULL; // op not supported
}
}
@ -660,7 +674,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_addressof_obj, uctypes_struct_addressof
/// captured by reference (and thus memory pointed by bytearray may change
/// or become invalid at later time). Use bytes_at() to capture by value.
STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) {
return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr));
return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr));
}
MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at);
@ -669,7 +683,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytear
/// captured by value, i.e. copied. Use bytearray_at() to capture by reference
/// ("zero copy").
STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) {
return mp_obj_new_bytes((void*)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size));
return mp_obj_new_bytes((void *)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size));
}
MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at);
@ -772,7 +786,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uctypes_globals, mp_module_uctypes_globals
const mp_obj_module_t mp_module_uctypes = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_uctypes_globals,
.globals = (mp_obj_dict_t *)&mp_module_uctypes_globals,
};
#endif

Wyświetl plik

@ -78,8 +78,8 @@ STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_arg
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context));
o->base.type = type;
mbedtls_sha256_init((mbedtls_sha256_context*)&o->state);
mbedtls_sha256_starts_ret((mbedtls_sha256_context*)&o->state, 0);
mbedtls_sha256_init((mbedtls_sha256_context *)&o->state);
mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0);
if (n_args == 1) {
uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -90,7 +90,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
mbedtls_sha256_update_ret((mbedtls_sha256_context*)&self->state, bufinfo.buf, bufinfo.len);
mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -98,7 +98,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, 32);
mbedtls_sha256_finish_ret((mbedtls_sha256_context*)&self->state, (unsigned char *)vstr.buf);
mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
@ -110,7 +110,7 @@ STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_arg
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX));
o->base.type = type;
sha256_init((CRYAL_SHA256_CTX*)o->state);
sha256_init((CRYAL_SHA256_CTX *)o->state);
if (n_args == 1) {
uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -121,7 +121,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len);
sha256_update((CRYAL_SHA256_CTX *)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -129,7 +129,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, SHA256_BLOCK_SIZE);
sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf);
sha256_final((CRYAL_SHA256_CTX *)self->state, (byte *)vstr.buf);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
#endif
@ -148,7 +148,7 @@ STATIC const mp_obj_type_t uhashlib_sha256_type = {
{ &mp_type_type },
.name = MP_QSTR_sha256,
.make_new = uhashlib_sha256_make_new,
.locals_dict = (void*)&uhashlib_sha256_locals_dict,
.locals_dict = (void *)&uhashlib_sha256_locals_dict,
};
#endif
@ -160,7 +160,7 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args,
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX));
o->base.type = type;
SHA1_Init((SHA1_CTX*)o->state);
SHA1_Init((SHA1_CTX *)o->state);
if (n_args == 1) {
uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -171,7 +171,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len);
SHA1_Update((SHA1_CTX *)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -179,7 +179,7 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, SHA1_SIZE);
SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state);
SHA1_Final((byte *)vstr.buf, (SHA1_CTX *)self->state);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
#endif
@ -196,8 +196,8 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args,
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context));
o->base.type = type;
mbedtls_sha1_init((mbedtls_sha1_context*)o->state);
mbedtls_sha1_starts_ret((mbedtls_sha1_context*)o->state);
mbedtls_sha1_init((mbedtls_sha1_context *)o->state);
mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state);
if (n_args == 1) {
uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -208,7 +208,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
mbedtls_sha1_update_ret((mbedtls_sha1_context*)self->state, bufinfo.buf, bufinfo.len);
mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -216,8 +216,8 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, 20);
mbedtls_sha1_finish_ret((mbedtls_sha1_context*)self->state, (byte*)vstr.buf);
mbedtls_sha1_free((mbedtls_sha1_context*)self->state);
mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf);
mbedtls_sha1_free((mbedtls_sha1_context *)self->state);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
#endif
@ -235,7 +235,7 @@ STATIC const mp_obj_type_t uhashlib_sha1_type = {
{ &mp_type_type },
.name = MP_QSTR_sha1,
.make_new = uhashlib_sha1_make_new,
.locals_dict = (void*)&uhashlib_sha1_locals_dict,
.locals_dict = (void *)&uhashlib_sha1_locals_dict,
};
#endif
@ -247,7 +247,7 @@ STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args,
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX));
o->base.type = type;
MD5_Init((MD5_CTX*)o->state);
MD5_Init((MD5_CTX *)o->state);
if (n_args == 1) {
uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -258,7 +258,7 @@ STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
MD5_Update((MD5_CTX*)self->state, bufinfo.buf, bufinfo.len);
MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -266,7 +266,7 @@ STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, MD5_SIZE);
MD5_Final((byte*)vstr.buf, (MD5_CTX*)self->state);
MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
#endif // MICROPY_SSL_AXTLS
@ -283,8 +283,8 @@ STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args,
mp_arg_check_num(n_args, n_kw, 0, 1, false);
mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context));
o->base.type = type;
mbedtls_md5_init((mbedtls_md5_context*)o->state);
mbedtls_md5_starts_ret((mbedtls_md5_context*)o->state);
mbedtls_md5_init((mbedtls_md5_context *)o->state);
mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state);
if (n_args == 1) {
uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]);
}
@ -295,7 +295,7 @@ STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
mbedtls_md5_update_ret((mbedtls_md5_context*)self->state, bufinfo.buf, bufinfo.len);
mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len);
return mp_const_none;
}
@ -303,8 +303,8 @@ STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) {
mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in);
vstr_t vstr;
vstr_init_len(&vstr, 16);
mbedtls_md5_finish_ret((mbedtls_md5_context*)self->state, (byte*)vstr.buf);
mbedtls_md5_free((mbedtls_md5_context*)self->state);
mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf);
mbedtls_md5_free((mbedtls_md5_context *)self->state);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
#endif // MICROPY_SSL_MBEDTLS
@ -322,7 +322,7 @@ STATIC const mp_obj_type_t uhashlib_md5_type = {
{ &mp_type_type },
.name = MP_QSTR_md5,
.make_new = uhashlib_md5_make_new,
.locals_dict = (void*)&uhashlib_md5_locals_dict,
.locals_dict = (void *)&uhashlib_md5_locals_dict,
};
#endif // MICROPY_PY_UHASHLIB_MD5
@ -343,7 +343,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globa
const mp_obj_module_t mp_module_uhashlib = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_uhashlib_globals,
.globals = (mp_obj_dict_t *)&mp_module_uhashlib_globals,
};
#endif //MICROPY_PY_UHASHLIB

Wyświetl plik

@ -115,7 +115,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uheapq_globals, mp_module_uheapq_globals_t
const mp_obj_module_t mp_module_uheapq = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_uheapq_globals,
.globals = (mp_obj_dict_t *)&mp_module_uheapq_globals,
};
#endif

Wyświetl plik

@ -100,7 +100,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
mp_obj_t stack_key = MP_OBJ_NULL;
S_NEXT(s);
for (;;) {
cont:
cont:
if (S_END(s)) {
break;
}
@ -147,11 +147,21 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
if (c == '\\') {
c = S_NEXT(s);
switch (c) {
case 'b': c = 0x08; break;
case 'f': c = 0x0c; break;
case 'n': c = 0x0a; break;
case 'r': c = 0x0d; break;
case 't': c = 0x09; break;
case 'b':
c = 0x08;
break;
case 'f':
c = 0x0c;
break;
case 'n':
c = 0x0a;
break;
case 'r':
c = 0x0d;
break;
case 't':
c = 0x09;
break;
case 'u': {
mp_uint_t num = 0;
for (int i = 0; i < 4; i++) {
@ -177,7 +187,16 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
next = mp_obj_new_str(vstr.buf, vstr.len);
break;
case '-':
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
bool flt = false;
vstr_reset(&vstr);
for (;;) {
@ -259,7 +278,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
}
}
}
success:
success:
// eat trailing whitespace
while (unichar_isspace(S_CUR(s))) {
S_NEXT(s);
@ -275,7 +294,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) {
vstr_clear(&vstr);
return stack_top;
fail:
fail:
mp_raise_ValueError("syntax error in JSON");
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load);
@ -283,7 +302,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load);
STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(obj, &bufinfo, MP_BUFFER_READ);
vstr_t vstr = {bufinfo.len, bufinfo.len, (char*)bufinfo.buf, true};
vstr_t vstr = {bufinfo.len, bufinfo.len, (char *)bufinfo.buf, true};
mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL};
return mod_ujson_load(MP_OBJ_FROM_PTR(&sio));
}
@ -301,7 +320,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ujson_globals, mp_module_ujson_globals_tab
const mp_obj_module_t mp_module_ujson = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ujson_globals,
.globals = (mp_obj_dict_t *)&mp_module_ujson_globals,
};
#endif //MICROPY_PY_UJSON

Wyświetl plik

@ -41,15 +41,14 @@ STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233;
STATIC uint8_t yasmarang_dat = 0;
#endif
STATIC uint32_t yasmarang(void)
{
yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
yasmarang_pad = (yasmarang_pad<<3) + (yasmarang_pad>>29);
yasmarang_n = yasmarang_pad | 2;
yasmarang_d ^= (yasmarang_pad<<31) + (yasmarang_pad>>1);
yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d>>8) ^ 1;
STATIC uint32_t yasmarang(void) {
yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n;
yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29);
yasmarang_n = yasmarang_pad | 2;
yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1);
yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d >> 8) ^ 1;
return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<1));
return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1);
} /* yasmarang */
// End of Yasmarang
@ -221,7 +220,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_urandom_globals, mp_module_urandom_globals
const mp_obj_module_t mp_module_urandom = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_urandom_globals,
.globals = (mp_obj_dict_t *)&mp_module_urandom_globals,
};
#endif

Wyświetl plik

@ -73,7 +73,7 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) {
return mp_const_none;
}
return mp_obj_new_str_of_type(mp_obj_get_type(self->str),
(const byte*)start, self->caps[no * 2 + 1] - start);
(const byte *)start, self->caps[no * 2 + 1] - start);
}
MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group);
@ -163,7 +163,7 @@ STATIC const mp_obj_type_t match_type = {
{ &mp_type_type },
.name = MP_QSTR_match,
.print = match_print,
.locals_dict = (void*)&match_locals_dict,
.locals_dict = (void *)&match_locals_dict,
};
#endif
@ -181,12 +181,12 @@ STATIC mp_obj_t ure_exec(bool is_anchored, uint n_args, const mp_obj_t *args) {
subj.begin = mp_obj_str_get_data(args[1], &len);
subj.end = subj.begin + len;
int caps_num = (self->re.sub + 1) * 2;
mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char*, caps_num);
mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char *, caps_num);
// cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
memset((char*)match->caps, 0, caps_num * sizeof(char*));
memset((char *)match->caps, 0, caps_num * sizeof(char *));
int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored);
if (res == 0) {
m_del_var(mp_obj_match_t, char*, caps_num, match);
m_del_var(mp_obj_match_t, char *, caps_num, match);
return mp_const_none;
}
@ -221,10 +221,10 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) {
}
mp_obj_t retval = mp_obj_new_list(0, NULL);
const char **caps = mp_local_alloc(caps_num * sizeof(char*));
const char **caps = mp_local_alloc(caps_num * sizeof(char *));
while (true) {
// cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
memset((char**)caps, 0, caps_num * sizeof(char*));
memset((char **)caps, 0, caps_num * sizeof(char *));
int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false);
// if we didn't have a match, or had an empty match, it's time to stop
@ -232,7 +232,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) {
break;
}
mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, caps[0] - subj.begin);
mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, caps[0] - subj.begin);
mp_obj_list_append(retval, s);
if (self->re.sub > 0) {
mp_raise_NotImplementedError("Splitting with sub-captures");
@ -243,9 +243,9 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) {
}
}
// cast is a workaround for a bug in msvc (see above)
mp_local_free((char**)caps);
mp_local_free((char **)caps);
mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, subj.end - subj.begin);
mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, subj.end - subj.begin);
mp_obj_list_append(retval, s);
return retval;
}
@ -272,14 +272,14 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a
vstr_t vstr_return;
vstr_return.buf = NULL; // We'll init the vstr after the first match
mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char*));
mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char *));
match->base.type = &match_type;
match->num_matches = caps_num / 2; // caps_num counts start and end pointers
match->str = where;
for (;;) {
// cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char
memset((char*)match->caps, 0, caps_num * sizeof(char*));
memset((char *)match->caps, 0, caps_num * sizeof(char *));
int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, false);
// If we didn't have a match, or had an empty match, it's time to stop
@ -296,7 +296,7 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a
vstr_add_strn(&vstr_return, subj.begin, match->caps[0] - subj.begin);
// Get replacement string
const char* repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace));
const char *repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace));
// Append replacement string to result, substituting any regex groups
while (*repl != '\0') {
@ -381,7 +381,7 @@ STATIC const mp_obj_type_t re_type = {
{ &mp_type_type },
.name = MP_QSTR_ure,
.print = re_print,
.locals_dict = (void*)&re_locals_dict,
.locals_dict = (void *)&re_locals_dict,
};
#endif
@ -402,7 +402,7 @@ STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) {
#endif
int error = re1_5_compilecode(&o->re, re_str);
if (error != 0) {
error:
error:
mp_raise_ValueError("Error in regex");
}
#if MICROPY_PY_URE_DEBUG
@ -459,7 +459,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_re_globals, mp_module_re_globals_table);
const mp_obj_module_t mp_module_ure = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_re_globals,
.globals = (mp_obj_dict_t *)&mp_module_re_globals,
};
#endif

Wyświetl plik

@ -66,9 +66,9 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_
} else {
// object exists; update its flags
if (or_flags) {
((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags |= flags;
((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags;
} else {
((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = flags;
((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags;
}
}
}
@ -161,13 +161,13 @@ STATIC mp_obj_t select_select(size_t n_args, const mp_obj_t *args) {
}
poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value);
if (poll_obj->flags_ret & MP_STREAM_POLL_RD) {
((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj;
((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj;
}
if (poll_obj->flags_ret & MP_STREAM_POLL_WR) {
((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj;
((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj;
}
if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) {
((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj;
((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj;
}
}
mp_map_deinit(&poll_map);
@ -220,7 +220,7 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas
if (elem == NULL) {
mp_raise_OSError(MP_ENOENT);
}
((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in);
((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify);
@ -345,7 +345,7 @@ STATIC const mp_obj_type_t mp_type_poll = {
.name = MP_QSTR_poll,
.getiter = mp_identity_getiter,
.iternext = poll_iternext,
.locals_dict = (void*)&poll_locals_dict,
.locals_dict = (void *)&poll_locals_dict,
};
/// \function poll()
@ -373,7 +373,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_t
const mp_obj_module_t mp_module_uselect = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_select_globals,
.globals = (mp_obj_dict_t *)&mp_module_select_globals,
};
#endif // MICROPY_PY_USELECT

Wyświetl plik

@ -55,11 +55,11 @@ struct ssl_args {
STATIC const mp_obj_type_t ussl_socket_type;
STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args) {
#if MICROPY_PY_USSL_FINALISER
#if MICROPY_PY_USSL_FINALISER
mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
#else
#else
mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
#endif
#endif
o->base.type = &ussl_socket_type;
o->buf = NULL;
o->bytes_left = 0;
@ -79,13 +79,13 @@ STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args
if (args->key.u_obj != mp_const_none) {
size_t len;
const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len);
const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len);
int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL);
if (res != SSL_OK) {
mp_raise_ValueError("invalid key");
}
data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len);
data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len);
res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL);
if (res != SSL_OK) {
mp_raise_ValueError("invalid cert");
@ -98,7 +98,7 @@ STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args
SSL_EXTENSIONS *ext = ssl_ext_new();
if (args->server_hostname.u_obj != mp_const_none) {
ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj);
ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj);
}
o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext);
@ -155,7 +155,7 @@ STATIC mp_uint_t ussl_socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int
return 0;
}
if (r == SSL_EAGAIN) {
eagain:
eagain:
r = MP_EAGAIN;
}
*errcode = r;
@ -219,9 +219,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ussl_socket_setblocking_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
#if MICROPY_PY_USSL_FINALISER
#if MICROPY_PY_USSL_FINALISER
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
#endif
#endif
};
STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
@ -240,7 +240,7 @@ STATIC const mp_obj_type_t ussl_socket_type = {
.getiter = NULL,
.iternext = NULL,
.protocol = &ussl_socket_stream_p,
.locals_dict = (void*)&ussl_socket_locals_dict,
.locals_dict = (void *)&ussl_socket_locals_dict,
};
STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
@ -258,7 +258,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_
struct ssl_args args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
return MP_OBJ_FROM_PTR(ussl_socket_new(sock, &args));
}
@ -273,7 +273,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
const mp_obj_module_t mp_module_ussl = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
.globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
};
#endif // MICROPY_PY_USSL

Wyświetl plik

@ -75,7 +75,7 @@ STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, cons
#endif
STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
mp_obj_t sock = *(mp_obj_t*)ctx;
mp_obj_t sock = *(mp_obj_t *)ctx;
const mp_stream_p_t *sock_stream = mp_get_stream(sock);
int err;
@ -92,7 +92,7 @@ STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
}
STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
mp_obj_t sock = *(mp_obj_t*)ctx;
mp_obj_t sock = *(mp_obj_t *)ctx;
const mp_stream_p_t *sock_stream = mp_get_stream(sock);
int err;
@ -113,11 +113,11 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
// Verify the socket object has the full stream protocol
mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
#if MICROPY_PY_USSL_FINALISER
#if MICROPY_PY_USSL_FINALISER
mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t);
#else
#else
mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
#endif
#endif
o->base.type = &ussl_socket_type;
o->sock = sock;
@ -141,9 +141,9 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
}
ret = mbedtls_ssl_config_defaults(&o->conf,
args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0) {
goto cleanup;
}
@ -171,7 +171,7 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
if (args->key.u_obj != mp_const_none) {
size_t key_len;
const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len);
const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len);
// len should include terminating null
ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
if (ret != 0) {
@ -180,7 +180,7 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
}
size_t cert_len;
const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
// len should include terminating null
ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
if (ret != 0) {
@ -230,7 +230,7 @@ STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
if (!mp_obj_is_true(binary_form)) {
mp_raise_NotImplementedError(NULL);
}
const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
if (peer_cert == NULL) {
return mp_const_none;
}
@ -318,9 +318,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
#if MICROPY_PY_USSL_FINALISER
#if MICROPY_PY_USSL_FINALISER
{ MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) },
#endif
#endif
{ MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
};
@ -340,7 +340,7 @@ STATIC const mp_obj_type_t ussl_socket_type = {
.getiter = NULL,
.iternext = NULL,
.protocol = &ussl_socket_stream_p,
.locals_dict = (void*)&ussl_socket_locals_dict,
.locals_dict = (void *)&ussl_socket_locals_dict,
};
STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
@ -358,7 +358,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_
struct ssl_args args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
return MP_OBJ_FROM_PTR(socket_new(sock, &args));
}
@ -373,7 +373,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
const mp_obj_module_t mp_module_ussl = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
.globals = (mp_obj_dict_t *)&mp_module_ssl_globals,
};
#endif // MICROPY_PY_USSL

Wyświetl plik

@ -190,9 +190,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump);
STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) {
case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0);
case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len);
default: return MP_OBJ_NULL; // op not supported
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(self->len != 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->len);
default:
return MP_OBJ_NULL; // op not supported
}
}
@ -212,7 +215,7 @@ STATIC const mp_obj_type_t utimeq_type = {
.name = MP_QSTR_utimeq,
.make_new = utimeq_make_new,
.unary_op = utimeq_unary_op,
.locals_dict = (void*)&utimeq_locals_dict,
.locals_dict = (void *)&utimeq_locals_dict,
};
STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = {
@ -224,7 +227,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_utimeq_globals, mp_module_utimeq_globals_t
const mp_obj_module_t mp_module_utimeq = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_utimeq_globals,
.globals = (mp_obj_dict_t *)&mp_module_utimeq_globals,
};
#endif //MICROPY_PY_UTIMEQ

Wyświetl plik

@ -71,11 +71,11 @@ STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, siz
if (n_args > 1 && args[1] == mp_const_true) {
o->opts |= BLOCKING_WRITE;
}
return MP_OBJ_FROM_PTR(o);
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
const mp_stream_p_t *stream_p = mp_get_stream(self->sock);
while (1) {
if (self->to_recv != 0) {
@ -183,7 +183,7 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int
self->msg_sz -= out_sz;
if (self->msg_sz == 0) {
byte last_state;
no_payload:
no_payload:
last_state = self->state;
self->state = FRAME_HEADER;
self->to_recv = 2;
@ -217,7 +217,7 @@ no_payload:
}
STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in);
assert(size < 0x10000);
byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)};
int hdr_sz;
@ -296,7 +296,7 @@ STATIC const mp_obj_type_t websocket_type = {
.name = MP_QSTR_websocket,
.make_new = websocket_make_new,
.protocol = &websocket_stream_p,
.locals_dict = (void*)&websocket_locals_dict,
.locals_dict = (void *)&websocket_locals_dict,
};
STATIC const mp_rom_map_elem_t uwebsocket_module_globals_table[] = {
@ -308,7 +308,7 @@ STATIC MP_DEFINE_CONST_DICT(uwebsocket_module_globals, uwebsocket_module_globals
const mp_obj_module_t mp_module_uwebsocket = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&uwebsocket_module_globals,
.globals = (mp_obj_dict_t *)&uwebsocket_module_globals,
};
#endif // MICROPY_PY_UWEBSOCKET

Wyświetl plik

@ -49,9 +49,9 @@ typedef struct _mp_obj_decompio_t {
} mp_obj_decompio_t;
STATIC int read_src_stream(TINF_DATA *data) {
byte *p = (void*)data;
byte *p = (void *)data;
p -= offsetof(mp_obj_decompio_t, decomp);
mp_obj_decompio_t *self = (mp_obj_decompio_t*)p;
mp_obj_decompio_t *self = (mp_obj_decompio_t *)p;
const mp_stream_p_t *stream = mp_get_stream(self->src_stream);
int err;
@ -91,7 +91,7 @@ STATIC mp_obj_t decompio_make_new(const mp_obj_type_t *type, size_t n_args, size
} else if (dict_opt >= 0) {
dict_opt = uzlib_zlib_parse_header(&o->decomp);
if (dict_opt < 0) {
header_error:
header_error:
mp_raise_ValueError("compression header");
}
dict_sz = 1 << dict_opt;
@ -110,7 +110,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er
}
o->decomp.dest = buf;
o->decomp.dest_limit = (byte*)buf + size;
o->decomp.dest_limit = (byte *)buf + size;
int st = uzlib_uncompress_chksum(&o->decomp);
if (st == TINF_DONE) {
o->eof = true;
@ -119,7 +119,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er
*errcode = MP_EINVAL;
return MP_STREAM_ERROR;
}
return o->decomp.dest - (byte*)buf;
return o->decomp.dest - (byte *)buf;
}
#if !MICROPY_ENABLE_DYNRUNTIME
@ -142,7 +142,7 @@ STATIC const mp_obj_type_t decompio_type = {
.name = MP_QSTR_DecompIO,
.make_new = decompio_make_new,
.protocol = &decompio_stream_p,
.locals_dict = (void*)&decompio_locals_dict,
.locals_dict = (void *)&decompio_locals_dict,
};
#endif
@ -162,7 +162,7 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) {
decomp->dest_limit = dest_buf + dest_buf_size;
DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", dest_buf_size);
decomp->source = bufinfo.buf;
decomp->source_limit = (byte*)bufinfo.buf + bufinfo.len;
decomp->source_limit = (byte *)bufinfo.buf + bufinfo.len;
int st;
bool is_zlib = true;
@ -195,13 +195,13 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) {
mp_uint_t final_sz = decomp->dest - dest_buf;
DEBUG_printf("uzlib: Resizing from " UINT_FMT " to final size: " UINT_FMT " bytes\n", dest_buf_size, final_sz);
dest_buf = (byte*)m_renew(byte, dest_buf, dest_buf_size, final_sz);
dest_buf = (byte *)m_renew(byte, dest_buf, dest_buf_size, final_sz);
mp_obj_t res = mp_obj_new_bytearray_by_ref(final_sz, dest_buf);
m_del_obj(TINF_DATA, decomp);
return res;
error:
nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st)));
nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st)));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress);
@ -216,7 +216,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uzlib_globals, mp_module_uzlib_globals_tab
const mp_obj_module_t mp_module_uzlib = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_uzlib_globals,
.globals = (mp_obj_dict_t *)&mp_module_uzlib_globals,
};
#endif

Wyświetl plik

@ -155,7 +155,7 @@ STATIC void handle_op(mp_obj_webrepl_t *self) {
open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb);
}
self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map);
self->cur_file = mp_builtin_open(2, open_args, (mp_map_t *)&mp_const_empty_map);
#if 0
struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 };
@ -196,7 +196,7 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int
}
if (self->state == STATE_PASSWD) {
char c = *(char*)buf;
char c = *(char *)buf;
if (c == '\r' || c == '\n') {
self->hdr.fname[self->data_to_recv] = 0;
DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname);
@ -224,8 +224,8 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int
DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv);
if (self->hdr_to_recv != 0) {
char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
*p++ = *(char*)buf;
char *p = (char *)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
*p++ = *(char *)buf;
if (--self->hdr_to_recv != 0) {
mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode);
if (hdr_sz == MP_STREAM_ERROR) {
@ -250,7 +250,7 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int
static
#endif
byte filebuf[512];
filebuf[0] = *(byte*)buf;
filebuf[0] = *(byte *)buf;
mp_uint_t buf_sz = 1;
if (--self->data_to_recv != 0) {
size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv);
@ -348,7 +348,7 @@ STATIC const mp_obj_type_t webrepl_type = {
.name = MP_QSTR__webrepl,
.make_new = webrepl_make_new,
.protocol = &webrepl_stream_p,
.locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict,
.locals_dict = (mp_obj_dict_t *)&webrepl_locals_dict,
};
STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = {
@ -361,7 +361,7 @@ STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table
const mp_obj_module_t mp_module_webrepl = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&webrepl_module_globals,
.globals = (mp_obj_dict_t *)&webrepl_module_globals,
};
#endif // MICROPY_PY_WEBREPL

Wyświetl plik

@ -71,7 +71,7 @@ STATIC void network_cyw43_print(const mp_print_t *print, mp_obj_t self_in, mp_pr
netif->ip_addr.addr >> 8 & 0xff,
netif->ip_addr.addr >> 16 & 0xff,
netif->ip_addr.addr >> 24
);
);
}
STATIC mp_obj_t network_cyw43_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
@ -135,7 +135,7 @@ STATIC int network_cyw43_scan_cb(void *env, const cyw43_ev_scan_result_t *res) {
mp_obj_get_array(list, &len, &items);
for (size_t i = 0; i < len; ++i) {
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(items[i]);
if (memcmp(res->bssid, ((mp_obj_str_t*)MP_OBJ_TO_PTR(t->items[1]))->data, sizeof(res->bssid)) == 0) {
if (memcmp(res->bssid, ((mp_obj_str_t *)MP_OBJ_TO_PTR(t->items[1]))->data, sizeof(res->bssid)) == 0) {
if (res->rssi > MP_OBJ_SMALL_INT_VALUE(t->items[3])) {
t->items[3] = MP_OBJ_NEW_SMALL_INT(res->rssi);
}
@ -289,7 +289,7 @@ STATIC mp_obj_t network_cyw43_status(size_t n_args, const mp_obj_t *args) {
mp_obj_t tuple[1] = {
mp_obj_new_bytes(&macs[i * 6], 6),
};
((mp_obj_list_t*)MP_OBJ_TO_PTR(list))->items[i] = mp_obj_new_tuple(1, tuple);
((mp_obj_list_t *)MP_OBJ_TO_PTR(list))->items[i] = mp_obj_new_tuple(1, tuple);
}
return list;
}
@ -334,12 +334,12 @@ STATIC mp_obj_t network_cyw43_config(size_t n_args, const mp_obj_t *args, mp_map
if (self->itf == CYW43_ITF_STA) {
uint8_t buf[36];
cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_SSID, 36, buf, self->itf);
return mp_obj_new_str((const char*)buf + 4, nw_get_le32(buf));
return mp_obj_new_str((const char *)buf + 4, nw_get_le32(buf));
} else {
size_t len;
const uint8_t *buf;
cyw43_wifi_ap_get_ssid(self->cyw, &len, &buf);
return mp_obj_new_str((const char*)buf, len);
return mp_obj_new_str((const char *)buf, len);
}
}
case MP_QSTR_mac: {
@ -379,7 +379,7 @@ STATIC mp_obj_t network_cyw43_config(size_t n_args, const mp_obj_t *args, mp_map
case MP_QSTR_essid: {
size_t len;
const char *str = mp_obj_str_get_data(e->value, &len);
cyw43_wifi_ap_set_ssid(self->cyw, len, (const uint8_t*)str);
cyw43_wifi_ap_set_ssid(self->cyw, len, (const uint8_t *)str);
break;
}
case MP_QSTR_monitor: {
@ -400,7 +400,7 @@ STATIC mp_obj_t network_cyw43_config(size_t n_args, const mp_obj_t *args, mp_map
case MP_QSTR_password: {
size_t len;
const char *str = mp_obj_str_get_data(e->value, &len);
cyw43_wifi_ap_set_password(self->cyw, len, (const uint8_t*)str);
cyw43_wifi_ap_set_password(self->cyw, len, (const uint8_t *)str);
break;
}
case MP_QSTR_pm: {
@ -454,7 +454,7 @@ const mp_obj_type_t mp_network_cyw43_type = {
.name = MP_QSTR_CYW43,
.print = network_cyw43_print,
.make_new = network_cyw43_make_new,
.locals_dict = (mp_obj_dict_t*)&network_cyw43_locals_dict,
.locals_dict = (mp_obj_dict_t *)&network_cyw43_locals_dict,
};
#endif // MICROPY_PY_NETWORK_CYW43

Wyświetl plik

@ -106,9 +106,9 @@ int mp_uos_dupterm_rx_chr(void) {
mp_uint_t out_sz = stream_p->read(MP_STATE_VM(dupterm_objs[idx]), buf, 1, &errcode);
if (errcode == 0 && out_sz != 0) {
return buf[0];
} else {
} else {
continue;
}
}
}
#endif

Wyświetl plik

@ -86,7 +86,7 @@ STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) {
// Optimized formula avoiding if conditions. We adjust difference "forward",
// wrap it around and adjust back.
mp_int_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1))
- MICROPY_PY_UTIME_TICKS_PERIOD / 2;
- MICROPY_PY_UTIME_TICKS_PERIOD / 2;
return MP_OBJ_NEW_SMALL_INT(diff);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff);

Wyświetl plik

@ -103,7 +103,7 @@ STATIC mp_vfs_mount_t *lookup_path(mp_obj_t path_in, mp_obj_t *path_out) {
mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out);
if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) {
*path_out = mp_obj_new_str_of_type(mp_obj_get_type(path_in),
(const byte*)p_out, strlen(p_out));
(const byte *)p_out, strlen(p_out));
}
return vfs;
}
@ -231,7 +231,7 @@ mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args
vfs->next = NULL;
// call the underlying object to do any mounting operation
mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t*)&args);
mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args);
// check that the destination mount point is unused
const char *path_out;
@ -315,7 +315,7 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
#endif
mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj);
return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t*)&args);
return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args);
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open);
@ -395,7 +395,7 @@ STATIC mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) {
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
t->items[0] = mp_obj_new_str_of_type(
self->is_str ? &mp_type_str : &mp_type_bytes,
(const byte*)vfs->str + 1, vfs->len - 1);
(const byte *)vfs->str + 1, vfs->len - 1);
t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR);
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
return MP_OBJ_FROM_PTR(t);

Wyświetl plik

@ -31,8 +31,8 @@
// return values of mp_vfs_lookup_path
// ROOT is 0 so that the default current directory is the root directory
#define MP_VFS_NONE ((mp_vfs_mount_t*)1)
#define MP_VFS_ROOT ((mp_vfs_mount_t*)0)
#define MP_VFS_NONE ((mp_vfs_mount_t *)1)
#define MP_VFS_ROOT ((mp_vfs_mount_t *)0)
// MicroPython's port-standardized versions of stat constants
#define MP_S_IFDIR (0x4000)

Wyświetl plik

@ -48,10 +48,10 @@ void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev) {
int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf) {
if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) {
mp_uint_t (*f)(uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)self->readblocks[2];
mp_uint_t (*f)(uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->readblocks[2];
return f(buf, block_num, num_blocks);
} else {
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks * self->block_size, buf};
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, buf};
self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
self->readblocks[3] = MP_OBJ_FROM_PTR(&ar);
mp_call_method_n_kw(2, 0, self->readblocks);
@ -80,10 +80,10 @@ int mp_vfs_blockdev_write(mp_vfs_blockdev_t *self, size_t block_num, size_t num_
}
if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) {
mp_uint_t (*f)(const uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)self->writeblocks[2];
mp_uint_t (*f)(const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->writeblocks[2];
return f(buf, block_num, num_blocks);
} else {
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks * self->block_size, (void*)buf};
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, (void *)buf};
self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar);
mp_call_method_n_kw(2, 0, self->writeblocks);
@ -98,7 +98,7 @@ int mp_vfs_blockdev_write_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t
return -MP_EROFS;
}
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void*)buf};
mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void *)buf};
self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num);
self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar);
self->writeblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off);

Wyświetl plik

@ -142,7 +142,7 @@ STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) {
if (self->is_str) {
t->items[0] = mp_obj_new_str(fn, strlen(fn));
} else {
t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn));
t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn));
}
if (fno.fattrib & AM_DIR) {
// dir
@ -318,7 +318,7 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) {
(fno.ftime >> 11) & 0x1f,
(fno.ftime >> 5) & 0x3f,
2 * (fno.ftime & 0x1f)
);
);
t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode
t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev
@ -425,7 +425,7 @@ const mp_obj_type_t mp_fat_vfs_type = {
.name = MP_QSTR_VfsFat,
.make_new = fat_vfs_make_new,
.protocol = &fat_vfs_proto,
.locals_dict = (mp_obj_dict_t*)&fat_vfs_locals_dict,
.locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict,
};

Wyświetl plik

@ -45,7 +45,7 @@
typedef void *bdev_t;
STATIC fs_user_mount_t *disk_get_device(void *bdev) {
return (fs_user_mount_t*)bdev;
return (fs_user_mount_t *)bdev;
}
/*-----------------------------------------------------------------------*/
@ -57,8 +57,7 @@ DRESULT disk_read (
BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to read (1..128) */
)
{
) {
fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) {
return RES_PARERR;
@ -78,8 +77,7 @@ DRESULT disk_write (
const BYTE *buff, /* Data to be written */
DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to write (1..128) */
)
{
) {
fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) {
return RES_PARERR;
@ -104,8 +102,7 @@ DRESULT disk_ioctl (
bdev_t pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
) {
fs_user_mount_t *vfs = disk_get_device(pdrv);
if (vfs == NULL) {
return RES_PARERR;
@ -130,24 +127,24 @@ DRESULT disk_ioctl (
return RES_OK;
case GET_SECTOR_COUNT: {
*((DWORD*)buff) = mp_obj_get_int(ret);
*((DWORD *)buff) = mp_obj_get_int(ret);
return RES_OK;
}
case GET_SECTOR_SIZE: {
if (ret == mp_const_none) {
// Default sector size
*((WORD*)buff) = 512;
*((WORD *)buff) = 512;
} else {
*((WORD*)buff) = mp_obj_get_int(ret);
*((WORD *)buff) = mp_obj_get_int(ret);
}
// need to store ssize because we use it in disk_read/disk_write
vfs->blockdev.block_size = *((WORD*)buff);
vfs->blockdev.block_size = *((WORD *)buff);
return RES_OK;
}
case GET_BLOCK_SIZE:
*((DWORD*)buff) = 1; // erase block size in units of sector size
*((DWORD *)buff) = 1; // erase block size in units of sector size
return RES_OK;
case IOCTL_INIT:
@ -161,7 +158,7 @@ DRESULT disk_ioctl (
} else {
stat = 0;
}
*((DSTATUS*)buff) = stat;
*((DSTATUS *)buff) = stat;
return RES_OK;
}

Wyświetl plik

@ -107,7 +107,7 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in);
if (request == MP_STREAM_SEEK) {
struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg;
struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg;
switch (s->whence) {
case 0: // SEEK_SET
@ -251,7 +251,7 @@ const mp_obj_type_t mp_type_vfs_fat_fileio = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_fat_fileio_stream_p,
.locals_dict = (mp_obj_dict_t*)&vfs_fat_rawfile_locals_dict,
.locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict,
};
#endif
@ -270,7 +270,7 @@ const mp_obj_type_t mp_type_vfs_fat_textio = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_fat_textio_stream_p,
.locals_dict = (mp_obj_dict_t*)&vfs_fat_rawfile_locals_dict,
.locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict,
};
// Factory function for I/O stream classes

Wyświetl plik

@ -44,13 +44,13 @@ static const mp_arg_t lfs_make_allowed_args[] = {
#include "lib/littlefs/lfs1.h"
#define LFS_BUILD_VERSION (1)
#define LFSx_MACRO(s) LFS1 ## s
#define LFSx_API(s) lfs1_ ## s
#define MP_VFS_LFSx(s) mp_vfs_lfs1_ ## s
#define LFSx_MACRO(s) LFS1##s
#define LFSx_API(s) lfs1_##s
#define MP_VFS_LFSx(s) mp_vfs_lfs1_##s
#define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs1_t
#define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs1_file_t
#define MP_TYPE_VFS_LFSx mp_type_vfs_lfs1
#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs1 ## s
#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs1##s
typedef struct _mp_obj_vfs_lfs1_t {
mp_obj_base_t base;
@ -90,13 +90,13 @@ mp_obj_t mp_vfs_lfs1_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode
#include "lib/littlefs/lfs2.h"
#define LFS_BUILD_VERSION (2)
#define LFSx_MACRO(s) LFS2 ## s
#define LFSx_API(s) lfs2_ ## s
#define MP_VFS_LFSx(s) mp_vfs_lfs2_ ## s
#define LFSx_MACRO(s) LFS2##s
#define LFSx_API(s) lfs2_##s
#define MP_VFS_LFSx(s) mp_vfs_lfs2_##s
#define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs2_t
#define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs2_file_t
#define MP_TYPE_VFS_LFSx mp_type_vfs_lfs2
#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs2 ## s
#define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs2##s
typedef struct _mp_obj_vfs_lfs2_t {
mp_obj_base_t base;

Wyświetl plik

@ -34,7 +34,7 @@
#include "py/mperrno.h"
#include "extmod/vfs.h"
STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API(config) *c, int cmd, int arg, bool must_return_int) {
STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API (config) * c, int cmd, int arg, bool must_return_int) {
mp_obj_t ret = mp_vfs_blockdev_ioctl(c->context, cmd, arg);
int ret_i = 0;
if (must_return_int || ret != mp_const_none) {
@ -43,27 +43,27 @@ STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API(config) *c, int cmd, int
return ret_i;
}
STATIC int MP_VFS_LFSx(dev_read)(const struct LFSx_API(config) *c, LFSx_API(block_t) block, LFSx_API(off_t) off, void *buffer, LFSx_API(size_t) size) {
STATIC int MP_VFS_LFSx(dev_read)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, void *buffer, LFSx_API(size_t) size) {
return mp_vfs_blockdev_read_ext(c->context, block, off, size, buffer);
}
STATIC int MP_VFS_LFSx(dev_prog)(const struct LFSx_API(config) *c, LFSx_API(block_t) block, LFSx_API(off_t) off, const void *buffer, LFSx_API(size_t) size) {
STATIC int MP_VFS_LFSx(dev_prog)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, const void *buffer, LFSx_API(size_t) size) {
return mp_vfs_blockdev_write_ext(c->context, block, off, size, buffer);
}
STATIC int MP_VFS_LFSx(dev_erase)(const struct LFSx_API(config) *c, LFSx_API(block_t) block) {
STATIC int MP_VFS_LFSx(dev_erase)(const struct LFSx_API (config) * c, LFSx_API(block_t) block) {
return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_BLOCK_ERASE, block, true);
}
STATIC int MP_VFS_LFSx(dev_sync)(const struct LFSx_API(config) *c) {
STATIC int MP_VFS_LFSx(dev_sync)(const struct LFSx_API (config) * c) {
return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_SYNC, 0, false);
}
STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx *self, mp_obj_t bdev, size_t read_size, size_t prog_size, size_t lookahead) {
STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx * self, mp_obj_t bdev, size_t read_size, size_t prog_size, size_t lookahead) {
self->blockdev.flags = MP_BLOCKDEV_FLAG_FREE_OBJ;
mp_vfs_blockdev_init(&self->blockdev, bdev);
struct LFSx_API(config) *config = &self->config;
struct LFSx_API (config) * config = &self->config;
memset(config, 0, sizeof(*config));
config->context = &self->blockdev;
@ -98,7 +98,7 @@ STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx *self, mp_obj_t bdev, size_
#endif
}
const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx *self, mp_obj_t path_in) {
const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx * self, mp_obj_t path_in) {
const char *path = mp_obj_str_get_str(path_in);
if (path[0] != '/') {
size_t l = vstr_len(&self->cur_dir);
@ -111,7 +111,7 @@ const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx *self, mp_obj_t path_in) {
return path;
}
STATIC mp_obj_t MP_VFS_LFSx(make_new)(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
STATIC mp_obj_t MP_VFS_LFSx(make_new)(const mp_obj_type_t * type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
mp_arg_val_t args[MP_ARRAY_SIZE(lfs_make_allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(lfs_make_allowed_args), lfs_make_allowed_args, args);
@ -147,7 +147,7 @@ STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(MP_VFS_LFSx(mkfs_obj), MP_ROM_PTR(&MP_VF
// Implementation of mp_vfs_lfs_file_open is provided in vfs_lfsx_file.c
STATIC MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(open_obj), MP_VFS_LFSx(file_open));
typedef struct MP_VFS_LFSx(_ilistdir_it_t) {
typedef struct MP_VFS_LFSx (_ilistdir_it_t) {
mp_obj_base_t base;
mp_fun_1_t iternext;
bool is_str;
@ -156,9 +156,9 @@ typedef struct MP_VFS_LFSx(_ilistdir_it_t) {
} MP_VFS_LFSx(ilistdir_it_t);
STATIC mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) {
MP_VFS_LFSx(ilistdir_it_t) *self = MP_OBJ_TO_PTR(self_in);
MP_VFS_LFSx(ilistdir_it_t) * self = MP_OBJ_TO_PTR(self_in);
struct LFSx_API(info) info;
struct LFSx_API (info) info;
for (;;) {
int ret = LFSx_API(dir_read)(&self->vfs->lfs, &self->dir, &info);
if (ret == 0) {
@ -166,7 +166,7 @@ STATIC mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) {
return MP_OBJ_STOP_ITERATION;
}
if (!(info.name[0] == '.' && (info.name[1] == '\0'
|| (info.name[1] == '.' && info.name[2] == '\0')))) {
|| (info.name[1] == '.' && info.name[2] == '\0')))) {
break;
}
}
@ -176,7 +176,7 @@ STATIC mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) {
if (self->is_str) {
t->items[0] = mp_obj_new_str(info.name, strlen(info.name));
} else {
t->items[0] = mp_obj_new_bytes((const byte*)info.name, strlen(info.name));
t->items[0] = mp_obj_new_bytes((const byte *)info.name, strlen(info.name));
}
t->items[1] = MP_OBJ_NEW_SMALL_INT(info.type == LFSx_MACRO(_TYPE_REG) ? MP_S_IFREG : MP_S_IFDIR);
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
@ -198,7 +198,7 @@ STATIC mp_obj_t MP_VFS_LFSx(ilistdir_func)(size_t n_args, const mp_obj_t *args)
path = vstr_null_terminated_str(&self->cur_dir);
}
MP_VFS_LFSx(ilistdir_it_t) *iter = m_new_obj(MP_VFS_LFSx(ilistdir_it_t));
MP_VFS_LFSx(ilistdir_it_t) * iter = m_new_obj(MP_VFS_LFSx(ilistdir_it_t));
iter->base.type = &mp_type_polymorph_iter;
iter->iternext = MP_VFS_LFSx(ilistdir_it_iternext);
iter->is_str = is_str_type;
@ -267,7 +267,7 @@ STATIC mp_obj_t MP_VFS_LFSx(chdir)(mp_obj_t self_in, mp_obj_t path_in) {
const char *path = MP_VFS_LFSx(make_path)(self, path_in);
if (path[1] != '\0') {
// Not at root, check it exists
struct LFSx_API(info) info;
struct LFSx_API (info) info;
int ret = LFSx_API(stat)(&self->lfs, path, &info);
if (ret < 0 || info.type != LFSx_MACRO(_TYPE_DIR)) {
mp_raise_OSError(-MP_ENOENT);
@ -305,7 +305,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(MP_VFS_LFSx(getcwd_obj), MP_VFS_LFSx(getcwd));
STATIC mp_obj_t MP_VFS_LFSx(stat)(mp_obj_t self_in, mp_obj_t path_in) {
MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in);
const char *path = mp_obj_str_get_str(path_in);
struct LFSx_API(info) info;
struct LFSx_API (info) info;
int ret = LFSx_API(stat)(&self->lfs, path, &info);
if (ret < 0) {
mp_raise_OSError(-ret);
@ -329,7 +329,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(stat_obj), MP_VFS_LFSx(stat));
STATIC int LFSx_API(traverse_cb)(void *data, LFSx_API(block_t) bl) {
(void)bl;
uint32_t *n = (uint32_t*)data;
uint32_t *n = (uint32_t *)data;
*n += 1;
return LFSx_MACRO(_ERR_OK);
}
@ -399,7 +399,7 @@ STATIC MP_DEFINE_CONST_DICT(MP_VFS_LFSx(locals_dict), MP_VFS_LFSx(locals_dict_ta
STATIC mp_import_stat_t MP_VFS_LFSx(import_stat)(void *self_in, const char *path) {
MP_OBJ_VFS_LFSx *self = self_in;
struct LFSx_API(info) info;
struct LFSx_API (info) info;
int ret = LFSx_API(stat)(&self->lfs, path, &info);
if (ret == 0) {
if (info.type == LFSx_MACRO(_TYPE_REG)) {
@ -424,5 +424,5 @@ const mp_obj_type_t MP_TYPE_VFS_LFSx = {
#endif
.make_new = MP_VFS_LFSx(make_new),
.protocol = &MP_VFS_LFSx(proto),
.locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(locals_dict),
.locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(locals_dict),
};

Wyświetl plik

@ -32,13 +32,13 @@
#include "py/mperrno.h"
#include "extmod/vfs.h"
STATIC void MP_VFS_LFSx(check_open)(MP_OBJ_VFS_LFSx_FILE *self) {
STATIC void MP_VFS_LFSx(check_open)(MP_OBJ_VFS_LFSx_FILE * self) {
if (self->vfs == NULL) {
mp_raise_ValueError(NULL);
}
}
STATIC void MP_VFS_LFSx(file_print)(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
STATIC void MP_VFS_LFSx(file_print)(const mp_print_t * print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)self_in;
(void)kind;
mp_printf(print, "<io.%s>", mp_obj_get_type_str(self_in));
@ -147,7 +147,7 @@ STATIC mp_uint_t MP_VFS_LFSx(file_ioctl)(mp_obj_t self_in, mp_uint_t request, ui
}
if (request == MP_STREAM_SEEK) {
struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg;
struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg;
int res = LFSx_API(file_seek)(&self->vfs->lfs, &self->file, s->offset, s->whence);
if (res < 0) {
*errcode = -res;
@ -214,7 +214,7 @@ const mp_obj_type_t MP_TYPE_VFS_LFSx_(_fileio) = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &MP_VFS_LFSx(fileio_stream_p),
.locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(file_locals_dict),
.locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict),
};
#endif
@ -232,5 +232,5 @@ const mp_obj_type_t MP_TYPE_VFS_LFSx_(_textio) = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &MP_VFS_LFSx(textio_stream_p),
.locals_dict = (mp_obj_dict_t*)&MP_VFS_LFSx(file_locals_dict),
.locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict),
};

Wyświetl plik

@ -64,7 +64,7 @@ STATIC mp_obj_t vfs_posix_get_path_obj(mp_obj_vfs_posix_t *self, mp_obj_t path)
}
}
STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char*)) {
STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char *)) {
mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in);
int ret = f(vfs_posix_get_path_str(self, path_in));
if (ret != 0) {
@ -193,7 +193,7 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) {
if (self->is_str) {
t->items[0] = mp_obj_new_str(fn, strlen(fn));
} else {
t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn));
t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn));
}
#ifdef _DIRENT_HAVE_D_TYPE
@ -382,7 +382,7 @@ const mp_obj_type_t mp_type_vfs_posix = {
.name = MP_QSTR_VfsPosix,
.make_new = vfs_posix_make_new,
.protocol = &vfs_posix_proto,
.locals_dict = (mp_obj_dict_t*)&vfs_posix_locals_dict,
.locals_dict = (mp_obj_dict_t *)&vfs_posix_locals_dict,
};
#endif // MICROPY_VFS_POSIX

Wyświetl plik

@ -79,7 +79,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_
case '+':
mode_rw = O_RDWR;
break;
#if MICROPY_PY_IO_FILEIO
#if MICROPY_PY_IO_FILEIO
// If we don't have io.FileIO, then files are in text mode implicitly
case 'b':
type = &mp_type_vfs_posix_fileio;
@ -87,7 +87,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_
case 't':
type = &mp_type_vfs_posix_textio;
break;
#endif
#endif
}
}
@ -189,7 +189,7 @@ STATIC mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_
}
return 0;
case MP_STREAM_SEEK: {
struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg;
struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
MP_THREAD_GIL_EXIT();
off_t off = lseek(o->fd, s->offset, s->whence);
MP_THREAD_GIL_ENTER();
@ -246,7 +246,7 @@ const mp_obj_type_t mp_type_vfs_posix_fileio = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_posix_fileio_stream_p,
.locals_dict = (mp_obj_dict_t*)&vfs_posix_rawfile_locals_dict,
.locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict,
};
#endif
@ -265,10 +265,10 @@ const mp_obj_type_t mp_type_vfs_posix_textio = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_posix_textio_stream_p,
.locals_dict = (mp_obj_dict_t*)&vfs_posix_rawfile_locals_dict,
.locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict,
};
const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO};
const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO};
const mp_obj_vfs_posix_file_t mp_sys_stdout_obj = {{&mp_type_textio}, STDOUT_FILENO};
const mp_obj_vfs_posix_file_t mp_sys_stderr_obj = {{&mp_type_textio}, STDERR_FILENO};

Wyświetl plik

@ -42,7 +42,7 @@ typedef struct _mp_reader_vfs_t {
} mp_reader_vfs_t;
STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) {
mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data;
mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data;
if (reader->pos >= reader->len) {
if (reader->len < sizeof(reader->buf)) {
return MP_READER_EOF;
@ -64,7 +64,7 @@ STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) {
}
STATIC void mp_reader_vfs_close(void *data) {
mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data;
mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data;
mp_stream_close(reader->file);
m_del_obj(mp_reader_vfs_t, reader);
}
@ -72,7 +72,7 @@ STATIC void mp_reader_vfs_close(void *data) {
void mp_reader_new_file(mp_reader_t *reader, const char *filename) {
mp_reader_vfs_t *rf = m_new_obj(mp_reader_vfs_t);
mp_obj_t arg = mp_obj_new_str(filename, strlen(filename));
rf->file = mp_vfs_open(1, &arg, (mp_map_t*)&mp_const_empty_map);
rf->file = mp_vfs_open(1, &arg, (mp_map_t *)&mp_const_empty_map);
int errcode;
rf->len = mp_stream_rw(rf->file, rf->buf, sizeof(rf->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE);
if (errcode != 0) {

Wyświetl plik

@ -27,13 +27,13 @@
#include "extmod/virtpin.h"
int mp_virtual_pin_read(mp_obj_t pin) {
mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin);
mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol;
mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin);
mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol;
return pin_p->ioctl(pin, MP_PIN_READ, 0, NULL);
}
void mp_virtual_pin_write(mp_obj_t pin, int value) {
mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin);
mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol;
mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin);
mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol;
pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL);
}

Wyświetl plik

@ -1 +1 @@
freeze('.', ('webrepl.py', 'webrepl_setup.py', 'websocket_helper.py',))
freeze(".", ("webrepl.py", "webrepl_setup.py", "websocket_helper.py",))

Wyświetl plik

@ -9,6 +9,7 @@ import _webrepl
listen_s = None
client_s = None
def setup_conn(port, accept_handler):
global listen_s
listen_s = socket.socket()
@ -44,7 +45,7 @@ def accept_conn(listen_sock):
ws = _webrepl._webrepl(ws)
cl.setblocking(False)
# notify REPL on socket incoming data (ESP32/ESP8266-only)
if hasattr(uos, 'dupterm_notify'):
if hasattr(uos, "dupterm_notify"):
cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify)
uos.dupterm(ws)
@ -63,6 +64,7 @@ def start(port=8266, password=None):
if password is None:
try:
import webrepl_cfg
_webrepl.password(webrepl_cfg.PASS)
setup_conn(port, accept_conn)
print("Started webrepl in normal mode")

Wyświetl plik

@ -1,20 +1,24 @@
import sys
#import uos as os
# import uos as os
import os
import machine
RC = "./boot.py"
CONFIG = "./webrepl_cfg.py"
def input_choice(prompt, choices):
while 1:
resp = input(prompt)
if resp in choices:
return resp
def getpass(prompt):
return input(prompt)
def input_pass():
while 1:
passwd1 = getpass("New password (4-9 chars): ")
@ -77,7 +81,9 @@ def main():
if resp == "E":
if exists(CONFIG):
resp2 = input_choice("Would you like to change WebREPL password? (y/n) ", ("y", "n", ""))
resp2 = input_choice(
"Would you like to change WebREPL password? (y/n) ", ("y", "n", "")
)
else:
print("To enable WebREPL, you must set password for it")
resp2 = "y"
@ -87,7 +93,6 @@ def main():
with open(CONFIG, "w") as f:
f.write("PASS = %r\n" % passwd)
if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
print("No further action required")
sys.exit()
@ -99,4 +104,5 @@ def main():
if resp == "y":
machine.reset()
main()

Wyświetl plik

@ -1,4 +1,5 @@
import sys
try:
import ubinascii as binascii
except:
@ -10,10 +11,11 @@ except:
DEBUG = 0
def server_handshake(sock):
clr = sock.makefile("rwb", 0)
l = clr.readline()
#sys.stdout.write(repr(l))
# sys.stdout.write(repr(l))
webkey = None
@ -23,11 +25,11 @@ def server_handshake(sock):
raise OSError("EOF in headers")
if l == b"\r\n":
break
# sys.stdout.write(l)
# sys.stdout.write(l)
h, v = [x.strip() for x in l.split(b":", 1)]
if DEBUG:
print((h, v))
if h == b'Sec-WebSocket-Key':
if h == b"Sec-WebSocket-Key":
webkey = v
if not webkey:
@ -43,11 +45,13 @@ def server_handshake(sock):
if DEBUG:
print("respkey:", respkey)
sock.send(b"""\
sock.send(
b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: """)
Sec-WebSocket-Accept: """
)
sock.send(respkey)
sock.send("\r\n\r\n")
@ -57,18 +61,22 @@ Sec-WebSocket-Accept: """)
# servers.
def client_handshake(sock):
cl = sock.makefile("rwb", 0)
cl.write(b"""\
cl.write(
b"""\
GET / HTTP/1.1\r
Host: echo.websocket.org\r
Connection: Upgrade\r
Upgrade: websocket\r
Sec-WebSocket-Key: foo\r
\r
""")
"""
)
l = cl.readline()
# print(l)
# print(l)
while 1:
l = cl.readline()
if l == b"\r\n":
break
# sys.stdout.write(l)

Wyświetl plik

@ -99,7 +99,7 @@ static int dhcp_socket_new_dgram(struct udp_pcb **udp, void *cb_data, udp_recv_f
}
// Register callback
udp_recv(*udp, cb_udp_recv, (void*)cb_data);
udp_recv(*udp, cb_udp_recv, (void *)cb_data);
return 0; // success
}
@ -202,7 +202,7 @@ static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p,
dhcp_msg.op = DHCPOFFER;
memcpy(&dhcp_msg.yiaddr, &d->ip.addr, 4);
uint8_t *opt = (uint8_t*)&dhcp_msg.options;
uint8_t *opt = (uint8_t *)&dhcp_msg.options;
opt += 4; // assume magic cookie: 99, 130, 83, 99
switch (opt[2]) {
@ -281,7 +281,7 @@ static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p,
opt_write_u32(&opt, DHCP_OPT_DNS, DEFAULT_DNS); // can have mulitple addresses
opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S);
*opt++ = DHCP_OPT_END;
dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t*)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t *)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
ignore_request:
pbuf_free(p);

Wyświetl plik

@ -64,7 +64,7 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian
}
const char *s = addr_str;
const char *s_top = addr_str + addr_len;
for (mp_uint_t i = 3 ; ; i--) {
for (mp_uint_t i = 3; ; i--) {
mp_uint_t val = 0;
for (; s < s_top && *s != '.'; s++) {
val = val * 10 + *s - '0';

Wyświetl plik

@ -44,10 +44,14 @@ static void dump_hex_bytes(const mp_print_t *print, size_t len, const uint8_t *b
static const char *ethertype_str(uint16_t type) {
// A value between 0x0000 - 0x05dc (inclusive) indicates a length, not type
switch (type) {
case 0x0800: return "IPv4";
case 0x0806: return "ARP";
case 0x86dd: return "IPv6";
default: return NULL;
case 0x0800:
return "IPv4";
case 0x0806:
return "ARP";
case 0x86dd:
return "IPv6";
default:
return NULL;
}
}
@ -113,14 +117,30 @@ void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t
buf += n;
mp_printf(print, " opts:");
switch (buf[6]) {
case 1: mp_printf(print, " DISCOVER"); break;
case 2: mp_printf(print, " OFFER"); break;
case 3: mp_printf(print, " REQUEST"); break;
case 4: mp_printf(print, " DECLINE"); break;
case 5: mp_printf(print, " ACK"); break;
case 6: mp_printf(print, " NACK"); break;
case 7: mp_printf(print, " RELEASE"); break;
case 8: mp_printf(print, " INFORM"); break;
case 1:
mp_printf(print, " DISCOVER");
break;
case 2:
mp_printf(print, " OFFER");
break;
case 3:
mp_printf(print, " REQUEST");
break;
case 4:
mp_printf(print, " DECLINE");
break;
case 5:
mp_printf(print, " ACK");
break;
case 6:
mp_printf(print, " NACK");
break;
case 7:
mp_printf(print, " RELEASE");
break;
case 8:
mp_printf(print, " INFORM");
break;
}
}
} else {

Wyświetl plik

@ -36,11 +36,11 @@
#define LEAPOCH ((31 + 29) * 86400)
#define DAYS_PER_400Y (365*400 + 97)
#define DAYS_PER_100Y (365*100 + 24)
#define DAYS_PER_4Y (365*4 + 1)
#define DAYS_PER_400Y (365 * 400 + 97)
#define DAYS_PER_100Y (365 * 100 + 24)
#define DAYS_PER_4Y (365 * 4 + 1)
STATIC const uint16_t days_since_jan1[]= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
STATIC const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
bool timeutils_is_leap_year(mp_uint_t year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;

Wyświetl plik

@ -28,14 +28,14 @@
#define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H
typedef struct _timeutils_struct_time_t {
uint16_t tm_year; // i.e. 2014
uint8_t tm_mon; // 1..12
uint8_t tm_mday; // 1..31
uint8_t tm_hour; // 0..23
uint8_t tm_min; // 0..59
uint8_t tm_sec; // 0..59
uint8_t tm_wday; // 0..6 0 = Monday
uint16_t tm_yday; // 1..366
uint16_t tm_year; // i.e. 2014
uint8_t tm_mon; // 1..12
uint8_t tm_mday; // 1..31
uint8_t tm_hour; // 0..23
uint8_t tm_min; // 0..59
uint8_t tm_sec; // 0..59
uint8_t tm_wday; // 0..6 0 = Monday
uint16_t tm_yday; // 1..366
} timeutils_struct_time_t;
bool timeutils_is_leap_year(mp_uint_t year);

Wyświetl plik

@ -52,7 +52,7 @@ const mp_arg_t mp_irq_init_args[] = {
mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) {
mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1);
self->base.type = &mp_irq_type;
self->methods = (mp_irq_methods_t*)methods;
self->methods = (mp_irq_methods_t *)methods;
self->parent = parent;
self->handler = mp_const_none;
self->ishard = false;
@ -120,5 +120,5 @@ const mp_obj_type_t mp_irq_type = {
{ &mp_type_type },
.name = MP_QSTR_irq,
.call = mp_irq_call,
.locals_dict = (mp_obj_dict_t*)&mp_irq_locals_dict,
.locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict,
};

Wyświetl plik

@ -89,7 +89,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input
} else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) {
lex = mp_lexer_new_from_file(source);
} else {
lex = (mp_lexer_t*)source;
lex = (mp_lexer_t *)source;
}
// source is a lexer, parse and compile the script
qstr source_name = lex->source_name;
@ -122,7 +122,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input
mp_hal_stdout_tx_strn("\x04", 1);
}
// check for SystemExit
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
// at the moment, the value of SystemExit is unused
ret = pyexec_system_exit;
} else {
@ -141,8 +141,8 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input
size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
printf("qstr:\n n_pool=%u\n n_qstr=%u\n "
"n_str_data_bytes=%u\n n_total_bytes=%u\n",
(unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
"n_str_data_bytes=%u\n n_total_bytes=%u\n",
(unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
}
#if MICROPY_ENABLE_GC
@ -316,10 +316,10 @@ STATIC int pyexec_friendly_repl_process_char(int c) {
} else {
if (ret == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
repl.cont_line = false;
goto input_restart;
// cancel everything
mp_hal_stdout_tx_str("\r\n");
repl.cont_line = false;
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// stop entering compound statement
goto exec;
@ -335,13 +335,13 @@ STATIC int pyexec_friendly_repl_process_char(int c) {
return 0;
}
exec: ;
exec:;
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
input_restart:
input_restart:
vstr_reset(MP_STATE_VM(repl_line));
repl.cont_line = false;
repl.paste_mode = false;
@ -419,11 +419,11 @@ int pyexec_friendly_repl(void) {
vstr_t line;
vstr_init(&line, 32);
#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
// in host mode, we enable the LCD for the repl
mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD")));
mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true);
#endif
#endif
friendly_repl_reset:
mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");

Wyświetl plik

@ -65,7 +65,7 @@ STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *er
if (c == '\r') {
c = '\n';
}
((byte*)buf)[i] = c;
((byte *)buf)[i] = c;
}
return size;
} else {
@ -103,9 +103,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stdio_obj___exit___obj, 4, 4, stdio_o
// TODO gc hook to close the file if not already closed
STATIC const mp_rom_map_elem_t stdio_locals_dict_table[] = {
#if MICROPY_PY_SYS_STDIO_BUFFER
#if MICROPY_PY_SYS_STDIO_BUFFER
{ MP_ROM_QSTR(MP_QSTR_buffer), MP_ROM_PTR(&stdio_buffer_obj) },
#endif
#endif
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)},
@ -134,7 +134,7 @@ STATIC const mp_obj_type_t stdio_obj_type = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &stdio_obj_stream_p,
.locals_dict = (mp_obj_dict_t*)&stdio_locals_dict,
.locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
};
const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN};
@ -144,7 +144,7 @@ const sys_stdio_obj_t mp_sys_stderr_obj = {{&stdio_obj_type}, .fd = STDIO_FD_ERR
#if MICROPY_PY_SYS_STDIO_BUFFER
STATIC mp_uint_t stdio_buffer_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
for (uint i = 0; i < size; i++) {
((byte*)buf)[i] = mp_hal_stdin_rx_chr();
((byte *)buf)[i] = mp_hal_stdin_rx_chr();
}
return size;
}
@ -168,7 +168,7 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = {
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &stdio_buffer_obj_stream_p,
.locals_dict = (mp_obj_dict_t*)&stdio_locals_dict,
.locals_dict = (mp_obj_dict_t *)&stdio_locals_dict,
};
STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused

Wyświetl plik

@ -49,20 +49,20 @@ STATIC void gc_helper_get_regs(regs_t arr) {
register long r13 asm ("r13");
register long r14 asm ("r14");
register long r15 asm ("r15");
#ifdef __clang__
#ifdef __clang__
// TODO:
// This is dirty workaround for Clang. It tries to get around
// uncompliant (wrt to GCC) behavior of handling register variables.
// Application of this patch here is random, and done only to unbreak
// MacOS build. Better, cross-arch ways to deal with Clang issues should
// be found.
asm("" : "=r"(rbx));
asm("" : "=r"(rbp));
asm("" : "=r"(r12));
asm("" : "=r"(r13));
asm("" : "=r"(r14));
asm("" : "=r"(r15));
#endif
asm ("" : "=r" (rbx));
asm ("" : "=r" (rbp));
asm ("" : "=r" (r12));
asm ("" : "=r" (r13));
asm ("" : "=r" (r14));
asm ("" : "=r" (r15));
#endif
arr[0] = rbx;
arr[1] = rbp;
arr[2] = r12;
@ -141,7 +141,7 @@ void gc_collect(void) {
regs_t regs;
gc_helper_get_regs(regs);
// GC stack (and regs because we captured them)
void **regs_ptr = (void**)(void*)&regs;
void **regs_ptr = (void **)(void *)&regs;
gc_collect_root(regs_ptr, ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)&regs) / sizeof(mp_uint_t));
gc_collect_end();
}

Wyświetl plik

@ -45,7 +45,7 @@ mp_uint_t mp_verbose_flag = 0;
// Heap size of GC heap (if enabled)
// Make it larger on a 64 bit machine, because pointers are larger.
long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4);
long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4);
STATIC void stderr_print_strn(void *env, const char *str, mp_uint_t len) {
(void)env;
@ -97,34 +97,34 @@ STATIC int compile_and_save(const char *file, const char *output_file, const cha
STATIC int usage(char **argv) {
printf(
"usage: %s [<opts>] [-X <implopt>] <input filename>\n"
"Options:\n"
"--version : show version information\n"
"-o : output file for compiled bytecode (defaults to input with .mpy extension)\n"
"-s : source filename to embed in the compiled bytecode (defaults to input file)\n"
"-v : verbose (trace various operations); can be multiple\n"
"-O[N] : apply bytecode optimizations of level N\n"
"\n"
"Target specific options:\n"
"-msmall-int-bits=number : set the maximum bits used to encode a small-int\n"
"-mno-unicode : don't support unicode in compiled strings\n"
"-mcache-lookup-bc : cache map lookups in the bytecode\n"
"-march=<arch> : set architecture for native emitter; x86, x64, armv6, armv7m, armv7em, armv7emsp, armv7emdp, xtensa, xtensawin\n"
"\n"
"Implementation specific options:\n", argv[0]
);
"usage: %s [<opts>] [-X <implopt>] <input filename>\n"
"Options:\n"
"--version : show version information\n"
"-o : output file for compiled bytecode (defaults to input with .mpy extension)\n"
"-s : source filename to embed in the compiled bytecode (defaults to input file)\n"
"-v : verbose (trace various operations); can be multiple\n"
"-O[N] : apply bytecode optimizations of level N\n"
"\n"
"Target specific options:\n"
"-msmall-int-bits=number : set the maximum bits used to encode a small-int\n"
"-mno-unicode : don't support unicode in compiled strings\n"
"-mcache-lookup-bc : cache map lookups in the bytecode\n"
"-march=<arch> : set architecture for native emitter; x86, x64, armv6, armv7m, armv7em, armv7emsp, armv7emdp, xtensa, xtensawin\n"
"\n"
"Implementation specific options:\n", argv[0]
);
int impl_opts_cnt = 0;
printf(
#if MICROPY_EMIT_NATIVE
" emit={bytecode,native,viper} -- set the default code emitter\n"
#else
" emit=bytecode -- set the default code emitter\n"
#endif
);
#if MICROPY_EMIT_NATIVE
" emit={bytecode,native,viper} -- set the default code emitter\n"
#else
" emit=bytecode -- set the default code emitter\n"
#endif
);
impl_opts_cnt++;
printf(
" heapsize=<n> -- set the heap size for the GC (default %ld)\n"
, heap_size);
" heapsize=<n> -- set the heap size for the GC (default %ld)\n"
, heap_size);
impl_opts_cnt++;
if (impl_opts_cnt == 0) {
@ -190,9 +190,9 @@ MP_NOINLINE int main_(int argc, char **argv) {
gc_init(heap, heap + heap_size);
mp_init();
#ifdef _WIN32
#ifdef _WIN32
set_fmode_binary();
#endif
#endif
mp_obj_list_init(mp_sys_path, 0);
mp_obj_list_init(mp_sys_argv, 0);
@ -241,7 +241,8 @@ MP_NOINLINE int main_(int argc, char **argv) {
MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf;
} else {
MP_STATE_VM(mp_optimise_value) = 0;
for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++);
for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {;
}
}
} else if (strcmp(argv[a], "-o") == 0) {
if (a + 1 >= argc) {

Wyświetl plik

@ -141,7 +141,7 @@ typedef long mp_off_t;
#else
#define MP_SSIZE_MAX _I32_MAX
#endif
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)(p)) //Avoid compiler warning about different const qualifiers
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)(p)) //Avoid compiler warning about different const qualifiers
#define restrict
#define inline __inline
#define alignof(t) __alignof(t)
@ -152,11 +152,11 @@ typedef long mp_off_t;
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#ifdef _WIN64
#define SSIZE_MAX _I64_MAX
typedef __int64 ssize_t;
typedef __int64 ssize_t;
#else
#define SSIZE_MAX _I32_MAX
typedef int ssize_t;
typedef int ssize_t;
#endif
typedef mp_off_t off_t;
typedef mp_off_t off_t;
#endif

Wyświetl plik

@ -44,11 +44,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) {
while (1);
while (1) {
;
}
}
void NORETURN __fatal_error(const char *msg) {
while (1);
while (1) {
;
}
}
#ifndef NDEBUG
@ -71,26 +75,63 @@ int _fstat() {return 0;}
int _isatty() {return 0;}
*/
void *malloc(size_t n) {return NULL;}
void *calloc(size_t nmemb, size_t size) {return NULL;}
void *realloc(void *ptr, size_t size) {return NULL;}
void free(void *p) {}
int printf(const char *m, ...) {return 0;}
void *memcpy(void *dest, const void *src, size_t n) {return NULL;}
int memcmp(const void *s1, const void *s2, size_t n) {return 0;}
void *memmove(void *dest, const void *src, size_t n) {return NULL;}
void *memset(void *s, int c, size_t n) {return NULL;}
int strcmp(const char *s1, const char* s2) {return 0;}
int strncmp(const char *s1, const char* s2, size_t n) {return 0;}
size_t strlen(const char *s) {return 0;}
char *strcat(char *dest, const char *src) {return NULL;}
char *strchr(const char *dest, int c) {return NULL;}
void *malloc(size_t n) {
return NULL;
}
void *calloc(size_t nmemb, size_t size) {
return NULL;
}
void *realloc(void *ptr, size_t size) {
return NULL;
}
void free(void *p) {
}
int printf(const char *m, ...) {
return 0;
}
void *memcpy(void *dest, const void *src, size_t n) {
return NULL;
}
int memcmp(const void *s1, const void *s2, size_t n) {
return 0;
}
void *memmove(void *dest, const void *src, size_t n) {
return NULL;
}
void *memset(void *s, int c, size_t n) {
return NULL;
}
int strcmp(const char *s1, const char *s2) {
return 0;
}
int strncmp(const char *s1, const char *s2, size_t n) {
return 0;
}
size_t strlen(const char *s) {
return 0;
}
char *strcat(char *dest, const char *src) {
return NULL;
}
char *strchr(const char *dest, int c) {
return NULL;
}
#include <stdarg.h>
int vprintf(const char *format, va_list ap) {return 0;}
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {return 0;}
int vprintf(const char *format, va_list ap) {
return 0;
}
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {
return 0;
}
#undef putchar
int putchar(int c) {return 0;}
int puts(const char *s) {return 0;}
int putchar(int c) {
return 0;
}
int puts(const char *s) {
return 0;
}
void _start(void) {main(0, NULL);}
void _start(void) {
main(0, NULL);
}

Wyświetl plik

@ -49,7 +49,7 @@
// type definitions for the specific machine
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
#define UINT_FMT "%lu"
#define INT_FMT "%ld"

Wyświetl plik

@ -8,20 +8,22 @@ import sys
import csv
SUPPORTED_AFS = { 'UART': ('TX', 'RX', 'RTS', 'CTS'),
'SPI': ('CLK', 'MOSI', 'MISO', 'CS0'),
#'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'),
'I2C': ('SDA', 'SCL'),
'TIM': ('PWM'),
'SD': ('CLK', 'CMD', 'DAT0'),
'ADC': ('CH0', 'CH1', 'CH2', 'CH3')
}
SUPPORTED_AFS = {
"UART": ("TX", "RX", "RTS", "CTS"),
"SPI": ("CLK", "MOSI", "MISO", "CS0"),
#'I2S': ('CLK', 'FS', 'DAT0', 'DAT1'),
"I2C": ("SDA", "SCL"),
"TIM": ("PWM"),
"SD": ("CLK", "CMD", "DAT0"),
"ADC": ("CH0", "CH1", "CH2", "CH3"),
}
def parse_port_pin(name_str):
"""Parses a string and returns a (port, gpio_bit) tuple."""
if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 characters")
if name_str[:2] != 'GP':
if name_str[:2] != "GP":
raise ValueError("Expecting pin name to start with GP")
if not name_str[2:].isdigit():
raise ValueError("Expecting numeric GPIO number")
@ -32,6 +34,7 @@ def parse_port_pin(name_str):
class AF:
"""Holds the description of an alternate function"""
def __init__(self, name, idx, fn, unit, type):
self.name = name
self.idx = idx
@ -42,11 +45,16 @@ class AF:
self.type = type
def print(self):
print (' AF({:16s}, {:4d}, {:8s}, {:4d}, {:8s}), // {}'.format(self.name, self.idx, self.fn, self.unit, self.type, self.name))
print(
" AF({:16s}, {:4d}, {:8s}, {:4d}, {:8s}), // {}".format(
self.name, self.idx, self.fn, self.unit, self.type, self.name
)
)
class Pin:
"""Holds the information associated with a pin."""
def __init__(self, name, port, gpio_bit, pin_num):
self.name = name
self.port = port
@ -59,25 +67,37 @@ class Pin:
self.afs.append(af)
def print(self):
print('// {}'.format(self.name))
print("// {}".format(self.name))
if len(self.afs):
print('const pin_af_t pin_{}_af[] = {{'.format(self.name))
print("const pin_af_t pin_{}_af[] = {{".format(self.name))
for af in self.afs:
af.print()
print('};')
print('pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, pin_{}_af, {});\n'.format(
self.name, self.name, self.port, self.gpio_bit, self.pin_num, self.name, len(self.afs)))
print("};")
print(
"pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, pin_{}_af, {});\n".format(
self.name,
self.name,
self.port,
self.gpio_bit,
self.pin_num,
self.name,
len(self.afs),
)
)
else:
print('pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, NULL, 0);\n'.format(
self.name, self.name, self.port, self.gpio_bit, self.pin_num))
print(
"pin_obj_t pin_{:4s} = PIN({:6s}, {:1d}, {:3d}, {:2d}, NULL, 0);\n".format(
self.name, self.name, self.port, self.gpio_bit, self.pin_num
)
)
def print_header(self, hdr_file):
hdr_file.write('extern pin_obj_t pin_{:s};\n'.format(self.name))
hdr_file.write("extern pin_obj_t pin_{:s};\n".format(self.name))
class Pins:
def __init__(self):
self.board_pins = [] # list of pin objects
self.board_pins = [] # list of pin objects
def find_pin(self, port, gpio_bit):
for pin in self.board_pins:
@ -95,7 +115,7 @@ class Pins:
return pin
def parse_af_file(self, filename, pin_col, pinname_col, af_start_col):
with open(filename, 'r') as csvfile:
with open(filename, "r") as csvfile:
rows = csv.reader(csvfile)
for row in rows:
try:
@ -103,16 +123,18 @@ class Pins:
except:
continue
if not row[pin_col].isdigit():
raise ValueError("Invalid pin number {:s} in row {:s}".format(row[pin_col]), row)
raise ValueError(
"Invalid pin number {:s} in row {:s}".format(row[pin_col]), row
)
# Pin numbers must start from 0 when used with the TI API
pin_num = int(row[pin_col]) - 1;
pin_num = int(row[pin_col]) - 1
pin = Pin(row[pinname_col], port_num, gpio_bit, pin_num)
self.board_pins.append(pin)
af_idx = 0
for af in row[af_start_col:]:
af_splitted = af.split('_')
fn_name = af_splitted[0].rstrip('0123456789')
if fn_name in SUPPORTED_AFS:
af_splitted = af.split("_")
fn_name = af_splitted[0].rstrip("0123456789")
if fn_name in SUPPORTED_AFS:
type_name = af_splitted[1]
if type_name in SUPPORTED_AFS[fn_name]:
unit_idx = af_splitted[0][-1]
@ -120,7 +142,7 @@ class Pins:
af_idx += 1
def parse_board_file(self, filename, cpu_pin_col):
with open(filename, 'r') as csvfile:
with open(filename, "r") as csvfile:
rows = csv.reader(csvfile)
for row in rows:
# Pin numbers must start from 0 when used with the TI API
@ -132,29 +154,39 @@ class Pins:
pin.board_pin = True
def print_named(self, label, pins):
print('')
print('STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{'.format(label))
print("")
print(
"STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{".format(label)
)
for pin in pins:
if pin.board_pin:
print(' {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},'.format(pin.name, pin.name))
print('};')
print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label));
print(
" {{ MP_ROM_QSTR(MP_QSTR_{:6s}), MP_ROM_PTR(&pin_{:6s}) }},".format(
pin.name, pin.name
)
)
print("};")
print(
"MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);".format(
label, label
)
)
def print(self):
for pin in self.board_pins:
if pin.board_pin:
pin.print()
self.print_named('board', self.board_pins)
print('')
self.print_named("board", self.board_pins)
print("")
def print_header(self, hdr_filename):
with open(hdr_filename, 'wt') as hdr_file:
with open(hdr_filename, "wt") as hdr_file:
for pin in self.board_pins:
if pin.board_pin:
pin.print_header(hdr_file)
def print_qstr(self, qstr_filename):
with open(qstr_filename, 'wt') as qstr_file:
with open(qstr_filename, "wt") as qstr_file:
pin_qstr_set = set([])
af_qstr_set = set([])
for pin in self.board_pins:
@ -162,67 +194,69 @@ class Pins:
pin_qstr_set |= set([pin.name])
for af in pin.afs:
af_qstr_set |= set([af.name])
print('// Board pins', file=qstr_file)
print("// Board pins", file=qstr_file)
for qstr in sorted(pin_qstr_set):
print('Q({})'.format(qstr), file=qstr_file)
print('\n// Pin AFs', file=qstr_file)
print("Q({})".format(qstr), file=qstr_file)
print("\n// Pin AFs", file=qstr_file)
for qstr in sorted(af_qstr_set):
print('Q({})'.format(qstr), file=qstr_file)
print("Q({})".format(qstr), file=qstr_file)
def main():
parser = argparse.ArgumentParser(
prog="make-pins.py",
usage="%(prog)s [options] [command]",
description="Generate board specific pin file"
description="Generate board specific pin file",
)
parser.add_argument(
"-a", "--af",
"-a",
"--af",
dest="af_filename",
help="Specifies the alternate function file for the chip",
default="cc3200_af.csv"
default="cc3200_af.csv",
)
parser.add_argument(
"-b", "--board",
dest="board_filename",
help="Specifies the board file",
"-b", "--board", dest="board_filename", help="Specifies the board file",
)
parser.add_argument(
"-p", "--prefix",
"-p",
"--prefix",
dest="prefix_filename",
help="Specifies beginning portion of generated pins file",
default="cc3200_prefix.c"
default="cc3200_prefix.c",
)
parser.add_argument(
"-q", "--qstr",
"-q",
"--qstr",
dest="qstr_filename",
help="Specifies name of generated qstr header file",
default="build/pins_qstr.h"
default="build/pins_qstr.h",
)
parser.add_argument(
"-r", "--hdr",
"-r",
"--hdr",
dest="hdr_filename",
help="Specifies name of generated pin header file",
default="build/pins.h"
default="build/pins.h",
)
args = parser.parse_args(sys.argv[1:])
pins = Pins()
print('// This file was automatically generated by make-pins.py')
print('//')
print("// This file was automatically generated by make-pins.py")
print("//")
if args.af_filename:
print('// --af {:s}'.format(args.af_filename))
print("// --af {:s}".format(args.af_filename))
pins.parse_af_file(args.af_filename, 0, 1, 3)
if args.board_filename:
print('// --board {:s}'.format(args.board_filename))
print("// --board {:s}".format(args.board_filename))
pins.parse_board_file(args.board_filename, 1)
if args.prefix_filename:
print('// --prefix {:s}'.format(args.prefix_filename))
print('')
with open(args.prefix_filename, 'r') as prefix_file:
print("// --prefix {:s}".format(args.prefix_filename))
print("")
with open(args.prefix_filename, "r") as prefix_file:
print(prefix_file.read())
pins.print()
pins.print_qstr(args.qstr_filename)

Wyświetl plik

@ -68,7 +68,7 @@ DWORD get_fattime(void) {
timeutils_struct_time_t tm;
timeutils_seconds_since_2000_to_struct_time(pyb_rtc_get_seconds(), &tm);
return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21) |
((tm.tm_mday) << 16) | ((tm.tm_hour) << 11) |
((tm.tm_min) << 5) | (tm.tm_sec >> 1);
return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21) |
((tm.tm_mday) << 16) | ((tm.tm_hour) << 11) |
((tm.tm_min) << 5) | (tm.tm_sec >> 1);
}

Wyświetl plik

@ -58,7 +58,7 @@ static StackType_t uxIdleTaskStack[configMINIMAL_STACK_SIZE] __attribute__ ((sec
DECLARE PUBLIC DATA
******************************************************************************/
#ifdef DEBUG
OsiTaskHandle mpTaskHandle;
OsiTaskHandle mpTaskHandle;
#endif
// This is the FreeRTOS heap, defined here so we can put it in a special segment
@ -78,30 +78,31 @@ int main (void) {
// Initialize the clocks and the interrupt system
HAL_SystemInit();
#if MICROPY_HW_ANTENNA_DIVERSITY
#if MICROPY_HW_ANTENNA_DIVERSITY
// configure the antenna selection pins
antenna_init0();
#endif
#endif
// Init the watchdog
pybwdt_init0();
#ifndef DEBUG
#ifndef DEBUG
OsiTaskHandle mpTaskHandle;
#endif
#endif
mpTaskHandle = xTaskCreateStatic(TASK_MicroPython, "MicroPy",
MICROPY_TASK_STACK_LEN, NULL, MICROPY_TASK_PRIORITY, mpTaskStack, &mpTaskTCB);
ASSERT(mpTaskHandle != NULL);
osi_start();
for ( ; ; );
for ( ; ;) {;
}
}
// We need this when configSUPPORT_STATIC_ALLOCATION is enabled
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer,
StackType_t **ppxIdleTaskStackBuffer,
uint32_t *pulIdleTaskStackSize ) {
StackType_t **ppxIdleTaskStackBuffer,
uint32_t *pulIdleTaskStackSize ) {
*ppxIdleTaskTCBBuffer = &xIdleTaskTCB;
*ppxIdleTaskStackBuffer = uxIdleTaskStack;
*pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;

Wyświetl plik

@ -187,15 +187,15 @@ extern const struct _mp_obj_module_t mp_module_ussl;
// type definitions for the specific machine
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1))
#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1))
#define MP_SSIZE_MAX (0x7FFFFFFF)
#define UINT_FMT "%u"
#define INT_FMT "%d"
typedef int32_t mp_int_t; // must be pointer size
typedef unsigned int mp_uint_t; // must be pointer size
typedef long mp_off_t;
typedef int32_t mp_int_t; // must be pointer size
typedef unsigned int mp_uint_t; // must be pointer size
typedef long mp_off_t;
#define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len)

Some files were not shown because too many files have changed in this diff Show More