all: Reformat C and Python source code with tools/codeformat.py.
This is run with uncrustify 0.70.1, and black 19.10b0.
This commit is contained in:
parent
3f39d18c2b
commit
69661f3343
@ -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
|
||||
|
@ -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:
|
||||
@ -293,7 +294,7 @@ class LCD160CR:
|
||||
|
||||
def screen_load(self, buf):
|
||||
l = self.w * self.h * 2 + 2
|
||||
self._fcmd2b('<BBHBBB', 0x70, l, 16, self.w, self.h)
|
||||
self._fcmd2b("<BBHBBB", 0x70, l, 16, self.w, self.h)
|
||||
n = 0
|
||||
ar = memoryview(buf)
|
||||
while n < len(buf):
|
||||
@ -303,19 +304,24 @@ class LCD160CR:
|
||||
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)
|
||||
|
@ -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:
|
||||
@ -22,11 +24,11 @@ def show_adc(lcd, adc):
|
||||
else:
|
||||
lcd.set_font(2, trans=1)
|
||||
lcd.set_pos(0, lcd.h - 60 + i * 16)
|
||||
lcd.write('%4s: ' % ('TEMP', 'VBAT', 'VREF')[i])
|
||||
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:
|
||||
@ -34,11 +36,13 @@ def show_adc(lcd, adc):
|
||||
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)
|
||||
@ -85,10 +89,13 @@ def test_features(lcd, orient=lcd160cr.PORTRAIT):
|
||||
|
||||
# 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')
|
||||
|
@ -6,22 +6,22 @@ import framebuf
|
||||
|
||||
# register definitions
|
||||
SET_CONTRAST = const(0x81)
|
||||
SET_ENTIRE_ON = const(0xa4)
|
||||
SET_NORM_INV = const(0xa6)
|
||||
SET_DISP = const(0xae)
|
||||
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
|
||||
@ -39,25 +39,35 @@ class SSD1306(framebuf.FrameBuffer):
|
||||
for cmd in (
|
||||
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_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_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_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,11 +102,11 @@ 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):
|
||||
@ -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)
|
||||
|
@ -12,11 +12,11 @@ SETUP_RETR = const(0x04)
|
||||
RF_CH = const(0x05)
|
||||
RF_SETUP = const(0x06)
|
||||
STATUS = const(0x07)
|
||||
RX_ADDR_P0 = const(0x0a)
|
||||
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
|
||||
@ -44,10 +44,11 @@ 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
|
||||
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):
|
||||
@ -232,7 +233,7 @@ 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
|
||||
|
@ -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")
|
||||
|
@ -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)
|
||||
t = -((t ^ 0xFFFF) + 1)
|
||||
return t / 16
|
||||
|
@ -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]
|
||||
|
@ -33,9 +33,9 @@ _R1_ILLEGAL_COMMAND = const(1 << 2)
|
||||
# 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)
|
||||
_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,9 +96,9 @@ 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))
|
||||
@ -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:
|
||||
@ -187,11 +187,11 @@ class SDCard:
|
||||
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,36 +199,36 @@ 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:
|
||||
@ -250,12 +250,12 @@ class SDCard:
|
||||
self.readinto(mv[offset : offset + 512])
|
||||
offset += 512
|
||||
nblocks -= 1
|
||||
if self.cmd(12, 0, 0xff, skip1=True):
|
||||
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:
|
||||
|
@ -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
|
||||
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'
|
||||
line = "abcdefghijklmnopqrstuvwxyz\n"
|
||||
lines = line * 200 # 5400 chars
|
||||
short = '1234567890\n'
|
||||
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:
|
||||
print("Single block read/write")
|
||||
with open(fn, "w") as f:
|
||||
n = f.write(short) # one block
|
||||
print(n, 'bytes written')
|
||||
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")
|
||||
|
@ -16,10 +16,10 @@ pyb.LED(3).off() # indicate that we finished waiting for the swit
|
||||
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
|
||||
|
@ -19,13 +19,13 @@ while True:
|
||||
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/)
|
||||
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
|
||||
log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
|
||||
|
||||
# end after switch is pressed again
|
||||
log.close() # close file
|
||||
|
@ -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
|
||||
|
||||
|
@ -6,7 +6,7 @@ accel = pyb.Accel() # create object of accelerom
|
||||
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
|
||||
|
||||
@ -14,7 +14,7 @@ blue.on() # turn on blue LED
|
||||
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
|
||||
log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file
|
||||
|
||||
log.close() # close file
|
||||
blue.off() # turn off LED
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
|
||||
@ -61,25 +64,29 @@ def decode_field(payload, adv_type):
|
||||
|
||||
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()
|
||||
|
@ -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)
|
||||
|
||||
# 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()
|
||||
|
@ -9,6 +9,7 @@ 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)
|
||||
@ -24,18 +25,25 @@ _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_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()
|
||||
|
@ -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,),)
|
||||
_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()
|
||||
|
@ -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)
|
||||
|
@ -1,7 +1,7 @@
|
||||
# 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
|
||||
@ -9,14 +9,16 @@ def conway_step():
|
||||
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)
|
||||
@ -27,6 +29,7 @@ def conway_step():
|
||||
elif not self and num_neighbours == 3:
|
||||
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
|
||||
@ -34,6 +37,7 @@ def conway_rand():
|
||||
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):
|
||||
@ -41,6 +45,7 @@ def conway_go(num_frames):
|
||||
lcd.show() # update the LCD
|
||||
pyb.delay(50)
|
||||
|
||||
|
||||
# testing
|
||||
conway_rand()
|
||||
conway_go(100)
|
||||
|
@ -4,11 +4,13 @@ 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)
|
||||
|
@ -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
|
||||
|
||||
|
@ -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)
|
||||
|
@ -1,5 +1,6 @@
|
||||
import pyb
|
||||
|
||||
|
||||
def led_angle(seconds_to_run_for):
|
||||
# make LED objects
|
||||
l1 = pyb.LED(1)
|
||||
|
@ -3,6 +3,7 @@ try:
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def mandelbrot():
|
||||
# returns True if c, complex, is in the Mandelbrot set
|
||||
# @micropython.native
|
||||
@ -21,7 +22,9 @@ def mandelbrot():
|
||||
lcd.set(u, v)
|
||||
lcd.show()
|
||||
|
||||
|
||||
# PC testing
|
||||
import lcd
|
||||
|
||||
lcd = lcd.LCD(128, 32)
|
||||
mandelbrot()
|
||||
|
@ -2,7 +2,9 @@
|
||||
|
||||
# Dummy function decorators
|
||||
|
||||
|
||||
def nodecor(x):
|
||||
return x
|
||||
|
||||
|
||||
bytecode = native = viper = nodecor
|
||||
|
@ -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()
|
||||
|
@ -10,6 +10,7 @@ HTTP/1.0 200 OK
|
||||
Hello #%d from MicroPython!
|
||||
"""
|
||||
|
||||
|
||||
def main(micropython_optimize=False):
|
||||
s = socket.socket()
|
||||
|
||||
|
@ -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)
|
||||
|
@ -20,6 +20,7 @@ HTTP/1.0 200 OK
|
||||
Hello #%d from MicroPython!
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
s = socket.socket()
|
||||
|
||||
|
@ -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()
|
||||
|
||||
|
@ -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("")
|
||||
|
@ -1,17 +1,22 @@
|
||||
# pyboard testing functions for CPython
|
||||
import time
|
||||
|
||||
|
||||
def delay(n):
|
||||
# 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):
|
||||
|
@ -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,7 +32,7 @@ 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():
|
||||
@ -41,5 +42,6 @@ def run_loop(leds=all_leds):
|
||||
except OSError: # VCPInterrupt # Ctrl+C in interpreter mode.
|
||||
break
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_loop()
|
||||
|
@ -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)
|
||||
|
||||
|
@ -6,4 +6,4 @@
|
||||
|
||||
import umachine as machine
|
||||
|
||||
print(hex(machine.mem16[0xc0000]))
|
||||
print(hex(machine.mem16[0xC0000]))
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -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
|
||||
{
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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;
|
||||
|
@ -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;
|
||||
@ -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) {
|
||||
@ -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);
|
||||
@ -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
|
||||
}
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -148,8 +148,12 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p
|
||||
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";
|
||||
@ -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);
|
||||
}
|
||||
@ -378,17 +385,23 @@ 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) {
|
||||
@ -629,7 +642,8 @@ STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
|
||||
}
|
||||
/* fallthru */
|
||||
|
||||
default: return MP_OBJ_NULL; // op not supported
|
||||
default:
|
||||
return MP_OBJ_NULL; // op not supported
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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 (;;) {
|
||||
|
@ -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)
|
||||
{
|
||||
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
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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;
|
||||
|
@ -1 +1 @@
|
||||
freeze('.', ('webrepl.py', 'webrepl_setup.py', 'websocket_helper.py',))
|
||||
freeze(".", ("webrepl.py", "webrepl_setup.py", "websocket_helper.py",))
|
||||
|
@ -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")
|
||||
|
@ -1,4 +1,5 @@
|
||||
import sys
|
||||
|
||||
# import uos as os
|
||||
import os
|
||||
import machine
|
||||
@ -6,15 +7,18 @@ 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()
|
||||
|
@ -1,4 +1,5 @@
|
||||
import sys
|
||||
|
||||
try:
|
||||
import ubinascii as binascii
|
||||
except:
|
||||
@ -10,6 +11,7 @@ except:
|
||||
|
||||
DEBUG = 0
|
||||
|
||||
|
||||
def server_handshake(sock):
|
||||
clr = sock.makefile("rwb", 0)
|
||||
l = clr.readline()
|
||||
@ -27,7 +29,7 @@ def server_handshake(sock):
|
||||
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)
|
||||
while 1:
|
||||
l = cl.readline()
|
||||
if l == b"\r\n":
|
||||
break
|
||||
|
||||
|
||||
# sys.stdout.write(l)
|
||||
|
@ -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 {
|
||||
|
@ -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) {
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -8,20 +8,22 @@ import sys
|
||||
import csv
|
||||
|
||||
|
||||
SUPPORTED_AFS = { 'UART': ('TX', 'RX', 'RTS', 'CTS'),
|
||||
'SPI': ('CLK', 'MOSI', 'MISO', 'CS0'),
|
||||
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')
|
||||
"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,20 +67,32 @@ 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:
|
||||
@ -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,15 +123,17 @@ 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')
|
||||
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]:
|
||||
@ -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)
|
||||
|
@ -95,7 +95,8 @@ int main (void) {
|
||||
|
||||
osi_start();
|
||||
|
||||
for ( ; ; );
|
||||
for ( ; ;) {;
|
||||
}
|
||||
}
|
||||
|
||||
// We need this when configSUPPORT_STATIC_ALLOCATION is enabled
|
||||
|
@ -158,8 +158,7 @@ soft_reset:
|
||||
// when waking up from hibernate we just want
|
||||
// to enable simplelink and leave it as is
|
||||
wlan_first_start();
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
// only if not comming out of hibernate or a soft reset
|
||||
mptask_enter_ap_mode();
|
||||
}
|
||||
|
@ -97,16 +97,14 @@ void TASK_Servers (void *pvParameters) {
|
||||
// now set/clear the flags
|
||||
servers_data.enabled = true;
|
||||
servers_data.do_enable = false;
|
||||
}
|
||||
else if (servers_data.do_disable) {
|
||||
} else if (servers_data.do_disable) {
|
||||
// disable network services
|
||||
telnet_disable();
|
||||
ftp_disable();
|
||||
// now clear the flags
|
||||
servers_data.do_disable = false;
|
||||
servers_data.enabled = false;
|
||||
}
|
||||
else if (servers_data.do_reset) {
|
||||
} else if (servers_data.do_reset) {
|
||||
// resetting the servers is needed to prevent half-open sockets
|
||||
servers_data.do_reset = false;
|
||||
if (servers_data.enabled) {
|
||||
@ -120,8 +118,7 @@ void TASK_Servers (void *pvParameters) {
|
||||
|
||||
if (cycle) {
|
||||
telnet_run();
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
ftp_run();
|
||||
}
|
||||
|
||||
|
@ -12,13 +12,15 @@ python3 run-tests --target wipy --device 192.168.1.1 ../cc3200/tools/smoke.py
|
||||
pin_map = [23, 24, 11, 12, 13, 14, 15, 16, 17, 22, 28, 10, 9, 8, 7, 6, 30, 31, 3, 0, 4, 5]
|
||||
test_bytes = os.urandom(1024)
|
||||
|
||||
|
||||
def test_pin_read(pull):
|
||||
# enable the pull resistor on all pins, then read the value
|
||||
for p in pin_map:
|
||||
pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull)
|
||||
pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull)
|
||||
# read the pin value
|
||||
print(pin())
|
||||
|
||||
|
||||
def test_pin_shorts(pull):
|
||||
if pull == Pin.PULL_UP:
|
||||
pull_inverted = Pin.PULL_DOWN
|
||||
@ -26,41 +28,42 @@ def test_pin_shorts (pull):
|
||||
pull_inverted = Pin.PULL_UP
|
||||
# enable all pulls of the specified type
|
||||
for p in pin_map:
|
||||
pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull_inverted)
|
||||
pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull_inverted)
|
||||
# then change the pull one pin at a time and read its value
|
||||
i = 0
|
||||
while i < len(pin_map):
|
||||
pin = Pin('GP' + str(pin_map[i]), mode=Pin.IN, pull=pull)
|
||||
Pin('GP' + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted)
|
||||
pin = Pin("GP" + str(pin_map[i]), mode=Pin.IN, pull=pull)
|
||||
Pin("GP" + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted)
|
||||
i += 1
|
||||
# read the pin value
|
||||
print(pin())
|
||||
|
||||
|
||||
test_pin_read(Pin.PULL_UP)
|
||||
test_pin_read(Pin.PULL_DOWN)
|
||||
test_pin_shorts(Pin.PULL_UP)
|
||||
test_pin_shorts(Pin.PULL_DOWN)
|
||||
|
||||
# create a test directory
|
||||
os.mkdir('/flash/test')
|
||||
os.chdir('/flash/test')
|
||||
os.mkdir("/flash/test")
|
||||
os.chdir("/flash/test")
|
||||
print(os.getcwd())
|
||||
# create a new file
|
||||
f = open('test.txt', 'w')
|
||||
f = open("test.txt", "w")
|
||||
n_w = f.write(test_bytes)
|
||||
print(n_w == len(test_bytes))
|
||||
f.close()
|
||||
f = open('test.txt', 'r')
|
||||
r = bytes(f.read(), 'ascii')
|
||||
f = open("test.txt", "r")
|
||||
r = bytes(f.read(), "ascii")
|
||||
# check that we can write and read it correctly
|
||||
print(r == test_bytes)
|
||||
f.close()
|
||||
os.remove('test.txt')
|
||||
os.chdir('..')
|
||||
os.rmdir('test')
|
||||
os.remove("test.txt")
|
||||
os.chdir("..")
|
||||
os.rmdir("test")
|
||||
|
||||
ls = os.listdir()
|
||||
print('test' not in ls)
|
||||
print("test" not in ls)
|
||||
print(ls)
|
||||
|
||||
# test the real time clock
|
||||
@ -73,4 +76,3 @@ time.sleep_ms(1000)
|
||||
time2 = rtc.now()
|
||||
print(time2[5] - time1[5] == 1)
|
||||
print(time2[6] - time1[6] < 5000) # microseconds
|
||||
|
||||
|
@ -19,7 +19,7 @@ import subprocess
|
||||
|
||||
|
||||
def print_exception(e):
|
||||
print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno))
|
||||
print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno))
|
||||
|
||||
|
||||
def execute(command):
|
||||
@ -29,7 +29,7 @@ def execute(command):
|
||||
# Poll process for new output until finished
|
||||
while True:
|
||||
nextline = process.stdout.readline()
|
||||
if nextline == '' and process.poll() != None:
|
||||
if nextline == "" and process.poll() != None:
|
||||
break
|
||||
sys.stdout.write(nextline)
|
||||
sys.stdout.flush()
|
||||
@ -43,25 +43,58 @@ def execute(command):
|
||||
else:
|
||||
raise ProcessException(command, exitCode, output)
|
||||
|
||||
|
||||
def main():
|
||||
cmd_parser = argparse.ArgumentParser(description='Flash the WiPy and optionally run a small test on it.')
|
||||
cmd_parser.add_argument('-u', '--uniflash', default=None, help='the path to the uniflash cli executable')
|
||||
cmd_parser.add_argument('-c', '--config', default=None, help='the path to the uniflash config file')
|
||||
cmd_parser.add_argument('-p', '--port', default=8, help='the com serial port')
|
||||
cmd_parser.add_argument('-s', '--servicepack', default=None, help='the path to the servicepack file')
|
||||
cmd_parser = argparse.ArgumentParser(
|
||||
description="Flash the WiPy and optionally run a small test on it."
|
||||
)
|
||||
cmd_parser.add_argument(
|
||||
"-u", "--uniflash", default=None, help="the path to the uniflash cli executable"
|
||||
)
|
||||
cmd_parser.add_argument(
|
||||
"-c", "--config", default=None, help="the path to the uniflash config file"
|
||||
)
|
||||
cmd_parser.add_argument("-p", "--port", default=8, help="the com serial port")
|
||||
cmd_parser.add_argument(
|
||||
"-s", "--servicepack", default=None, help="the path to the servicepack file"
|
||||
)
|
||||
args = cmd_parser.parse_args()
|
||||
|
||||
output = ""
|
||||
com_port = 'com=' + str(args.port)
|
||||
servicepack_path = 'spPath=' + args.servicepack
|
||||
com_port = "com=" + str(args.port)
|
||||
servicepack_path = "spPath=" + args.servicepack
|
||||
|
||||
try:
|
||||
if args.uniflash == None or args.config == None:
|
||||
raise ValueError('uniflash path and config path are mandatory')
|
||||
raise ValueError("uniflash path and config path are mandatory")
|
||||
if args.servicepack == None:
|
||||
output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, '-operations', 'format', 'program'])
|
||||
output += execute(
|
||||
[
|
||||
args.uniflash,
|
||||
"-config",
|
||||
args.config,
|
||||
"-setOptions",
|
||||
com_port,
|
||||
"-operations",
|
||||
"format",
|
||||
"program",
|
||||
]
|
||||
)
|
||||
else:
|
||||
output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, servicepack_path, '-operations', 'format', 'servicePackUpdate', 'program'])
|
||||
output += execute(
|
||||
[
|
||||
args.uniflash,
|
||||
"-config",
|
||||
args.config,
|
||||
"-setOptions",
|
||||
com_port,
|
||||
servicepack_path,
|
||||
"-operations",
|
||||
"format",
|
||||
"servicePackUpdate",
|
||||
"program",
|
||||
]
|
||||
)
|
||||
except Exception as e:
|
||||
print_exception(e)
|
||||
output = ""
|
||||
@ -77,5 +110,6 @@ def main():
|
||||
print("======================================")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@ -23,12 +23,12 @@ from telnetlib import Telnet
|
||||
|
||||
|
||||
def print_exception(e):
|
||||
print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno))
|
||||
print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno))
|
||||
|
||||
|
||||
def ftp_directory_exists(ftpobj, directory_name):
|
||||
filelist = []
|
||||
ftpobj.retrlines('LIST',filelist.append)
|
||||
ftpobj.retrlines("LIST", filelist.append)
|
||||
for f in filelist:
|
||||
if f.split()[-1] == directory_name:
|
||||
return True
|
||||
@ -37,34 +37,34 @@ def ftp_directory_exists(ftpobj, directory_name):
|
||||
|
||||
def transfer_file(args):
|
||||
with FTP(args.ip, timeout=20) as ftp:
|
||||
print ('FTP connection established')
|
||||
print("FTP connection established")
|
||||
|
||||
if '230' in ftp.login(args.user, args.password):
|
||||
print ('Login successful')
|
||||
if "230" in ftp.login(args.user, args.password):
|
||||
print("Login successful")
|
||||
|
||||
if '250' in ftp.cwd('/flash'):
|
||||
if not ftp_directory_exists(ftp, 'sys'):
|
||||
print ('/flash/sys directory does not exist')
|
||||
if not '550' in ftp.mkd('sys'):
|
||||
print ('/flash/sys directory created')
|
||||
if "250" in ftp.cwd("/flash"):
|
||||
if not ftp_directory_exists(ftp, "sys"):
|
||||
print("/flash/sys directory does not exist")
|
||||
if not "550" in ftp.mkd("sys"):
|
||||
print("/flash/sys directory created")
|
||||
else:
|
||||
print ('Error: cannot create /flash/sys directory')
|
||||
print("Error: cannot create /flash/sys directory")
|
||||
return False
|
||||
if '250' in ftp.cwd('sys'):
|
||||
if "250" in ftp.cwd("sys"):
|
||||
print("Entered '/flash/sys' directory")
|
||||
with open(args.file, "rb") as fwfile:
|
||||
print ('Firmware image found, initiating transfer...')
|
||||
if '226' in ftp.storbinary("STOR " + 'mcuimg.bin', fwfile, 512):
|
||||
print ('File transfer complete')
|
||||
print("Firmware image found, initiating transfer...")
|
||||
if "226" in ftp.storbinary("STOR " + "mcuimg.bin", fwfile, 512):
|
||||
print("File transfer complete")
|
||||
return True
|
||||
else:
|
||||
print ('Error: file transfer failed')
|
||||
print("Error: file transfer failed")
|
||||
else:
|
||||
print ('Error: cannot enter /flash/sys directory')
|
||||
print("Error: cannot enter /flash/sys directory")
|
||||
else:
|
||||
print ('Error: cannot enter /flash directory')
|
||||
print("Error: cannot enter /flash directory")
|
||||
else:
|
||||
print ('Error: ftp login failed')
|
||||
print("Error: ftp login failed")
|
||||
|
||||
return False
|
||||
|
||||
@ -76,20 +76,24 @@ def reset_board(args):
|
||||
tn = Telnet(args.ip, timeout=5)
|
||||
print("Connected via Telnet, trying to login now")
|
||||
|
||||
if b'Login as:' in tn.read_until(b"Login as:", timeout=5):
|
||||
tn.write(bytes(args.user, 'ascii') + b"\r\n")
|
||||
if b"Login as:" in tn.read_until(b"Login as:", timeout=5):
|
||||
tn.write(bytes(args.user, "ascii") + b"\r\n")
|
||||
|
||||
if b'Password:' in tn.read_until(b"Password:", timeout=5):
|
||||
if b"Password:" in tn.read_until(b"Password:", timeout=5):
|
||||
# needed because of internal implementation details of the WiPy's telnet server
|
||||
time.sleep(0.2)
|
||||
tn.write(bytes(args.password, 'ascii') + b"\r\n")
|
||||
tn.write(bytes(args.password, "ascii") + b"\r\n")
|
||||
|
||||
if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5):
|
||||
if b'Type "help()" for more information.' in tn.read_until(
|
||||
b'Type "help()" for more information.', timeout=5
|
||||
):
|
||||
print("Telnet login succeeded")
|
||||
tn.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program
|
||||
tn.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program
|
||||
time.sleep(1)
|
||||
tn.write(b'\r\x02') # ctrl-B: enter friendly REPL
|
||||
if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5):
|
||||
tn.write(b"\r\x02") # ctrl-B: enter friendly REPL
|
||||
if b'Type "help()" for more information.' in tn.read_until(
|
||||
b'Type "help()" for more information.', timeout=5
|
||||
):
|
||||
tn.write(b"import machine\r\n")
|
||||
tn.write(b"machine.reset()\r\n")
|
||||
time.sleep(2)
|
||||
@ -112,7 +116,7 @@ def reset_board(args):
|
||||
|
||||
def verify_update(args):
|
||||
success = False
|
||||
firmware_tag = ''
|
||||
firmware_tag = ""
|
||||
|
||||
def find_tag(tag):
|
||||
if tag in firmware_tag:
|
||||
@ -135,21 +139,26 @@ def verify_update(args):
|
||||
print("Timeout while connecting via telnet, retrying...")
|
||||
retries += 1
|
||||
else:
|
||||
print('Error: Telnet connection timed out!')
|
||||
print("Error: Telnet connection timed out!")
|
||||
return False
|
||||
|
||||
try:
|
||||
firmware_tag = tn.read_until (b'with CC3200')
|
||||
tag_file_path = args.file.rstrip('mcuimg.bin') + 'genhdr/mpversion.h'
|
||||
firmware_tag = tn.read_until(b"with CC3200")
|
||||
tag_file_path = args.file.rstrip("mcuimg.bin") + "genhdr/mpversion.h"
|
||||
|
||||
if args.tag is not None:
|
||||
success = find_tag(bytes(args.tag, 'ascii'))
|
||||
success = find_tag(bytes(args.tag, "ascii"))
|
||||
else:
|
||||
with open(tag_file_path) as tag_file:
|
||||
for line in tag_file:
|
||||
bline = bytes(line, 'ascii')
|
||||
if b'MICROPY_GIT_HASH' in bline:
|
||||
bline = bline.lstrip(b'#define MICROPY_GIT_HASH ').replace(b'"', b'').replace(b'\r', b'').replace(b'\n', b'')
|
||||
bline = bytes(line, "ascii")
|
||||
if b"MICROPY_GIT_HASH" in bline:
|
||||
bline = (
|
||||
bline.lstrip(b"#define MICROPY_GIT_HASH ")
|
||||
.replace(b'"', b"")
|
||||
.replace(b"\r", b"")
|
||||
.replace(b"\n", b"")
|
||||
)
|
||||
success = find_tag(bline)
|
||||
break
|
||||
|
||||
@ -164,24 +173,28 @@ def verify_update(args):
|
||||
|
||||
|
||||
def main():
|
||||
cmd_parser = argparse.ArgumentParser(description='Update the WiPy firmware with the specified image file')
|
||||
cmd_parser.add_argument('-f', '--file', default=None, help='the path of the firmware file')
|
||||
cmd_parser.add_argument('-u', '--user', default='micro', help='the username')
|
||||
cmd_parser.add_argument('-p', '--password', default='python', help='the login password')
|
||||
cmd_parser.add_argument('--ip', default='192.168.1.1', help='the ip address of the WiPy')
|
||||
cmd_parser.add_argument('--verify', action='store_true', help='verify that the update succeeded')
|
||||
cmd_parser.add_argument('-t', '--tag', default=None, help='git tag of the firmware image')
|
||||
cmd_parser = argparse.ArgumentParser(
|
||||
description="Update the WiPy firmware with the specified image file"
|
||||
)
|
||||
cmd_parser.add_argument("-f", "--file", default=None, help="the path of the firmware file")
|
||||
cmd_parser.add_argument("-u", "--user", default="micro", help="the username")
|
||||
cmd_parser.add_argument("-p", "--password", default="python", help="the login password")
|
||||
cmd_parser.add_argument("--ip", default="192.168.1.1", help="the ip address of the WiPy")
|
||||
cmd_parser.add_argument(
|
||||
"--verify", action="store_true", help="verify that the update succeeded"
|
||||
)
|
||||
cmd_parser.add_argument("-t", "--tag", default=None, help="git tag of the firmware image")
|
||||
args = cmd_parser.parse_args()
|
||||
|
||||
result = 1
|
||||
|
||||
try:
|
||||
if args.file is None:
|
||||
raise ValueError('the image file path must be specified')
|
||||
raise ValueError("the image file path must be specified")
|
||||
if transfer_file(args):
|
||||
if reset_board(args):
|
||||
if args.verify:
|
||||
print ('Waiting for the WiFi connection to come up again...')
|
||||
print("Waiting for the WiFi connection to come up again...")
|
||||
# this time is to allow the system's wireless network card to
|
||||
# connect to the WiPy again.
|
||||
time.sleep(5)
|
||||
|
@ -1,2 +1,2 @@
|
||||
include('$(PORT_DIR)/boards/manifest.py')
|
||||
include("$(PORT_DIR)/boards/manifest.py")
|
||||
freeze("modules")
|
||||
|
@ -63,8 +63,7 @@ class DotStar:
|
||||
dotstar[0] = (128, 0, 0) # Red
|
||||
"""
|
||||
|
||||
def __init__(self, spi, n, *, brightness=1.0, auto_write=True,
|
||||
pixel_order=BGR):
|
||||
def __init__(self, spi, n, *, brightness=1.0, auto_write=True, pixel_order=BGR):
|
||||
self._spi = spi
|
||||
self._n = n
|
||||
# Supply one extra clock cycle for each two pixels in the strip.
|
||||
@ -79,10 +78,10 @@ class DotStar:
|
||||
self._buf[i] = 0x00
|
||||
# Mark the beginnings of each pixel.
|
||||
for i in range(START_HEADER_SIZE, self.end_header_index, 4):
|
||||
self._buf[i] = 0xff
|
||||
self._buf[i] = 0xFF
|
||||
# 0xff bytes at the end.
|
||||
for i in range(self.end_header_index, len(self._buf)):
|
||||
self._buf[i] = 0xff
|
||||
self._buf[i] = 0xFF
|
||||
self._brightness = 1.0
|
||||
# Set auto_write to False temporarily so brightness setter does _not_
|
||||
# call show() while in __init__.
|
||||
@ -129,7 +128,7 @@ class DotStar:
|
||||
offset = index * 4 + START_HEADER_SIZE
|
||||
rgb = value
|
||||
if isinstance(value, int):
|
||||
rgb = (value >> 16, (value >> 8) & 0xff, value & 0xff)
|
||||
rgb = (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
|
||||
|
||||
if len(rgb) == 4:
|
||||
brightness = value[3]
|
||||
@ -171,15 +170,15 @@ class DotStar:
|
||||
out = []
|
||||
for in_i in range(*index.indices(self._n)):
|
||||
out.append(
|
||||
tuple(self._buf[in_i * 4 + (3 - i) + START_HEADER_SIZE] for i in range(3)))
|
||||
tuple(self._buf[in_i * 4 + (3 - i) + START_HEADER_SIZE] for i in range(3))
|
||||
)
|
||||
return out
|
||||
if index < 0:
|
||||
index += len(self)
|
||||
if index >= self._n or index < 0:
|
||||
raise IndexError
|
||||
offset = index * 4
|
||||
return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE]
|
||||
for i in range(3))
|
||||
return tuple(self._buf[offset + (3 - i) + START_HEADER_SIZE] for i in range(3))
|
||||
|
||||
def __len__(self):
|
||||
return self._n
|
||||
@ -222,7 +221,7 @@ class DotStar:
|
||||
buf[i] = self._buf[i] if i % 4 == 0 else int(self._buf[i] * self._brightness)
|
||||
# Four 0xff bytes at the end.
|
||||
for i in range(self.end_header_index, len(buf)):
|
||||
buf[i] = 0xff
|
||||
buf[i] = 0xFF
|
||||
|
||||
if self._spi:
|
||||
self._spi.write(buf)
|
||||
|
@ -53,6 +53,7 @@ def get_battery_voltage():
|
||||
measuredvbat *= 3.7 # Multiply by 3.7V, our reference voltage
|
||||
return measuredvbat
|
||||
|
||||
|
||||
# Return the current charge state of the battery - we need to read the value multiple times
|
||||
# to eliminate false negatives due to the charge IC not knowing the difference between no battery
|
||||
# and a full battery not charging - This is why the charge LED flashes
|
||||
@ -64,7 +65,9 @@ def get_battery_charging():
|
||||
measuredVal = 0 # start our reading at 0
|
||||
io = Pin(BAT_CHARGE, Pin.IN) # Assign the pin to read
|
||||
|
||||
for y in range(0, 10): # loop through 10 times adding the read values together to ensure no false positives
|
||||
for y in range(
|
||||
0, 10
|
||||
): # loop through 10 times adding the read values together to ensure no false positives
|
||||
measuredVal += io.value()
|
||||
|
||||
return measuredVal == 0 # return True if the value is 0
|
||||
@ -85,11 +88,16 @@ def set_dotstar_power(state):
|
||||
else:
|
||||
Pin(13, Pin.IN, Pin.PULL_HOLD) # Set PULL_HOLD on the pin to allow the 3V3 pull-up to work
|
||||
|
||||
Pin(DOTSTAR_CLK, Pin.OUT if state else Pin.IN) # If power is on, set CLK to be output, otherwise input
|
||||
Pin(DOTSTAR_DATA, Pin.OUT if state else Pin.IN) # If power is on, set DATA to be output, otherwise input
|
||||
Pin(
|
||||
DOTSTAR_CLK, Pin.OUT if state else Pin.IN
|
||||
) # If power is on, set CLK to be output, otherwise input
|
||||
Pin(
|
||||
DOTSTAR_DATA, Pin.OUT if state else Pin.IN
|
||||
) # If power is on, set DATA to be output, otherwise input
|
||||
|
||||
# A small delay to let the IO change state
|
||||
time.sleep(.035)
|
||||
time.sleep(0.035)
|
||||
|
||||
|
||||
# Dotstar rainbow colour wheel
|
||||
def dotstar_color_wheel(wheel_pos):
|
||||
@ -105,6 +113,7 @@ def dotstar_color_wheel(wheel_pos):
|
||||
wheel_pos -= 170
|
||||
return wheel_pos * 3, 255 - wheel_pos * 3, 0
|
||||
|
||||
|
||||
# Go into deep sleep but shut down the APA first to save power
|
||||
# Use this if you want lowest deep sleep current
|
||||
def go_deepsleep(t):
|
||||
|
@ -1,6 +1,6 @@
|
||||
freeze('$(PORT_DIR)/modules')
|
||||
freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py'))
|
||||
freeze('$(MPY_DIR)/ports/esp8266/modules', 'ntptime.py')
|
||||
freeze('$(MPY_DIR)/drivers/dht', 'dht.py')
|
||||
freeze('$(MPY_DIR)/drivers/onewire')
|
||||
include('$(MPY_DIR)/extmod/webrepl/manifest.py')
|
||||
freeze("$(PORT_DIR)/modules")
|
||||
freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
|
||||
freeze("$(MPY_DIR)/ports/esp8266/modules", "ntptime.py")
|
||||
freeze("$(MPY_DIR)/drivers/dht", "dht.py")
|
||||
freeze("$(MPY_DIR)/drivers/onewire")
|
||||
include("$(MPY_DIR)/extmod/webrepl/manifest.py")
|
||||
|
@ -1,6 +1,6 @@
|
||||
include('manifest.py')
|
||||
include("manifest.py")
|
||||
|
||||
freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py')
|
||||
freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py')
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.py')
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.robust', 'umqtt/robust.py')
|
||||
freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
|
||||
freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.py")
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.robust", "umqtt/robust.py")
|
||||
|
@ -180,17 +180,23 @@ STATIC mp_obj_t esp32_partition_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_
|
||||
esp32_partition_obj_t *self = MP_OBJ_TO_PTR(self_in);
|
||||
mp_int_t cmd = mp_obj_get_int(cmd_in);
|
||||
switch (cmd) {
|
||||
case MP_BLOCKDEV_IOCTL_INIT: return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_DEINIT: return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_SYNC: return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: return MP_OBJ_NEW_SMALL_INT(self->part->size / BLOCK_SIZE_BYTES);
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: return MP_OBJ_NEW_SMALL_INT(BLOCK_SIZE_BYTES);
|
||||
case MP_BLOCKDEV_IOCTL_INIT:
|
||||
return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_DEINIT:
|
||||
return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_SYNC:
|
||||
return MP_OBJ_NEW_SMALL_INT(0);
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
|
||||
return MP_OBJ_NEW_SMALL_INT(self->part->size / BLOCK_SIZE_BYTES);
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
|
||||
return MP_OBJ_NEW_SMALL_INT(BLOCK_SIZE_BYTES);
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: {
|
||||
uint32_t offset = mp_obj_get_int(arg_in) * BLOCK_SIZE_BYTES;
|
||||
check_esp_err(esp_partition_erase_range(self->part, offset, BLOCK_SIZE_BYTES));
|
||||
return MP_OBJ_NEW_SMALL_INT(0);
|
||||
}
|
||||
default: return mp_const_none;
|
||||
default:
|
||||
return mp_const_none;
|
||||
}
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_partition_ioctl_obj, esp32_partition_ioctl);
|
||||
|
@ -36,18 +36,28 @@ void IRAM_ATTR esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numByte
|
||||
|
||||
uint32_t irq_state = mp_hal_quiet_timing_enter();
|
||||
for (t = time0;; t = time0) {
|
||||
if (pix & mask) t = time1; // Bit high duration
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start
|
||||
if (pix & mask) {
|
||||
t = time1; // Bit high duration
|
||||
}
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < period) {
|
||||
; // Wait for bit start
|
||||
}
|
||||
GPIO_REG_WRITE(GPIO_OUT_W1TS_REG, pinMask); // Set high
|
||||
startTime = c; // Save start time
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < t) {
|
||||
; // Wait high duration
|
||||
}
|
||||
GPIO_REG_WRITE(GPIO_OUT_W1TC_REG, pinMask); // Set low
|
||||
if (!(mask >>= 1)) { // Next bit/byte
|
||||
if(p >= end) break;
|
||||
if (p >= end) {
|
||||
break;
|
||||
}
|
||||
pix = *p++;
|
||||
mask = 0x80;
|
||||
}
|
||||
}
|
||||
while ((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit
|
||||
while ((mp_hal_ticks_cpu() - startTime) < period) {
|
||||
; // Wait for last bit
|
||||
}
|
||||
mp_hal_quiet_timing_exit(irq_state);
|
||||
}
|
||||
|
@ -36,6 +36,6 @@ DWORD get_fattime(void) {
|
||||
timeutils_struct_time_t tm;
|
||||
timeutils_seconds_since_2000_to_struct_time(tv.tv_sec, &tm);
|
||||
|
||||
return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
|
||||
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1));
|
||||
return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
|
||||
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1);
|
||||
}
|
||||
|
@ -69,11 +69,18 @@ STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n
|
||||
gpio_num_t pin_id = machine_pin_get_id(args[0]);
|
||||
const madc_obj_t *self = NULL;
|
||||
for (int i = 0; i < MP_ARRAY_SIZE(madc_obj); i++) {
|
||||
if (pin_id == madc_obj[i].gpio_id) { self = &madc_obj[i]; break; }
|
||||
if (pin_id == madc_obj[i].gpio_id) {
|
||||
self = &madc_obj[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!self) {
|
||||
mp_raise_ValueError("invalid Pin for ADC");
|
||||
}
|
||||
if (!self) mp_raise_ValueError("invalid Pin for ADC");
|
||||
esp_err_t err = adc1_config_channel_atten(self->adc1_id, ADC_ATTEN_0db);
|
||||
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self);
|
||||
if (err == ESP_OK) {
|
||||
return MP_OBJ_FROM_PTR(self);
|
||||
}
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
|
||||
@ -96,7 +103,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(madc_read_u16_obj, madc_read_u16);
|
||||
STATIC mp_obj_t madc_read(mp_obj_t self_in) {
|
||||
madc_obj_t *self = self_in;
|
||||
int val = adc1_get_raw(self->adc1_id);
|
||||
if (val == -1) mp_raise_ValueError("Parameter Error");
|
||||
if (val == -1) {
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
return MP_OBJ_NEW_SMALL_INT(val);
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_1(madc_read_obj, madc_read);
|
||||
@ -105,7 +114,9 @@ STATIC mp_obj_t madc_atten(mp_obj_t self_in, mp_obj_t atten_in) {
|
||||
madc_obj_t *self = self_in;
|
||||
adc_atten_t atten = mp_obj_get_int(atten_in);
|
||||
esp_err_t err = adc1_config_channel_atten(self->adc1_id, atten);
|
||||
if (err == ESP_OK) return mp_const_none;
|
||||
if (err == ESP_OK) {
|
||||
return mp_const_none;
|
||||
}
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten);
|
||||
@ -117,11 +128,20 @@ STATIC mp_obj_t madc_width(mp_obj_t cls_in, mp_obj_t width_in) {
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
switch (width) {
|
||||
case ADC_WIDTH_9Bit: adc_bit_width = 9; break;
|
||||
case ADC_WIDTH_10Bit: adc_bit_width = 10; break;
|
||||
case ADC_WIDTH_11Bit: adc_bit_width = 11; break;
|
||||
case ADC_WIDTH_12Bit: adc_bit_width = 12; break;
|
||||
default: break;
|
||||
case ADC_WIDTH_9Bit:
|
||||
adc_bit_width = 9;
|
||||
break;
|
||||
case ADC_WIDTH_10Bit:
|
||||
adc_bit_width = 10;
|
||||
break;
|
||||
case ADC_WIDTH_11Bit:
|
||||
adc_bit_width = 11;
|
||||
break;
|
||||
case ADC_WIDTH_12Bit:
|
||||
adc_bit_width = 12;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
|
@ -54,15 +54,22 @@ STATIC mp_obj_t mdac_make_new(const mp_obj_type_t *type, size_t n_args, size_t n
|
||||
gpio_num_t pin_id = machine_pin_get_id(args[0]);
|
||||
const mdac_obj_t *self = NULL;
|
||||
for (int i = 0; i < MP_ARRAY_SIZE(mdac_obj); i++) {
|
||||
if (pin_id == mdac_obj[i].gpio_id) { self = &mdac_obj[i]; break; }
|
||||
if (pin_id == mdac_obj[i].gpio_id) {
|
||||
self = &mdac_obj[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!self) {
|
||||
mp_raise_ValueError("invalid Pin for DAC");
|
||||
}
|
||||
if (!self) mp_raise_ValueError("invalid Pin for DAC");
|
||||
|
||||
esp_err_t err = dac_output_enable(self->dac_id);
|
||||
if (err == ESP_OK) {
|
||||
err = dac_output_voltage(self->dac_id, 0);
|
||||
}
|
||||
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self);
|
||||
if (err == ESP_OK) {
|
||||
return MP_OBJ_FROM_PTR(self);
|
||||
}
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
|
||||
@ -74,10 +81,14 @@ STATIC void mdac_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_
|
||||
STATIC mp_obj_t mdac_write(mp_obj_t self_in, mp_obj_t value_in) {
|
||||
mdac_obj_t *self = self_in;
|
||||
int value = mp_obj_get_int(value_in);
|
||||
if (value < 0 || value > 255) mp_raise_ValueError("Value out of range");
|
||||
if (value < 0 || value > 255) {
|
||||
mp_raise_ValueError("Value out of range");
|
||||
}
|
||||
|
||||
esp_err_t err = dac_output_voltage(self->dac_id, value);
|
||||
if (err == ESP_OK) return mp_const_none;
|
||||
if (err == ESP_OK) {
|
||||
return mp_const_none;
|
||||
}
|
||||
mp_raise_ValueError("Parameter Error");
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_2(mdac_write_obj, mdac_write);
|
||||
|
@ -222,7 +222,8 @@ STATIC mp_obj_t machine_sdcard_make_new(const mp_obj_type_t *type, size_t n_args
|
||||
.gpio_wp = SDSPI_SLOT_NO_WP,
|
||||
.dma_channel = 2
|
||||
},
|
||||
SDSPI_SLOT_CONFIG_DEFAULT() };
|
||||
SDSPI_SLOT_CONFIG_DEFAULT()
|
||||
};
|
||||
|
||||
DEBUG_printf(" Setting up SPI slot configuration");
|
||||
sdspi_slot_config_t slot_config = slot_defaults[slot_num];
|
||||
@ -352,14 +353,16 @@ STATIC mp_obj_t machine_sdcard_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t
|
||||
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_COUNT:
|
||||
err = sdcard_ensure_card_init(self, false);
|
||||
if (err != ESP_OK)
|
||||
if (err != ESP_OK) {
|
||||
return MP_OBJ_NEW_SMALL_INT(-1);
|
||||
}
|
||||
return MP_OBJ_NEW_SMALL_INT(self->card.csd.capacity);
|
||||
|
||||
case MP_BLOCKDEV_IOCTL_BLOCK_SIZE:
|
||||
err = sdcard_ensure_card_init(self, false);
|
||||
if (err != ESP_OK)
|
||||
if (err != ESP_OK) {
|
||||
return MP_OBJ_NEW_SMALL_INT(-1);
|
||||
}
|
||||
return MP_OBJ_NEW_SMALL_INT(_SECTOR_SIZE(self));
|
||||
|
||||
default: // unknown command
|
||||
|
@ -62,9 +62,14 @@ STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_
|
||||
gpio_num_t pin_id = machine_pin_get_id(args[0]);
|
||||
const mtp_obj_t *self = NULL;
|
||||
for (int i = 0; i < MP_ARRAY_SIZE(touchpad_obj); i++) {
|
||||
if (pin_id == touchpad_obj[i].gpio_id) { self = &touchpad_obj[i]; break; }
|
||||
if (pin_id == touchpad_obj[i].gpio_id) {
|
||||
self = &touchpad_obj[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!self) {
|
||||
mp_raise_ValueError("invalid pin for touchpad");
|
||||
}
|
||||
if (!self) mp_raise_ValueError("invalid pin for touchpad");
|
||||
|
||||
static int initialized = 0;
|
||||
if (!initialized) {
|
||||
@ -73,7 +78,9 @@ STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_
|
||||
initialized = 1;
|
||||
}
|
||||
esp_err_t err = touch_pad_config(self->touchpad_id, 0);
|
||||
if (err == ESP_OK) return MP_OBJ_FROM_PTR(self);
|
||||
if (err == ESP_OK) {
|
||||
return MP_OBJ_FROM_PTR(self);
|
||||
}
|
||||
mp_raise_ValueError("Touch pad error");
|
||||
}
|
||||
|
||||
@ -81,7 +88,9 @@ STATIC mp_obj_t mtp_config(mp_obj_t self_in, mp_obj_t value_in) {
|
||||
mtp_obj_t *self = self_in;
|
||||
uint16_t value = mp_obj_get_int(value_in);
|
||||
esp_err_t err = touch_pad_config(self->touchpad_id, value);
|
||||
if (err == ESP_OK) return mp_const_none;
|
||||
if (err == ESP_OK) {
|
||||
return mp_const_none;
|
||||
}
|
||||
mp_raise_ValueError("Touch pad error");
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_2(mtp_config_obj, mtp_config);
|
||||
@ -90,7 +99,9 @@ STATIC mp_obj_t mtp_read(mp_obj_t self_in) {
|
||||
mtp_obj_t *self = self_in;
|
||||
uint16_t value;
|
||||
esp_err_t err = touch_pad_read(self->touchpad_id, &value);
|
||||
if (err == ESP_OK) return MP_OBJ_NEW_SMALL_INT(value);
|
||||
if (err == ESP_OK) {
|
||||
return MP_OBJ_NEW_SMALL_INT(value);
|
||||
}
|
||||
mp_raise_ValueError("Touch pad error");
|
||||
}
|
||||
MP_DEFINE_CONST_FUN_OBJ_1(mtp_read_obj, mtp_read);
|
||||
|
@ -5,21 +5,21 @@ OFFSET_PARTITIONS = 0x8000
|
||||
OFFSET_APPLICATION = 0x10000
|
||||
|
||||
files_in = [
|
||||
('bootloader', OFFSET_BOOTLOADER, sys.argv[1]),
|
||||
('partitions', OFFSET_PARTITIONS, sys.argv[2]),
|
||||
('application', OFFSET_APPLICATION, sys.argv[3]),
|
||||
("bootloader", OFFSET_BOOTLOADER, sys.argv[1]),
|
||||
("partitions", OFFSET_PARTITIONS, sys.argv[2]),
|
||||
("application", OFFSET_APPLICATION, sys.argv[3]),
|
||||
]
|
||||
file_out = sys.argv[4]
|
||||
|
||||
cur_offset = OFFSET_BOOTLOADER
|
||||
with open(file_out, 'wb') as fout:
|
||||
with open(file_out, "wb") as fout:
|
||||
for name, offset, file_in in files_in:
|
||||
assert offset >= cur_offset
|
||||
fout.write(b'\xff' * (offset - cur_offset))
|
||||
fout.write(b"\xff" * (offset - cur_offset))
|
||||
cur_offset = offset
|
||||
with open(file_in, 'rb') as fin:
|
||||
with open(file_in, "rb") as fin:
|
||||
data = fin.read()
|
||||
fout.write(data)
|
||||
cur_offset += len(data)
|
||||
print('%-12s% 8d' % (name, len(data)))
|
||||
print('%-12s% 8d' % ('total', cur_offset))
|
||||
print("%-12s% 8d" % (name, len(data)))
|
||||
print("%-12s% 8d" % ("total", cur_offset))
|
||||
|
@ -103,7 +103,9 @@ NORETURN void _esp_exceptions(esp_err_t e) {
|
||||
}
|
||||
|
||||
static inline void esp_exceptions(esp_err_t e) {
|
||||
if (e != ESP_OK) _esp_exceptions(e);
|
||||
if (e != ESP_OK) {
|
||||
_esp_exceptions(e);
|
||||
}
|
||||
}
|
||||
|
||||
#define ESP_EXCEPTIONS(x) do { esp_exceptions(x); } while (0);
|
||||
@ -520,12 +522,16 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) {
|
||||
// To set a static IP we have to disable DHCP first
|
||||
if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) {
|
||||
esp_err_t e = tcpip_adapter_dhcpc_stop(self->if_id);
|
||||
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e);
|
||||
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) {
|
||||
_esp_exceptions(e);
|
||||
}
|
||||
ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(self->if_id, &info));
|
||||
ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(self->if_id, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
|
||||
} else if (self->if_id == WIFI_IF_AP) {
|
||||
esp_err_t e = tcpip_adapter_dhcps_stop(WIFI_IF_AP);
|
||||
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e);
|
||||
if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) {
|
||||
_esp_exceptions(e);
|
||||
}
|
||||
ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(WIFI_IF_AP, &info));
|
||||
ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(WIFI_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info));
|
||||
ESP_EXCEPTIONS(tcpip_adapter_dhcps_start(WIFI_IF_AP));
|
||||
|
@ -293,7 +293,9 @@ STATIC mp_obj_t socket_bind(const mp_obj_t arg0, const mp_obj_t arg1) {
|
||||
_socket_getaddrinfo(arg1, &res);
|
||||
int r = lwip_bind(self->fd, res->ai_addr, res->ai_addrlen);
|
||||
lwip_freeaddrinfo(res);
|
||||
if (r < 0) exception_from_errno(errno);
|
||||
if (r < 0) {
|
||||
exception_from_errno(errno);
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
|
||||
@ -302,7 +304,9 @@ STATIC mp_obj_t socket_listen(const mp_obj_t arg0, const mp_obj_t arg1) {
|
||||
socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
|
||||
int backlog = mp_obj_get_int(arg1);
|
||||
int r = lwip_listen(self->fd, backlog);
|
||||
if (r < 0) exception_from_errno(errno);
|
||||
if (r < 0) {
|
||||
exception_from_errno(errno);
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
|
||||
@ -318,8 +322,12 @@ STATIC mp_obj_t socket_accept(const mp_obj_t arg0) {
|
||||
MP_THREAD_GIL_EXIT();
|
||||
new_fd = lwip_accept(self->fd, &addr, &addr_len);
|
||||
MP_THREAD_GIL_ENTER();
|
||||
if (new_fd >= 0) break;
|
||||
if (errno != EAGAIN) exception_from_errno(errno);
|
||||
if (new_fd >= 0) {
|
||||
break;
|
||||
}
|
||||
if (errno != EAGAIN) {
|
||||
exception_from_errno(errno);
|
||||
}
|
||||
check_for_exceptions();
|
||||
}
|
||||
if (new_fd < 0) {
|
||||
@ -445,8 +453,9 @@ void _socket_settimeout(socket_obj_t *sock, uint64_t timeout_ms) {
|
||||
|
||||
STATIC mp_obj_t socket_settimeout(const mp_obj_t arg0, const mp_obj_t arg1) {
|
||||
socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
|
||||
if (arg1 == mp_const_none) _socket_settimeout(self, UINT64_MAX);
|
||||
else {
|
||||
if (arg1 == mp_const_none) {
|
||||
_socket_settimeout(self, UINT64_MAX);
|
||||
} else {
|
||||
#if MICROPY_PY_BUILTINS_FLOAT
|
||||
_socket_settimeout(self, mp_obj_get_float(arg1) * 1000L);
|
||||
#else
|
||||
@ -459,8 +468,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout);
|
||||
|
||||
STATIC mp_obj_t socket_setblocking(const mp_obj_t arg0, const mp_obj_t arg1) {
|
||||
socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
|
||||
if (mp_obj_is_true(arg1)) _socket_settimeout(self, UINT64_MAX);
|
||||
else _socket_settimeout(self, 0);
|
||||
if (mp_obj_is_true(arg1)) {
|
||||
_socket_settimeout(self, UINT64_MAX);
|
||||
} else {
|
||||
_socket_settimeout(self, 0);
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
|
||||
@ -559,11 +571,17 @@ int _socket_send(socket_obj_t *sock, const char *data, size_t datalen) {
|
||||
MP_THREAD_GIL_EXIT();
|
||||
int r = lwip_write(sock->fd, data + sentlen, datalen - sentlen);
|
||||
MP_THREAD_GIL_ENTER();
|
||||
if (r < 0 && errno != EWOULDBLOCK) exception_from_errno(errno);
|
||||
if (r > 0) sentlen += r;
|
||||
if (r < 0 && errno != EWOULDBLOCK) {
|
||||
exception_from_errno(errno);
|
||||
}
|
||||
if (r > 0) {
|
||||
sentlen += r;
|
||||
}
|
||||
check_for_exceptions();
|
||||
}
|
||||
if (sentlen == 0) mp_raise_OSError(MP_ETIMEDOUT);
|
||||
if (sentlen == 0) {
|
||||
mp_raise_OSError(MP_ETIMEDOUT);
|
||||
}
|
||||
return sentlen;
|
||||
}
|
||||
|
||||
@ -583,7 +601,9 @@ STATIC mp_obj_t socket_sendall(const mp_obj_t arg0, const mp_obj_t arg1) {
|
||||
mp_buffer_info_t bufinfo;
|
||||
mp_get_buffer_raise(arg1, &bufinfo, MP_BUFFER_READ);
|
||||
int r = _socket_send(sock, bufinfo.buf, bufinfo.len);
|
||||
if (r < bufinfo.len) mp_raise_OSError(MP_ETIMEDOUT);
|
||||
if (r < bufinfo.len) {
|
||||
mp_raise_OSError(MP_ETIMEDOUT);
|
||||
}
|
||||
return mp_const_none;
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_sendall_obj, socket_sendall);
|
||||
@ -606,7 +626,9 @@ STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_
|
||||
MP_THREAD_GIL_EXIT();
|
||||
int ret = lwip_sendto(self->fd, bufinfo.buf, bufinfo.len, 0, (struct sockaddr *)&to, sizeof(to));
|
||||
MP_THREAD_GIL_ENTER();
|
||||
if (ret > 0) return mp_obj_new_int_from_uint(ret);
|
||||
if (ret > 0) {
|
||||
return mp_obj_new_int_from_uint(ret);
|
||||
}
|
||||
if (ret == -1 && errno != EWOULDBLOCK) {
|
||||
exception_from_errno(errno);
|
||||
}
|
||||
@ -638,8 +660,13 @@ STATIC mp_uint_t socket_stream_write(mp_obj_t self_in, const void *buf, mp_uint_
|
||||
MP_THREAD_GIL_EXIT();
|
||||
int r = lwip_write(sock->fd, buf, size);
|
||||
MP_THREAD_GIL_ENTER();
|
||||
if (r > 0) return r;
|
||||
if (r < 0 && errno != EWOULDBLOCK) { *errcode = errno; return MP_STREAM_ERROR; }
|
||||
if (r > 0) {
|
||||
return r;
|
||||
}
|
||||
if (r < 0 && errno != EWOULDBLOCK) {
|
||||
*errcode = errno;
|
||||
return MP_STREAM_ERROR;
|
||||
}
|
||||
check_for_exceptions();
|
||||
}
|
||||
*errcode = sock->retries == 0 ? MP_EWOULDBLOCK : MP_ETIMEDOUT;
|
||||
@ -650,13 +677,22 @@ STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintpt
|
||||
socket_obj_t *socket = self_in;
|
||||
if (request == MP_STREAM_POLL) {
|
||||
|
||||
fd_set rfds; FD_ZERO(&rfds);
|
||||
fd_set wfds; FD_ZERO(&wfds);
|
||||
fd_set efds; FD_ZERO(&efds);
|
||||
fd_set rfds;
|
||||
FD_ZERO(&rfds);
|
||||
fd_set wfds;
|
||||
FD_ZERO(&wfds);
|
||||
fd_set efds;
|
||||
FD_ZERO(&efds);
|
||||
struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 };
|
||||
if (arg & MP_STREAM_POLL_RD) FD_SET(socket->fd, &rfds);
|
||||
if (arg & MP_STREAM_POLL_WR) FD_SET(socket->fd, &wfds);
|
||||
if (arg & MP_STREAM_POLL_HUP) FD_SET(socket->fd, &efds);
|
||||
if (arg & MP_STREAM_POLL_RD) {
|
||||
FD_SET(socket->fd, &rfds);
|
||||
}
|
||||
if (arg & MP_STREAM_POLL_WR) {
|
||||
FD_SET(socket->fd, &wfds);
|
||||
}
|
||||
if (arg & MP_STREAM_POLL_HUP) {
|
||||
FD_SET(socket->fd, &efds);
|
||||
}
|
||||
|
||||
int r = select((socket->fd) + 1, &rfds, &wfds, &efds, &timeout);
|
||||
if (r < 0) {
|
||||
@ -665,9 +701,15 @@ STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintpt
|
||||
}
|
||||
|
||||
mp_uint_t ret = 0;
|
||||
if (FD_ISSET(socket->fd, &rfds)) ret |= MP_STREAM_POLL_RD;
|
||||
if (FD_ISSET(socket->fd, &wfds)) ret |= MP_STREAM_POLL_WR;
|
||||
if (FD_ISSET(socket->fd, &efds)) ret |= MP_STREAM_POLL_HUP;
|
||||
if (FD_ISSET(socket->fd, &rfds)) {
|
||||
ret |= MP_STREAM_POLL_RD;
|
||||
}
|
||||
if (FD_ISSET(socket->fd, &wfds)) {
|
||||
ret |= MP_STREAM_POLL_WR;
|
||||
}
|
||||
if (FD_ISSET(socket->fd, &efds)) {
|
||||
ret |= MP_STREAM_POLL_HUP;
|
||||
}
|
||||
return ret;
|
||||
} else if (request == MP_STREAM_CLOSE) {
|
||||
if (socket->fd >= 0) {
|
||||
@ -761,7 +803,9 @@ STATIC mp_obj_t esp_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) {
|
||||
mp_obj_list_append(ret_list, mp_obj_new_tuple(5, addrinfo_objs));
|
||||
}
|
||||
|
||||
if (res) lwip_freeaddrinfo(res);
|
||||
if (res) {
|
||||
lwip_freeaddrinfo(res);
|
||||
}
|
||||
return ret_list;
|
||||
}
|
||||
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_socket_getaddrinfo_obj, 2, 6, esp_socket_getaddrinfo);
|
||||
|
@ -4,9 +4,10 @@ from flashbdev import bdev
|
||||
|
||||
try:
|
||||
if bdev:
|
||||
uos.mount(bdev, '/')
|
||||
uos.mount(bdev, "/")
|
||||
except OSError:
|
||||
import inisetup
|
||||
|
||||
vfs = inisetup.setup()
|
||||
|
||||
gc.collect()
|
||||
|
@ -1,4 +1,4 @@
|
||||
from esp32 import Partition
|
||||
|
||||
bdev = Partition.find(Partition.TYPE_DATA, label='vfs')
|
||||
bdev = Partition.find(Partition.TYPE_DATA, label="vfs")
|
||||
bdev = bdev[0] if bdev else None
|
||||
|
@ -1,41 +1,49 @@
|
||||
import uos
|
||||
from flashbdev import bdev
|
||||
|
||||
|
||||
def check_bootsec():
|
||||
buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE
|
||||
bdev.readblocks(0, buf)
|
||||
empty = True
|
||||
for b in buf:
|
||||
if b != 0xff:
|
||||
if b != 0xFF:
|
||||
empty = False
|
||||
break
|
||||
if empty:
|
||||
return True
|
||||
fs_corrupted()
|
||||
|
||||
|
||||
def fs_corrupted():
|
||||
import time
|
||||
|
||||
while 1:
|
||||
print("""\
|
||||
print(
|
||||
"""\
|
||||
FAT filesystem appears to be corrupted. If you had important data there, you
|
||||
may want to make a flash snapshot to try to recover it. Otherwise, perform
|
||||
factory reprogramming of MicroPython firmware (completely erase flash, followed
|
||||
by firmware programming).
|
||||
""")
|
||||
"""
|
||||
)
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def setup():
|
||||
check_bootsec()
|
||||
print("Performing initial setup")
|
||||
uos.VfsFat.mkfs(bdev)
|
||||
vfs = uos.VfsFat(bdev)
|
||||
uos.mount(vfs, '/')
|
||||
uos.mount(vfs, "/")
|
||||
with open("boot.py", "w") as f:
|
||||
f.write("""\
|
||||
f.write(
|
||||
"""\
|
||||
# This file is executed on every boot (including wake-boot from deepsleep)
|
||||
#import esp
|
||||
#esp.osdebug(None)
|
||||
#import webrepl
|
||||
#webrepl.start()
|
||||
""")
|
||||
"""
|
||||
)
|
||||
return vfs
|
||||
|
@ -22,8 +22,7 @@ class NeoPixel:
|
||||
|
||||
def __getitem__(self, index):
|
||||
offset = index * self.bpp
|
||||
return tuple(self.buf[offset + self.ORDER[i]]
|
||||
for i in range(self.bpp))
|
||||
return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
|
||||
|
||||
def fill(self, color):
|
||||
for i in range(self.n):
|
||||
|
@ -114,7 +114,8 @@ STATIC void freertos_entry(void *arg) {
|
||||
ext_thread_entry(arg);
|
||||
}
|
||||
vTaskDelete(NULL);
|
||||
for (;;);
|
||||
for (;;) {;
|
||||
}
|
||||
}
|
||||
|
||||
void mp_thread_create_ex(void *(*entry)(void *), void *arg, size_t *stack_size, int priority, char *name) {
|
||||
@ -197,7 +198,7 @@ void mp_thread_mutex_init(mp_thread_mutex_t *mutex) {
|
||||
}
|
||||
|
||||
int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait) {
|
||||
return (pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0));
|
||||
return pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0);
|
||||
}
|
||||
|
||||
void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) {
|
||||
|
@ -1,5 +1,5 @@
|
||||
freeze('$(PORT_DIR)/modules')
|
||||
freeze('$(MPY_DIR)/tools', ('upip.py', 'upip_utarfile.py'))
|
||||
freeze('$(MPY_DIR)/drivers/dht', 'dht.py')
|
||||
freeze('$(MPY_DIR)/drivers/onewire')
|
||||
include('$(MPY_DIR)/extmod/webrepl/manifest.py')
|
||||
freeze("$(PORT_DIR)/modules")
|
||||
freeze("$(MPY_DIR)/tools", ("upip.py", "upip_utarfile.py"))
|
||||
freeze("$(MPY_DIR)/drivers/dht", "dht.py")
|
||||
freeze("$(MPY_DIR)/drivers/onewire")
|
||||
include("$(MPY_DIR)/extmod/webrepl/manifest.py")
|
||||
|
@ -1,27 +1,27 @@
|
||||
include('manifest.py')
|
||||
include("manifest.py")
|
||||
|
||||
# drivers
|
||||
freeze('$(MPY_DIR)/drivers/display', 'ssd1306.py')
|
||||
freeze("$(MPY_DIR)/drivers/display", "ssd1306.py")
|
||||
|
||||
# file utilities
|
||||
freeze('$(MPY_LIB_DIR)/upysh', 'upysh.py')
|
||||
freeze("$(MPY_LIB_DIR)/upysh", "upysh.py")
|
||||
|
||||
# uasyncio
|
||||
freeze('$(MPY_LIB_DIR)/uasyncio', 'uasyncio/__init__.py')
|
||||
freeze('$(MPY_LIB_DIR)/uasyncio.core', 'uasyncio/core.py')
|
||||
freeze("$(MPY_LIB_DIR)/uasyncio", "uasyncio/__init__.py")
|
||||
freeze("$(MPY_LIB_DIR)/uasyncio.core", "uasyncio/core.py")
|
||||
|
||||
# requests
|
||||
freeze('$(MPY_LIB_DIR)/urequests', 'urequests.py')
|
||||
freeze('$(MPY_LIB_DIR)/urllib.urequest', 'urllib/urequest.py')
|
||||
freeze("$(MPY_LIB_DIR)/urequests", "urequests.py")
|
||||
freeze("$(MPY_LIB_DIR)/urllib.urequest", "urllib/urequest.py")
|
||||
|
||||
# umqtt with examples
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'umqtt/simple.py')
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.robust', 'umqtt/robust.py')
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'example_pub_button.py')
|
||||
freeze('$(MPY_LIB_DIR)/umqtt.simple', 'example_sub_led.py')
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.simple", "umqtt/simple.py")
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.robust", "umqtt/robust.py")
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.simple", "example_pub_button.py")
|
||||
freeze("$(MPY_LIB_DIR)/umqtt.simple", "example_sub_led.py")
|
||||
|
||||
# HTTP examples
|
||||
freeze('$(MPY_DIR)/examples/network', 'http_client.py')
|
||||
freeze('$(MPY_DIR)/examples/network', 'http_client_ssl.py')
|
||||
freeze('$(MPY_DIR)/examples/network', 'http_server.py')
|
||||
freeze('$(MPY_DIR)/examples/network', 'http_server_ssl.py')
|
||||
freeze("$(MPY_DIR)/examples/network", "http_client.py")
|
||||
freeze("$(MPY_DIR)/examples/network", "http_client_ssl.py")
|
||||
freeze("$(MPY_DIR)/examples/network", "http_server.py")
|
||||
freeze("$(MPY_DIR)/examples/network", "http_server_ssl.py")
|
||||
|
@ -46,19 +46,29 @@ void /*ICACHE_RAM_ATTR*/ esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32
|
||||
|
||||
uint32_t irq_state = mp_hal_quiet_timing_enter();
|
||||
for (t = time0;; t = time0) {
|
||||
if(pix & mask) t = time1; // Bit high duration
|
||||
while(((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start
|
||||
if (pix & mask) {
|
||||
t = time1; // Bit high duration
|
||||
}
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < period) {
|
||||
; // Wait for bit start
|
||||
}
|
||||
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high
|
||||
startTime = c; // Save start time
|
||||
while(((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration
|
||||
while (((c = mp_hal_ticks_cpu()) - startTime) < t) {
|
||||
; // Wait high duration
|
||||
}
|
||||
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low
|
||||
if (!(mask >>= 1)) { // Next bit/byte
|
||||
if(p >= end) break;
|
||||
if (p >= end) {
|
||||
break;
|
||||
}
|
||||
pix = *p++;
|
||||
mask = 0x80;
|
||||
}
|
||||
}
|
||||
while((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit
|
||||
while ((mp_hal_ticks_cpu() - startTime) < period) {
|
||||
; // Wait for last bit
|
||||
}
|
||||
mp_hal_quiet_timing_exit(irq_state);
|
||||
}
|
||||
|
||||
|
@ -81,8 +81,7 @@ typedef enum {
|
||||
} TIMER_INT_MODE;
|
||||
|
||||
STATIC void ICACHE_FLASH_ATTR
|
||||
pwm_insert_sort(struct pwm_single_param pwm[], uint8 n)
|
||||
{
|
||||
pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) {
|
||||
uint8 i;
|
||||
|
||||
for (i = 1; i < n; i++) {
|
||||
@ -118,8 +117,7 @@ STATIC volatile uint8 critical = 0;
|
||||
} while (0)
|
||||
|
||||
void ICACHE_FLASH_ATTR
|
||||
pwm_start(void)
|
||||
{
|
||||
pwm_start(void) {
|
||||
uint8 i, j;
|
||||
PWM_DBG("--Function pwm_start() is called\n");
|
||||
PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num);
|
||||
@ -212,8 +210,7 @@ pwm_start(void)
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void ICACHE_FLASH_ATTR
|
||||
pwm_set_duty(int16_t duty, uint8 channel)
|
||||
{
|
||||
pwm_set_duty(int16_t duty, uint8 channel) {
|
||||
uint8 i;
|
||||
for (i = 0; i < pwm_channel_num; i++) {
|
||||
if (pwm_out_io_num[i] == channel) {
|
||||
@ -221,8 +218,9 @@ pwm_set_duty(int16_t duty, uint8 channel)
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(i==pwm_channel_num) // non found
|
||||
if (i == pwm_channel_num) { // non found
|
||||
return;
|
||||
}
|
||||
|
||||
LOCK_PWM(critical); // enter critical
|
||||
if (duty < 1) {
|
||||
@ -242,8 +240,7 @@ pwm_set_duty(int16_t duty, uint8 channel)
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void ICACHE_FLASH_ATTR
|
||||
pwm_set_freq(uint16 freq, uint8 channel)
|
||||
{
|
||||
pwm_set_freq(uint16 freq, uint8 channel) {
|
||||
LOCK_PWM(critical); // enter critical
|
||||
if (freq > PWM_FREQ_MAX) {
|
||||
pwm.freq = PWM_FREQ_MAX;
|
||||
@ -264,8 +261,7 @@ pwm_set_freq(uint16 freq, uint8 channel)
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
uint16 ICACHE_FLASH_ATTR
|
||||
pwm_get_duty(uint8 channel)
|
||||
{
|
||||
pwm_get_duty(uint8 channel) {
|
||||
uint8 i;
|
||||
for (i = 0; i < pwm_channel_num; i++) {
|
||||
if (pwm_out_io_num[i] == channel) {
|
||||
@ -273,8 +269,9 @@ pwm_get_duty(uint8 channel)
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(i==pwm_channel_num) // non found
|
||||
if (i == pwm_channel_num) { // non found
|
||||
return 0;
|
||||
}
|
||||
|
||||
return pwm.duty[channel];
|
||||
}
|
||||
@ -286,8 +283,7 @@ pwm_get_duty(uint8 channel)
|
||||
* Returns : uint16 : pwm frequency
|
||||
*******************************************************************************/
|
||||
uint16 ICACHE_FLASH_ATTR
|
||||
pwm_get_freq(uint8 channel)
|
||||
{
|
||||
pwm_get_freq(uint8 channel) {
|
||||
return pwm.freq;
|
||||
}
|
||||
|
||||
@ -299,8 +295,7 @@ pwm_get_freq(uint8 channel)
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
STATIC void ICACHE_RAM_ATTR
|
||||
pwm_tim1_intr_handler(void *dummy)
|
||||
{
|
||||
pwm_tim1_intr_handler(void *dummy) {
|
||||
(void)dummy;
|
||||
uint8 local_toggle = pwm_toggle; // pwm_toggle may change outside
|
||||
RTC_CLR_REG_MASK(FRC1_INT_ADDRESS, FRC1_INT_CLR_MASK);
|
||||
@ -335,8 +330,7 @@ pwm_tim1_intr_handler(void *dummy)
|
||||
* Returns : NONE
|
||||
*******************************************************************************/
|
||||
void ICACHE_FLASH_ATTR
|
||||
pwm_init(void)
|
||||
{
|
||||
pwm_init(void) {
|
||||
uint8 i;
|
||||
|
||||
RTC_REG_WRITE(FRC1_CTRL_ADDRESS, //FRC2_AUTO_RELOAD|
|
||||
@ -376,8 +370,9 @@ pwm_add(uint8_t pin_id, uint32_t pin_mux, uint32_t pin_func){
|
||||
}
|
||||
uint8 i;
|
||||
for (i = 0; i < PWM_CHANNEL; i++) {
|
||||
if(pwm_out_io_num[i]==channel) // already exist
|
||||
if (pwm_out_io_num[i] == channel) { // already exist
|
||||
return channel;
|
||||
}
|
||||
if (pwm_out_io_num[i] == -1) { // empty exist
|
||||
LOCK_PWM(critical); // enter critical
|
||||
pwm_out_io_num[i] = channel;
|
||||
|
@ -38,7 +38,9 @@ static inline int prio2id(uint8_t prio) {
|
||||
int id = PRIO2ID(prio);
|
||||
if (id < 0 || id >= MP_ARRAY_SIZE(emu_tasks)) {
|
||||
printf("task prio out of range: %d\n", prio);
|
||||
while (1);
|
||||
while (1) {
|
||||
;
|
||||
}
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
@ -38,6 +38,6 @@ DWORD get_fattime(void) {
|
||||
timeutils_struct_time_t tm;
|
||||
timeutils_seconds_since_2000_to_struct_time(secs, &tm);
|
||||
|
||||
return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
|
||||
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1));
|
||||
return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) |
|
||||
((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1);
|
||||
}
|
||||
|
@ -188,7 +188,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
|
||||
uint32_t addr_bits, uint32_t addr_data,
|
||||
uint32_t dout_bits, uint32_t dout_data,
|
||||
uint32_t din_bits, uint32_t dummy_bits) {
|
||||
while (spi_busy(spi_no)) {}; // Wait for SPI to be ready
|
||||
while (spi_busy(spi_no)) {
|
||||
}
|
||||
; // Wait for SPI to be ready
|
||||
|
||||
// Enable SPI Functions
|
||||
// Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.
|
||||
@ -280,7 +282,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
|
||||
|
||||
// Return DIN data
|
||||
if (din_bits) {
|
||||
while (spi_busy(spi_no)) {}; // Wait for SPI transaction to complete
|
||||
while (spi_busy(spi_no)) {
|
||||
}
|
||||
; // Wait for SPI transaction to complete
|
||||
if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_RD_BYTE_ORDER) {
|
||||
// Assuming data in is written to MSB. TBC
|
||||
return READ_PERI_REG(SPI_W0(spi_no)) >> (32 - din_bits);
|
||||
@ -301,7 +305,9 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data,
|
||||
Just do minimal work needed to send 8 bits.
|
||||
*/
|
||||
inline void spi_tx8fast(uint8_t spi_no, uint8_t dout_data) {
|
||||
while (spi_busy(spi_no)) {}; // Wait for SPI to be ready
|
||||
while (spi_busy(spi_no)) {
|
||||
}
|
||||
; // Wait for SPI to be ready
|
||||
|
||||
// Enable SPI Functions
|
||||
// Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set.
|
||||
|
@ -8,33 +8,33 @@ assert len(sys.argv) == 4
|
||||
|
||||
md5 = hashlib.md5()
|
||||
|
||||
with open(sys.argv[3], 'wb') as fout:
|
||||
with open(sys.argv[3], "wb") as fout:
|
||||
|
||||
with open(sys.argv[1], 'rb') as f:
|
||||
with open(sys.argv[1], "rb") as f:
|
||||
data_flash = f.read()
|
||||
fout.write(data_flash)
|
||||
# First 4 bytes include flash size, etc. which may be changed
|
||||
# by esptool.py, etc.
|
||||
md5.update(data_flash[4:])
|
||||
print('flash ', len(data_flash))
|
||||
print("flash ", len(data_flash))
|
||||
|
||||
with open(sys.argv[2], 'rb') as f:
|
||||
with open(sys.argv[2], "rb") as f:
|
||||
data_rom = f.read()
|
||||
|
||||
pad = b'\xff' * (SEGS_MAX_SIZE - len(data_flash))
|
||||
pad = b"\xff" * (SEGS_MAX_SIZE - len(data_flash))
|
||||
assert len(pad) >= 4
|
||||
fout.write(pad[:-4])
|
||||
md5.update(pad[:-4])
|
||||
len_data = struct.pack("I", SEGS_MAX_SIZE + len(data_rom))
|
||||
fout.write(len_data)
|
||||
md5.update(len_data)
|
||||
print('padding ', len(pad))
|
||||
print("padding ", len(pad))
|
||||
|
||||
fout.write(data_rom)
|
||||
md5.update(data_rom)
|
||||
print('irom0text', len(data_rom))
|
||||
print("irom0text", len(data_rom))
|
||||
|
||||
fout.write(md5.digest())
|
||||
|
||||
print('total ', SEGS_MAX_SIZE + len(data_rom))
|
||||
print('md5 ', md5.hexdigest())
|
||||
print("total ", SEGS_MAX_SIZE + len(data_rom))
|
||||
print("md5 ", md5.hexdigest())
|
||||
|
@ -1,13 +1,15 @@
|
||||
import gc
|
||||
|
||||
gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
|
||||
import uos
|
||||
from flashbdev import bdev
|
||||
|
||||
if bdev:
|
||||
try:
|
||||
uos.mount(bdev, '/')
|
||||
uos.mount(bdev, "/")
|
||||
except:
|
||||
import inisetup
|
||||
|
||||
inisetup.setup()
|
||||
|
||||
gc.collect()
|
||||
|
@ -1,11 +1,12 @@
|
||||
import esp
|
||||
|
||||
|
||||
class FlashBdev:
|
||||
|
||||
SEC_SIZE = 4096
|
||||
RESERVED_SECS = 1
|
||||
START_SEC = esp.flash_user_start() // SEC_SIZE + RESERVED_SECS
|
||||
NUM_BLK = 0x6b - RESERVED_SECS
|
||||
NUM_BLK = 0x6B - RESERVED_SECS
|
||||
|
||||
def __init__(self, blocks=NUM_BLK):
|
||||
self.blocks = blocks
|
||||
@ -32,6 +33,7 @@ class FlashBdev:
|
||||
esp.flash_erase(arg + self.START_SEC)
|
||||
return 0
|
||||
|
||||
|
||||
size = esp.flash_size()
|
||||
if size < 1024 * 1024:
|
||||
bdev = None
|
||||
|
@ -2,45 +2,55 @@ import uos
|
||||
import network
|
||||
from flashbdev import bdev
|
||||
|
||||
|
||||
def wifi():
|
||||
import ubinascii
|
||||
|
||||
ap_if = network.WLAN(network.AP_IF)
|
||||
essid = b"MicroPython-%s" % ubinascii.hexlify(ap_if.config("mac")[-3:])
|
||||
ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"micropythoN")
|
||||
|
||||
|
||||
def check_bootsec():
|
||||
buf = bytearray(bdev.SEC_SIZE)
|
||||
bdev.readblocks(0, buf)
|
||||
empty = True
|
||||
for b in buf:
|
||||
if b != 0xff:
|
||||
if b != 0xFF:
|
||||
empty = False
|
||||
break
|
||||
if empty:
|
||||
return True
|
||||
fs_corrupted()
|
||||
|
||||
|
||||
def fs_corrupted():
|
||||
import time
|
||||
|
||||
while 1:
|
||||
print("""\
|
||||
print(
|
||||
"""\
|
||||
The FAT filesystem starting at sector %d with size %d sectors appears to
|
||||
be corrupted. If you had important data there, you may want to make a flash
|
||||
snapshot to try to recover it. Otherwise, perform factory reprogramming
|
||||
of MicroPython firmware (completely erase flash, followed by firmware
|
||||
programming).
|
||||
""" % (bdev.START_SEC, bdev.blocks))
|
||||
"""
|
||||
% (bdev.START_SEC, bdev.blocks)
|
||||
)
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def setup():
|
||||
check_bootsec()
|
||||
print("Performing initial setup")
|
||||
wifi()
|
||||
uos.VfsFat.mkfs(bdev)
|
||||
vfs = uos.VfsFat(bdev)
|
||||
uos.mount(vfs, '/')
|
||||
uos.mount(vfs, "/")
|
||||
with open("boot.py", "w") as f:
|
||||
f.write("""\
|
||||
f.write(
|
||||
"""\
|
||||
# This file is executed on every boot (including wake-boot from deepsleep)
|
||||
#import esp
|
||||
#esp.osdebug(None)
|
||||
@ -50,5 +60,6 @@ import gc
|
||||
#import webrepl
|
||||
#webrepl.start()
|
||||
gc.collect()
|
||||
""")
|
||||
"""
|
||||
)
|
||||
return vfs
|
||||
|
@ -21,8 +21,7 @@ class NeoPixel:
|
||||
|
||||
def __getitem__(self, index):
|
||||
offset = index * self.bpp
|
||||
return tuple(self.buf[offset + self.ORDER[i]]
|
||||
for i in range(self.bpp))
|
||||
return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
|
||||
|
||||
def fill(self, color):
|
||||
for i in range(self.n):
|
||||
|
@ -13,9 +13,10 @@ NTP_DELTA = 3155673600
|
||||
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
|
||||
host = "pool.ntp.org"
|
||||
|
||||
|
||||
def time():
|
||||
NTP_QUERY = bytearray(48)
|
||||
NTP_QUERY[0] = 0x1b
|
||||
NTP_QUERY[0] = 0x1B
|
||||
addr = socket.getaddrinfo(host, 123)[0][-1]
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
@ -27,11 +28,13 @@ def time():
|
||||
val = struct.unpack("!I", msg[40:44])[0]
|
||||
return val - NTP_DELTA
|
||||
|
||||
|
||||
# There's currently no timezone support in MicroPython, so
|
||||
# utime.localtime() will return UTC time (as if it was .gmtime())
|
||||
def settime():
|
||||
t = time()
|
||||
import machine
|
||||
import utime
|
||||
|
||||
tm = utime.localtime(t)
|
||||
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
|
||||
|
@ -10,13 +10,16 @@ def main():
|
||||
fid = esp.flash_id()
|
||||
|
||||
print("FlashROM:")
|
||||
print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16))
|
||||
print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xFF, fid & 0xFF00 | fid >> 16))
|
||||
|
||||
print("Flash bootloader data:")
|
||||
SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"}
|
||||
FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"}
|
||||
FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xF: "80MHz"}
|
||||
print("Byte @2: %02x" % ROM[2])
|
||||
print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))
|
||||
print(
|
||||
"Byte @3: %02x (Flash size: %s Flash freq: %s)"
|
||||
% (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xF))
|
||||
)
|
||||
print("Firmware checksum:")
|
||||
print(esp.check_fw())
|
||||
|
||||
@ -24,7 +27,9 @@ def main():
|
||||
print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig())
|
||||
print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig())
|
||||
print("Free WiFi driver buffers of type:")
|
||||
for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")):
|
||||
for i, comm in enumerate(
|
||||
("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")
|
||||
):
|
||||
print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm))
|
||||
print("lwIP PCBs:")
|
||||
lwip.print_pcbs()
|
||||
|
@ -131,11 +131,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
|
||||
|
@ -1,7 +1,7 @@
|
||||
print('uPy')
|
||||
print('a long string that is not interned')
|
||||
print('a string that has unicode αβγ chars')
|
||||
print(b'bytes 1234\x01')
|
||||
print("uPy")
|
||||
print("a long string that is not interned")
|
||||
print("a string that has unicode αβγ chars")
|
||||
print(b"bytes 1234\x01")
|
||||
print(123456789)
|
||||
for i in range(4):
|
||||
print(i)
|
||||
|
@ -84,11 +84,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
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user