def reset(spi1, cs, force=False, reply=5): if force == False and __class__.isconnected(): return True try: # create wiznet5k nic __class__.nic = network.WIZNET5K(spi=spi1, cs=cs) # time.sleep_ms(500) # wait at ready to connect except Exception as e: print(e) return False return True
def main(): import network, pyb nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.A3, pyb.Pin.board.A4) while not nic.isconnected(): pass nic.active(1) nic.ifconfig( ('192.168.178.135', '255.255.255.0', '192.168.178.1', '192.168.178.1')) ip_address_v4 = nic.ifconfig()[0] s = socket.socket() ai = socket.getaddrinfo(ip_address_v4, 80) print("Bind address info:", ai) addr = ai[0][-1] print("IP Address: ", addr) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:80/") counter = 0 while True: sock, addr = s.accept() #s.setblocking(False) print("Client address:", addr) stream = sock.makefile("rwb") req = stream.readline().decode("ascii") method, path, protocol = req.split(" ") print("Got", method, "request for", path) while True: h = stream.readline().decode("ascii").strip() if h == "": break print("Got HTTP header:", h) stream.write((CONTENT % counter).encode("ascii")) stream.close() sock.close() counter += 1 print()
版本:v1.0 日期:2019.11 作者:01Studio 说明:通过Socket编程实现pyBoard+W5500以太网模块连接网络。 ''' import network, usocket, pyb from machine import I2C, Pin from ssd1306 import SSD1306_I2C #初始化相关模块,OLED引脚换成了Y9、Y10 i2c = I2C(sda=Pin('Y10'), scl=Pin('Y9')) oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) #以太网模块初始化 nic = network.WIZNET5K(pyb.SPI(2), 'Y5', 'Y4') nic.active(True) nic.ifconfig('dhcp') #判断网络是否连接成功 if nic.isconnected(): print(nic.ifconfig()) #打印IP信息 #OLED数据显示 oled.fill(0) #清屏背景黑色 oled.text('IP/Subnet/GW:', 0, 0) oled.text(nic.ifconfig()[0], 0, 20) oled.text(nic.ifconfig()[1], 0, 38) oled.text(nic.ifconfig()[2], 0, 56) oled.show()
####################################### addr = (server_ip, server_port) spi1 = SPI(4, mode=SPI.MODE_MASTER, baudrate=600 * 1000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=WIZNET5K_SPI_SCK, mosi=WIZNET5K_SPI_MOSI, miso=WIZNET5K_SPI_MISO) # create wiznet5k nic nic = network.WIZNET5K(spi=spi1, cs=WIZNET5K_SPI_CS) print("Static IP: ", nic.ifconfig()) ############################# UDP Test ############################## # The server must first know the client's IP and port number through the message sent by the client before it send the message to the client sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(5) while True: sock.sendto("Client send: hello UDP\n".encode(), addr) try: data, addr1 = sock.recvfrom(10) print("Recv from server: ", data) except Exception as e: pass time.sleep_ms(500)
def init_network(self): self._log.debug("Hal: Init") ip_address_v4 = None #connect to database _dbc.connect() #Get network record key try: network = db.networkTable.getrow() except (OSError, StopIteration): network = None self._log.debug("Hal: Network Table StopIteration") # check for network record if network: self._log.debug("Hal: init, network record present") else: self._log.debug("Hal: init, network record missing") _dbc.close() if self._utils.get_platform() == 'linux': self._log.debug("Hal: linux") if network: return True else: return False elif self._utils.get_platform() == 'pyboard': self._log.debug("Hal: pyboard") import pyb, network as ethernet if network: board = self.board() if network['spi'] == 0: self._log.debug( "Hal: pyboard, spi is empty: trying default!") if board == "PYBv3 with STM32F405RG": # connect to default setup core._nic = ethernet.WIZNET5K(pyb.SPI(1), pyb.Pin.board.A3, pyb.Pin.board.A4) # wait to connect import utime cnt = 0 while not core._nic.isconnected(): if cnt > 10: break cnt += 1 utime.sleep(1) if not core._nic.isconnected(): self._log.debug( "Hal: pyboard, spi is empty: no default setup!" ) return False else: self._log.debug( "Hal: pyboard, spi is empty: unknown board: " + board) return False if not core._nic: if board == "PYBv3 with STM32F405RG": core._nic = ethernet.WIZNET5K(pyb.SPI(network['spi']), network['pin_cs'], network['pin_rst']) else: self._log.debug("Hal: pyboard, unknown board: " + board) return False while not core._nic.isconnected(): pass #core._nic.active(1) self._nic = core._nic if network['ip']: self._nic.ifconfig((network['ip'], network['subnet'], network['gateway'], network['dns'])) else: try: self._nic.ifconfig('dhcp') except OSError as e: self._log.debug("Hal: pyboard network init OSError: " + repr(e)) return False ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: pyboard, ip: " + ip_address_v4) else: self._log.debug("Hal: pyboard, network record empty") return False elif self._utils.get_platform() == 'esp32': self._log.debug("Hal: esp32") if network: import network as wifi # AP mode self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic self._nic.active(True) # SSID already set? if not network['ssid']: self._log.debug("Hal: esp32, ssid empty") # No ssid set yet, let's connect to the strongest unencrypted wifi ap possible wlan_list = self._nic.scan() # parse list, find the strongest open network strength = -500 wlan_ap = None for wlan in wlan_list: self._log.debug("Hal: esp32, Scan: Ssid found: " + str(wlan[0], 'utf8') + " Strength: " + str(wlan[3]) + ' dBm' + " Security: " + str(wlan[4])) if wlan[3] > strength and wlan[4] == 0: strength = wlan[3] wlan_ap = str(wlan[0], 'utf8') self._log.debug( "Hal: esp32, Scan: Open ssid found: " + wlan_ap) if wlan_ap == None: return False else: #Activate station if not self._nic.isconnected(): self._nic.connect(wlan_ap) while not self._nic.isconnected(): pass else: #Activate station if not self._nic.isconnected(): self._nic.connect(network['ssid'], network['key']) while not self._nic.isconnected(): pass ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: esp32, ip: " + ip_address_v4) #deactivate AP ap_if = wifi.WLAN(wifi.AP_IF) ap_if.active(False) elif self._utils.get_platform() == 'esp8266': if network: if not network['ssid']: self._log.debug("Hal: esp8266, ssid empty") return False import network as wifi #Activate station self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic if not self._nic.isconnected(): self._nic.active(True) self._nic.connect(network['ssid'], network['key']) while not self._nic.isconnected(): pass ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: esp8266, ip: " + ip_address_v4) #deactivate AP ap_if = wifi.WLAN(wifi.AP_IF) ap_if.active(False) else: self._log.debug("Hal: failure") self._nic = None return False if ip_address_v4: self._log.debug("Hal: nic present") return True else: self._log.debug("Hal: nic not present") return False
import machine import utime as time import network import pyb from pyb import Timer, Pin, I2C import uasyncio as asyncio nic = network.WIZNET5K(machine.SPI(1), machine.Pin('A4', machine.Pin.OUT), machine.Pin('C5', machine.Pin.OUT)) nic.ifconfig(('192.168.1.42', '255.255.255.0', '192.168.1.1', '8.8.8.8')) backplaneI2C = I2C(1, I2C.MASTER, baudrate=200000) robotI2C = I2C(2, I2C.MASTER, baudrate=200000) blueLed = machine.Pin('B4', machine.Pin.OUT) greenLed = machine.Pin('A15', machine.Pin.OUT) def getTime(): return time.ticks_ms() class Sensor: def __init__(self, collectFunction): self.data = 0 self.lastCollectionTime = 0 self.cacheDuration = 100 self.collectFunction = collectFunction def value(self): if time.ticks_diff(getTime(),
说明:通过Socket编程实现pyBoard+W5500以太网模块与电脑服务器助手建立TCP连接,相互收发数据。 ''' import network,usocket,pyb from machine import I2C,Pin from ssd1306 import SSD1306_I2C #初始化相关模块 i2c = I2C(sda=Pin('Y10'), scl=Pin('Y9')) oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) #socket数据接收中断标志位 socket_node = 0 #初始化以太网模块 nic = network.WIZNET5K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4) nic.active(True) nic.ifconfig('dhcp') #判断网络是否连接成功 if nic.isconnected(): print(nic.ifconfig()) #打印IP信息 #OLED数据显示 oled.fill(0) #清屏背景黑色 oled.text('IP/Subnet/GW:',0,0) oled.text(nic.ifconfig()[0], 0, 20) oled.text(nic.ifconfig()[1],0,38) oled.text(nic.ifconfig()[2],0,56) oled.show()
# wizntp # ntp time base is 1900, posix 1970, micropython 2000 import pyb import network import struct import time nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4) #nic.ifconfig(('192.168.1.16', '255.255.255.0', '192.168.1.1', '75.75.75.75')) #pyb.delay(300) # wait for ifconfig rtc = pyb.RTC() # now use socket as usual from socket import * TIME2000 = 3155702400 - 4 * 3600 # timezone client = socket(AF_INET, SOCK_DGRAM) query = bytearray(48) query[0] = 0x1b client.sendto(query, ('192.168.1.4', 123)) data, address = client.recvfrom(1024) t = struct.unpack('!I', data[40:]) # hack unpack for micropy t = t[0] - TIME2000 d = time.localtime(t) rtc.datetime( (d[0], d[1], d[2], 1, d[3], d[4], d[5], 0)) # set rtc day of week bogus print('rtc', rtc.datetime()) pyb.delay(5000) print('rtc', rtc.datetime())
def init_network(self, mode = core.NET_STA): self._log.debug("Hal: Init") ip_address_v4 = None #connect to database _dbc.connect() #Get network record key try: network = db.networkTable.getrow() except (OSError, StopIteration): network = None self._log.debug("Hal: Network Table StopIteration") return False # check for network record if network: self._log.debug("Hal: init, network record present") else: self._log.debug("Hal: init, network record missing") return False _dbc.close() if self._utils.get_platform() == 'linux': self._log.debug("Hal: linux") core.initial_upyeasywifi = core.NET_ETH if network: return True else: return False elif self._utils.get_platform() == 'pyboard': self._log.debug("Hal: pyboard") import pyb, network as ethernet if network: # run in ethernet mode core.initial_upyeasywifi = core.NET_ETH # get board type board = self.board() if network['spi'] == 0: self._log.warning("Hal: pyboard, spi is empty: trying default!") if board == "PYBv3 with STM32F405RG": # connect to default setup core._nic = ethernet.WIZNET5K(pyb.SPI(1), pyb.Pin.board.A3, pyb.Pin.board.A4) # wait to connect import utime cnt = 0 while not core._nic.isconnected(): if cnt > 10: break cnt += 1 utime.sleep(1) if not core._nic.isconnected(): self._log.error("Hal: pyboard, spi is empty: no default setup!") return False else: self._log.error("Hal: pyboard, spi is empty: unknown board: "+ board) return False if not core._nic: if board == "PYBv3 with STM32F405RG": self._log.debug("Hal: Board: "+ board) core._nic = ethernet.WIZNET5K(pyb.SPI(network['spi']), network['cs'], network['rst']) else: self._log.error("Hal: pyboard, unknown board: "+ board) return False while not core._nic.isconnected(): pass core._nic.active(1) self._nic = core._nic if network['ip']: self._nic.ifconfig((network['ip'], network['subnet'], network['gateway'], network['dns'])) else: try: self._nic.ifconfig('dhcp') except (OSError, TypeError) as e: self._log.error("Hal: pyboard network init Error: "+repr(e)) return False ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: pyboard, ip: "+ip_address_v4) else: self._log.error("Hal: pyboard, network record empty") return False elif self._utils.get_platform() == 'esp32': self._log.debug("Hal: esp32") if network: import network as wifi # SSID already set? if network['mode'] == core.NET_AP or (network['mode'] == core.NET_STA and not network['ssid']): self._log.error("Hal: esp32, ssid empty") # No ssid set yet, goto AP mode! self._log.warning("Hal: init esp32 network: AP mode") self._nic = wifi.WLAN(wifi.AP_IF) core._nic = self._nic self._nic.active(True) machinename = self._utils.get_upyeasy_name() if machinename == core.initial_upyeasyname: ssidname = "{}-{}".format(core.initial_upyeasyname,self._utils.get_machine_id()) else: ssidname = "{}-{}".format(core.initial_upyeasyname,machinename) self._nic.config(essid=ssidname) ip_address_v4 = self._nic.ifconfig()[0] core.initial_upyeasywifi = core.NET_AP else: # STA mode self._log.debug("Hal: init esp32 network: STA mode") self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic self._nic.active(True) #Activate station if not self._nic.isconnected(): self._nic.connect(network['ssid'], network['key']) # get start time nicstart = self.get_time_sec() import utime # wait until connected or 30s timeout while not self._nic.isconnected(): # wait 1sec utime.sleep(1) # get current sec time nicnow = self.get_time_sec() # timeout reached? if nicnow > nicstart+30: break if self._nic.isconnected(): # if ip address set: use it! if network['ip']: self._nic.ifconfig((network['ip'], network['subnet'], network['gateway'], network['dns'])) # get ip address ip_address_v4 = self._nic.ifconfig()[0] # network mode STA+AP if network['mode']=='STA+AP': self._log.debug("Hal: init esp32 network: STA+AP mode") self._apnic = wifi.WLAN(wifi.AP_IF) self._apnic.active(True) machinename = self._utils.get_upyeasy_name() if machinename == core.initial_upyeasyname: ssidname = "{}-{}".format(core.initial_upyeasyname,self._utils.get_machine_id()) else: ssidname = "{}-{}".format(core.initial_upyeasyname,machinename) self._apnic.config(essid=ssidname) core.initial_upyeasywifi = core.NET_STA_AP else: core.initial_upyeasywifi = core.NET_STA else: self._log.warning("Hal: esp32, wifi connect attempts unsuccesfull, going to AP mode") # disconnect nic to prevent endless wifi connect trials self._nic.disconnect() # goto AP mode! self._log.debug("Hal: init esp32 network: AP mode") self._nic = wifi.WLAN(wifi.AP_IF) core._nic = self._nic self._nic.active(True) machinename = self._utils.get_upyeasy_name() if machinename == core.initial_upyeasyname: ssidname = "{}-{}".format(core.initial_upyeasyname,self._utils.get_machine_id()) else: ssidname = "{}-{}".format(core.initial_upyeasyname,machinename) self._nic.config(essid=ssidname) ip_address_v4 = self._nic.ifconfig()[0] core.initial_upyeasywifi = core.NET_AP self._log.debug("Hal: esp32, ip: "+ip_address_v4) else: self._log.error("Hal: esp32 network db record not available") elif self._utils.get_platform() == 'esp8266': if network: if not network['ssid']: self._log.debug("Hal: esp8266, ssid empty") return False import network as wifi #Activate station self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic if not self._nic.isconnected(): self._nic.active(True) self._nic.connect(network['ssid'], network['key']) while not self._nic.isconnected(): pass ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: esp8266, ip: "+ip_address_v4) #deactivate AP ap_if = wifi.WLAN(wifi.AP_IF) ap_if.active(False) else: self._log.error("Hal: failure") self._nic = None return False if ip_address_v4: self._log.debug("Hal: nic present") return True else: self._log.error("Hal: nic not present") return False
def init_network(self): self._log.debug("Hal: Init") ip_address_v4 = None #connect to database _dbc.connect() #Get network record key try: network = db.networkTable.getrow() except (OSError, StopIteration): network = None self._log.debug("Hal: Network Table StopIteration") # check for network record if network: self._log.debug("Hal: init, network record present") else: self._log.debug("Hal: init, network record missing") _dbc.close() if self._utils.get_platform() == 'linux': self._log.debug("Hal: linux") if network: return True else: return False elif self._utils.get_platform() == 'pyboard': self._log.debug("Hal: pyboard") import pyb, network as ethernet if network: board = self.board() if network['spi'] == 0: self._log.debug( "Hal: pyboard, spi is empty: trying default!") if board == "PYBv3 with STM32F405RG": # connect to default setup core._nic = ethernet.WIZNET5K(pyb.SPI(1), pyb.Pin.board.A3, pyb.Pin.board.A4) # wait to connect import utime cnt = 0 while not core._nic.isconnected(): if cnt > 10: break cnt += 1 utime.sleep(1) if not core._nic.isconnected(): self._log.debug( "Hal: pyboard, spi is empty: no default setup!" ) return False else: self._log.debug( "Hal: pyboard, spi is empty: unknown board: " + board) return False if not core._nic: if board == "PYBv3 with STM32F405RG": core._nic = ethernet.WIZNET5K(pyb.SPI(network['spi']), network['cs'], network['rst']) else: self._log.debug("Hal: pyboard, unknown board: " + board) return False while not core._nic.isconnected(): pass #core._nic.active(1) self._nic = core._nic if network['ip']: self._nic.ifconfig((network['ip'], network['subnet'], network['gateway'], network['dns'])) else: try: self._nic.ifconfig('dhcp') except (OSError, TypeError) as e: self._log.debug("Hal: pyboard network init Error: " + repr(e)) return False ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: pyboard, ip: " + ip_address_v4) else: self._log.debug("Hal: pyboard, network record empty") return False elif self._utils.get_platform() == 'esp32': self._log.debug("Hal: esp32") if network: import network as wifi # SSID already set? if not network['ssid']: self._log.debug("Hal: esp32, ssid empty") # No ssid set yet, goto AP mode! self._nic = wifi.WLAN(wifi.AP_IF) core._nic = self._nic self._nic.active(True) self._nic.config(essid="uPyEasy") core.initial_upyeasywifi = "AP" else: # STA mode self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic self._nic.active(True) #Activate station if not self._nic.isconnected(): self._nic.connect(network['ssid'], network['key']) while not self._nic.isconnected(): pass # if ip address set: use it! if network['ip']: self._nic.ifconfig( (network['ip'], network['subnet'], network['gateway'], network['dns'])) core.initial_upyeasywifi = "STA" ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: esp32, ip: " + ip_address_v4) elif self._utils.get_platform() == 'esp8266': if network: if not network['ssid']: self._log.debug("Hal: esp8266, ssid empty") return False import network as wifi #Activate station self._nic = wifi.WLAN(wifi.STA_IF) core._nic = self._nic if not self._nic.isconnected(): self._nic.active(True) self._nic.connect(network['ssid'], network['key']) while not self._nic.isconnected(): pass ip_address_v4 = self._nic.ifconfig()[0] self._log.debug("Hal: esp8266, ip: " + ip_address_v4) #deactivate AP ap_if = wifi.WLAN(wifi.AP_IF) ap_if.active(False) else: self._log.debug("Hal: failure") self._nic = None return False if ip_address_v4: self._log.debug("Hal: nic present") return True else: self._log.debug("Hal: nic not present") return False
from pyb import SPI, Pin import network nic = network.WIZNET5K( SPI(1), Pin.board.X5, Pin.board.X4 ) print( "Activate") nic.active( True ) # Fixing static IP # nic.ifconfig(('10.0.0.77', '255.255.255.0', '10.0.0.240', '8.8.8.8')) print( "Querying DHCP for address" ) nic.ifconfig('dhcp') print( "getting IP config" ) print( nic.ifconfig() ) # returns ('192.168.1.60', '255.255.255.0', '192.168.1.1', '192.168.1.1') print( nic.isconnected() ) # returns True
<p>Hello #%d from uPyEasy!</p> </body> </html> """ app = picoweb.WebApp(__name__) @app.route("/") def index(req, resp): yield from picoweb.start_response(resp) yield from resp.awrite(CONTENT) class plugins(object): def __init__(self) : print("init") async def asyncdevices(self): print("async") import network,pyb nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.A3, pyb.Pin.board.A4) while not nic.isconnected(): pass nic.active(1) nic.ifconfig(('192.168.178.100', '255.255.255.0', '192.168.178.1', '192.168.178.1')) loop = asyncio.get_event_loop() _plugins = plugins() loop.create_task(_plugins.asyncdevices()) app.run(host="0.0.0.0", port=80,debug=False)