all: Use non-u versions of built-in modules.

This changes almost all uses of "u-module" to just "module" for the
following built-in modules:
- binascii
- collections
- errno
- io
- json
- socket
- struct
- sys
- time

There are some remaining uses of "u-module" naming, for the cases where the
built-in module is extended in Python, eg `python-stdlib/os` uses `uos`.

Also, there are remaining uses of `utime` when non-standard (compared to
CPython) functions are used, like `utime.ticks_ms()`.

Signed-off-by: Damien George <damien@micropython.org>
pull/880/head
Damien George 2024-06-12 13:58:32 +10:00
rodzic 7271f1ddc7
commit 84ba452113
22 zmienionych plików z 72 dodań i 84 usunięć

Wyświetl plik

@ -5,7 +5,7 @@ from micropython import const
import machine import machine
from utime import sleep_ms from utime import sleep_ms
from ustruct import calcsize, pack_into from ustruct import calcsize, pack_into
import uerrno import errno
# for set_orient # for set_orient
PORTRAIT = const(0) PORTRAIT = const(0)
@ -110,7 +110,7 @@ class LCD160CR:
return return
t -= 1 t -= 1
sleep_ms(1) sleep_ms(1)
raise OSError(uerrno.ETIMEDOUT) raise OSError(errno.ETIMEDOUT)
def oflush(self, n=255): def oflush(self, n=255):
t = 5000 t = 5000
@ -121,7 +121,7 @@ class LCD160CR:
return return
t -= 1 t -= 1
machine.idle() machine.idle()
raise OSError(uerrno.ETIMEDOUT) raise OSError(errno.ETIMEDOUT)
def iflush(self): def iflush(self):
t = 5000 t = 5000
@ -131,7 +131,7 @@ class LCD160CR:
return return
t -= 1 t -= 1
sleep_ms(1) sleep_ms(1)
raise OSError(uerrno.ETIMEDOUT) raise OSError(errno.ETIMEDOUT)
#### MISC METHODS #### #### MISC METHODS ####
@ -254,7 +254,7 @@ class LCD160CR:
return self.buf[3][1] | self.buf[3][2] << 8 return self.buf[3][1] | self.buf[3][2] << 8
t -= 1 t -= 1
sleep_ms(1) sleep_ms(1)
raise OSError(uerrno.ETIMEDOUT) raise OSError(errno.ETIMEDOUT)
def get_line(self, x, y, buf): def get_line(self, x, y, buf):
l = len(buf) // 2 l = len(buf) // 2
@ -268,7 +268,7 @@ class LCD160CR:
return return
t -= 1 t -= 1
sleep_ms(1) sleep_ms(1)
raise OSError(uerrno.ETIMEDOUT) raise OSError(errno.ETIMEDOUT)
def screen_dump(self, buf, x=0, y=0, w=None, h=None): def screen_dump(self, buf, x=0, y=0, w=None, h=None):
if w is None: if w is None:

Wyświetl plik

@ -1,7 +1,7 @@
"""Test for nrf24l01 module. Portable between MicroPython targets.""" """Test for nrf24l01 module. Portable between MicroPython targets."""
import usys import sys
import ustruct as struct import struct
import utime import utime
from machine import Pin, SPI, SoftSPI from machine import Pin, SPI, SoftSPI
from nrf24l01 import NRF24L01 from nrf24l01 import NRF24L01
@ -14,20 +14,20 @@ _RX_POLL_DELAY = const(15)
# initiator may be a slow device. Value tested with Pyboard, ESP32 and ESP8266. # initiator may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
_RESPONDER_SEND_DELAY = const(10) _RESPONDER_SEND_DELAY = const(10)
if usys.platform == "pyboard": if sys.platform == "pyboard":
spi = SPI(2) # miso : Y7, mosi : Y8, sck : Y6 spi = SPI(2) # miso : Y7, mosi : Y8, sck : Y6
cfg = {"spi": spi, "csn": "Y5", "ce": "Y4"} cfg = {"spi": spi, "csn": "Y5", "ce": "Y4"}
elif usys.platform == "esp8266": # Hardware SPI elif sys.platform == "esp8266": # Hardware SPI
spi = SPI(1) # miso : 12, mosi : 13, sck : 14 spi = SPI(1) # miso : 12, mosi : 13, sck : 14
cfg = {"spi": spi, "csn": 4, "ce": 5} cfg = {"spi": spi, "csn": 4, "ce": 5}
elif usys.platform == "esp32": # Software SPI elif sys.platform == "esp32": # Software SPI
spi = SoftSPI(sck=Pin(25), mosi=Pin(33), miso=Pin(32)) spi = SoftSPI(sck=Pin(25), mosi=Pin(33), miso=Pin(32))
cfg = {"spi": spi, "csn": 26, "ce": 27} cfg = {"spi": spi, "csn": 26, "ce": 27}
elif usys.platform == "rp2": # Hardware SPI with explicit pin definitions elif sys.platform == "rp2": # Hardware SPI with explicit pin definitions
spi = SPI(0, sck=Pin(2), mosi=Pin(3), miso=Pin(4)) spi = SPI(0, sck=Pin(2), mosi=Pin(3), miso=Pin(4))
cfg = {"spi": spi, "csn": 5, "ce": 6} cfg = {"spi": spi, "csn": 5, "ce": 6}
else: else:
raise ValueError("Unsupported platform {}".format(usys.platform)) raise ValueError("Unsupported platform {}".format(sys.platform))
# Addresses are in little-endian format. They correspond to big-endian # Addresses are in little-endian format. They correspond to big-endian
# 0xf0f0f0f0e1, 0xf0f0f0f0d2 # 0xf0f0f0f0e1, 0xf0f0f0f0d2

Wyświetl plik

@ -1,13 +1,6 @@
import utime from time import gmtime
import socket
try: import struct
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org' # The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org" host = "pool.ntp.org"
@ -53,7 +46,7 @@ def time():
# Convert timestamp from NTP format to our internal format # Convert timestamp from NTP format to our internal format
EPOCH_YEAR = utime.gmtime(0)[0] EPOCH_YEAR = gmtime(0)[0]
if EPOCH_YEAR == 2000: if EPOCH_YEAR == 2000:
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 3155673600 NTP_DELTA = 3155673600
@ -71,5 +64,5 @@ def settime():
t = time() t = time()
import machine import machine
tm = utime.gmtime(t) tm = gmtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0)) machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

Wyświetl plik

@ -1,15 +1,15 @@
import uio import io
import usocket import socket
import udnspkt import udnspkt
s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dns_addr = usocket.getaddrinfo("127.0.0.1", 53)[0][-1] dns_addr = socket.getaddrinfo("127.0.0.1", 53)[0][-1]
def resolve(domain, is_ipv6): def resolve(domain, is_ipv6):
buf = uio.BytesIO(48) buf = io.BytesIO(48)
udnspkt.make_req(buf, "google.com", is_ipv6) udnspkt.make_req(buf, "google.com", is_ipv6)
v = buf.getvalue() v = buf.getvalue()
print("query: ", v) print("query: ", v)
@ -17,11 +17,11 @@ def resolve(domain, is_ipv6):
resp = s.recv(1024) resp = s.recv(1024)
print("resp:", resp) print("resp:", resp)
buf = uio.BytesIO(resp) buf = io.BytesIO(resp)
addr = udnspkt.parse_resp(buf, is_ipv6) addr = udnspkt.parse_resp(buf, is_ipv6)
print("bin addr:", addr) print("bin addr:", addr)
print("addr:", usocket.inet_ntop(usocket.AF_INET6 if is_ipv6 else usocket.AF_INET, addr)) print("addr:", socket.inet_ntop(socket.AF_INET6 if is_ipv6 else socket.AF_INET, addr))
resolve("google.com", False) resolve("google.com", False)

Wyświetl plik

@ -1,6 +1,3 @@
import uio
def write_fqdn(buf, name): def write_fqdn(buf, name):
parts = name.split(".") parts = name.split(".")
for p in parts: for p in parts:

Wyświetl plik

@ -1,4 +1,4 @@
import utime import time
from . import simple from . import simple
@ -7,7 +7,7 @@ class MQTTClient(simple.MQTTClient):
DEBUG = False DEBUG = False
def delay(self, i): def delay(self, i):
utime.sleep(self.DELAY) time.sleep(self.DELAY)
def log(self, in_reconnect, e): def log(self, in_reconnect, e):
if self.DEBUG: if self.DEBUG:

Wyświetl plik

@ -1,5 +1,5 @@
import time import time
import ubinascii import binascii
import machine import machine
from umqtt.simple import MQTTClient from umqtt.simple import MQTTClient
from machine import Pin from machine import Pin
@ -10,7 +10,7 @@ button = Pin(0, Pin.IN)
# Default MQTT server to connect to # Default MQTT server to connect to
SERVER = "192.168.1.35" SERVER = "192.168.1.35"
CLIENT_ID = ubinascii.hexlify(machine.unique_id()) CLIENT_ID = binascii.hexlify(machine.unique_id())
TOPIC = b"led" TOPIC = b"led"

Wyświetl plik

@ -1,6 +1,6 @@
from umqtt.simple import MQTTClient from umqtt.simple import MQTTClient
from machine import Pin from machine import Pin
import ubinascii import binascii
import machine import machine
import micropython import micropython
@ -11,7 +11,7 @@ led = Pin(2, Pin.OUT, value=1)
# Default MQTT server to connect to # Default MQTT server to connect to
SERVER = "192.168.1.35" SERVER = "192.168.1.35"
CLIENT_ID = ubinascii.hexlify(machine.unique_id()) CLIENT_ID = binascii.hexlify(machine.unique_id())
TOPIC = b"led" TOPIC = b"led"

Wyświetl plik

@ -1,6 +1,6 @@
import usocket as socket import socket
import ustruct as struct import struct
from ubinascii import hexlify from binascii import hexlify
class MQTTException(Exception): class MQTTException(Exception):

Wyświetl plik

@ -1,4 +1,4 @@
import usocket import socket
def urlopen(url, data=None, method="GET"): def urlopen(url, data=None, method="GET"):
@ -22,10 +22,10 @@ def urlopen(url, data=None, method="GET"):
host, port = host.split(":", 1) host, port = host.split(":", 1)
port = int(port) port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
ai = ai[0] ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2]) s = socket.socket(ai[0], ai[1], ai[2])
try: try:
s.connect(ai[-1]) s.connect(ai[-1])
if proto == "https:": if proto == "https:":

Wyświetl plik

@ -1,4 +1,4 @@
import usocket import socket
class Response: class Response:
@ -28,9 +28,9 @@ class Response:
return str(self.content, self.encoding) return str(self.content, self.encoding)
def json(self): def json(self):
import ujson import json
return ujson.loads(self.content) return json.loads(self.content)
def request( def request(
@ -51,11 +51,11 @@ def request(
chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None) chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None)
if auth is not None: if auth is not None:
import ubinascii import binascii
username, password = auth username, password = auth
formated = b"{}:{}".format(username, password) formated = b"{}:{}".format(username, password)
formated = str(ubinascii.b2a_base64(formated)[:-1], "ascii") formated = str(binascii.b2a_base64(formated)[:-1], "ascii")
headers["Authorization"] = "Basic {}".format(formated) headers["Authorization"] = "Basic {}".format(formated)
try: try:
@ -76,14 +76,14 @@ def request(
host, port = host.split(":", 1) host, port = host.split(":", 1)
port = int(port) port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM) ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
ai = ai[0] ai = ai[0]
resp_d = None resp_d = None
if parse_headers is not False: if parse_headers is not False:
resp_d = {} resp_d = {}
s = usocket.socket(ai[0], usocket.SOCK_STREAM, ai[2]) s = socket.socket(ai[0], socket.SOCK_STREAM, ai[2])
if timeout is not None: if timeout is not None:
# Note: settimeout is not supported on all platforms, will raise # Note: settimeout is not supported on all platforms, will raise
@ -103,9 +103,9 @@ def request(
if json is not None: if json is not None:
assert data is None assert data is None
import ujson from json import dumps
data = ujson.dumps(json) data = dumps(json)
if "Content-Type" not in headers: if "Content-Type" not in headers:
headers["Content-Type"] = "application/json" headers["Content-Type"] = "application/json"

Wyświetl plik

@ -17,20 +17,20 @@ class Socket:
return self._read_buffer.readline() return self._read_buffer.readline()
class usocket: class socket:
AF_INET = 2 AF_INET = 2
SOCK_STREAM = 1 SOCK_STREAM = 1
IPPROTO_TCP = 6 IPPROTO_TCP = 6
@staticmethod @staticmethod
def getaddrinfo(host, port, af=0, type=0, flags=0): def getaddrinfo(host, port, af=0, type=0, flags=0):
return [(usocket.AF_INET, usocket.SOCK_STREAM, usocket.IPPROTO_TCP, "", ("127.0.0.1", 80))] return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", 80))]
def socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP): def socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP):
return Socket() return Socket()
sys.modules["usocket"] = usocket sys.modules["socket"] = socket
# ruff: noqa: E402 # ruff: noqa: E402
import requests import requests

Wyświetl plik

@ -3,7 +3,7 @@ Minimal and functional version of CPython's argparse module.
""" """
import sys import sys
from ucollections import namedtuple from collections import namedtuple
class _ArgError(BaseException): class _ArgError(BaseException):

Wyświetl plik

@ -1,5 +1,5 @@
from binascii import * from binascii import *
import utime import time
data = b"zlutoucky kun upel dabelske ody" data = b"zlutoucky kun upel dabelske ody"
h = hexlify(data) h = hexlify(data)
@ -14,10 +14,10 @@ if data2 != data:
a2b_base64(b"as==") == b"j" a2b_base64(b"as==") == b"j"
start = utime.time() start = time.time()
for x in range(100000): for x in range(100000):
d = unhexlify(h) d = unhexlify(h)
print("100000 iterations in: " + str(utime.time() - start)) print("100000 iterations in: " + str(time.time() - start))
print("OK") print("OK")

Wyświetl plik

@ -62,7 +62,7 @@ class Error(Exception):
error = Error # backward compatibility error = Error # backward compatibility
try: try:
from ucollections import OrderedDict from collections import OrderedDict
except ImportError: except ImportError:
OrderedDict = None OrderedDict = None

Wyświetl plik

@ -1,4 +1,4 @@
import uio import io
c = {} c = {}
@ -18,11 +18,11 @@ def resource_stream(package, resource):
else: else:
d = "." d = "."
# if d[0] != "/": # if d[0] != "/":
# import uos # import os
# d = uos.getcwd() + "/" + d # d = os.getcwd() + "/" + d
c[package] = d + "/" c[package] = d + "/"
p = c[package] p = c[package]
if isinstance(p, dict): if isinstance(p, dict):
return uio.BytesIO(p[resource]) return io.BytesIO(p[resource])
return open(p + resource, "rb") return open(p + resource, "rb")

Wyświetl plik

@ -1,4 +1,4 @@
import utime import time
from machine import Timer from machine import Timer
@ -7,5 +7,5 @@ t2 = Timer(1, 3)
t1.callback(lambda t: print(t, "tick1")) t1.callback(lambda t: print(t, "tick1"))
t2.callback(lambda t: print(t, "tick2")) t2.callback(lambda t: print(t, "tick2"))
utime.sleep(3) time.sleep(3)
print("done") print("done")

Wyświetl plik

@ -1,9 +1,7 @@
import ffilib import ffilib
import uctypes import uctypes
import array import array
import uos
import os import os
import utime
from signal import * from signal import *
libc = ffilib.libc() libc = ffilib.libc()

Wyświetl plik

@ -1,5 +1,5 @@
import array import array
import ustruct as struct import struct
import errno as errno_ import errno as errno_
import stat as stat_ import stat as stat_
import ffilib import ffilib

Wyświetl plik

@ -1,8 +1,8 @@
import ffilib import ffilib
import uctypes import uctypes
import ustruct import struct
from ucollections import namedtuple from collections import namedtuple
libc = ffilib.libc() libc = ffilib.libc()
@ -20,6 +20,6 @@ def getpwnam(user):
if not passwd: if not passwd:
raise KeyError("getpwnam(): name not found: {}".format(user)) raise KeyError("getpwnam(): name not found: {}".format(user))
passwd_fmt = "SSIISSS" passwd_fmt = "SSIISSS"
passwd = uctypes.bytes_at(passwd, ustruct.calcsize(passwd_fmt)) passwd = uctypes.bytes_at(passwd, struct.calcsize(passwd_fmt))
passwd = ustruct.unpack(passwd_fmt, passwd) passwd = struct.unpack(passwd_fmt, passwd)
return struct_passwd(*passwd) return struct_passwd(*passwd)

Wyświetl plik

@ -1,5 +1,5 @@
import ffi import ffi
import ustruct as struct import struct
import os import os
import errno import errno
import ffilib import ffilib

Wyświetl plik

@ -1,6 +1,6 @@
from utime import * from utime import *
from ucollections import namedtuple from collections import namedtuple
import ustruct import struct
import uctypes import uctypes
import ffi import ffi
import ffilib import ffilib
@ -34,13 +34,13 @@ _struct_time = namedtuple(
def _tuple_to_c_tm(t): def _tuple_to_c_tm(t):
return ustruct.pack( return struct.pack(
"@iiiiiiiii", t[5], t[4], t[3], t[2], t[1] - 1, t[0] - 1900, (t[6] + 1) % 7, t[7] - 1, t[8] "@iiiiiiiii", t[5], t[4], t[3], t[2], t[1] - 1, t[0] - 1900, (t[6] + 1) % 7, t[7] - 1, t[8]
) )
def _c_tm_to_tuple(tm): def _c_tm_to_tuple(tm):
t = ustruct.unpack("@iiiiiiiii", tm) t = struct.unpack("@iiiiiiiii", tm)
return _struct_time( return _struct_time(
t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8] t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8]
) )
@ -64,7 +64,7 @@ def localtime(t=None):
t = time() t = time()
t = int(t) t = int(t)
a = ustruct.pack("l", t) a = struct.pack("l", t)
tm_p = localtime_(a) tm_p = localtime_(a)
return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36)) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36))
@ -74,7 +74,7 @@ def gmtime(t=None):
t = time() t = time()
t = int(t) t = int(t)
a = ustruct.pack("l", t) a = struct.pack("l", t)
tm_p = gmtime_(a) tm_p = gmtime_(a)
return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36)) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36))