最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - W5500-EVB-PICO (RP2040) alwas comes back with "Socket operation failed: [Errno 107] ENOTCONN" - Stack

programmeradmin1浏览0评论

I am using W5500-EVB-PICO to connect via Ethernet to the network. Later I want to send out BME680 data to Thingspeak. Whatever I try, I always get "Socket operation failed: [Errno 107] ENOTCONN". I am trying firmware rp2_w5500_20220318_v1.04.uf2, rp2_w5500_20220421_v1.0.5.uf2 and rp2_w5500_20221111_v2.0.0.uf2.

Does someone know the issue and might help with some good solutions?

This is my minimal code example.

MAIN2.py

from machine import Pin, SPI
import network
import socket
import time

# Pin definitions
SPI_MOSI_PIN = 19
SPI_MISO_PIN = 16
SPI_SCK_PIN = 18
SPI_CS_PIN = 17
RESET_PIN = 20
LED_PIN = 25

# Initialize LED
led = Pin(LED_PIN, Pin.OUT)

def init_ethernet():
    """Initialize W5500 Ethernet connection"""
    print("\nInitializing Ethernet...")
    led.value(0)
    
    try:
        # Initialize SPI for W5500
        print("Initializing SPI...")
        spi = SPI(0, 
                  baudrate=500_000,
                  mosi=Pin(SPI_MOSI_PIN),
                  miso=Pin(SPI_MISO_PIN),
                  sck=Pin(SPI_SCK_PIN))
        
        # Initialize CS and Reset pins
        print("Initializing control pins...")
        cs = Pin(SPI_CS_PIN, Pin.OUT)
        reset = Pin(RESET_PIN, Pin.OUT)
        
        # Hard reset sequence
        print("Performing hard reset sequence...")
        cs.value(1)
        reset.value(1)
        time.sleep(0.5)
        reset.value(0)
        time.sleep(0.5)
        reset.value(1)
        time.sleep(0.5)
        
        # Initialize WIZNET5K
        print("Creating network interface...")
        nic = network.WIZNET5K(spi, cs, reset)
        time.sleep(1)
        
        # Configure network with retries
        print("Activating interface and waiting for DHCP...")
        retry_count = 0
        max_retries = 5
        connected = False
        
        while not connected and retry_count < max_retries:
            try:
                retry_count += 1
                print("\nAttempt {}/{}:".format(retry_count, max_retries))
                
                # Reset interface
                print("Resetting interface...")
                nic.active(False)
                time.sleep(1)
                nic.active(True)
                time.sleep(1)
                
                # Wait for DHCP configuration
                print("Waiting for DHCP configuration", end="")
                for _ in range(15):  # 15 second timeout
                    if nic.isconnected():
                        config = nic.ifconfig()
                        if config[0] != '0.0.0.0':  # Valid IP received
                            connected = True
                            break
                    print(".", end="")
                    time.sleep(1)
                print()
                
                if connected:
                    print("\nNetwork configured successfully:")
                    print("IP:", config[0])
                    print("Subnet:", config[1])
                    print("Gateway:", config[2])
                    print("DNS:", config[3])
                    break
                else:
                    print("DHCP configuration failed, retrying...")
                    
            except Exception as e:
                print("Attempt failed:", str(e))
                time.sleep(2)
        
        if not connected:
            raise Exception("Failed to configure network after {} attempts".format(max_retries))
            
        print("\nNetwork interface ready!")
        time.sleep(2)  # Final stabilization delay
        return nic
        
    except Exception as e:
        print("Error in init_ethernet:", str(e))
        led.value(0)
        raise

def test_network(nic):
    """Test network connectivity"""
    sock = None
    try:
        print("\nTesting network connection...")
        
        # Check basic connectivity
        print("Interface connected:", nic.isconnected())
        print("Interface active:", nic.active())
        
        # Get network config
        config = nic.ifconfig()
        print("\nNetwork configuration:")
        print("IP:", config[0])
        print("Subnet:", config[1])
        print("Gateway:", config[2])
        print("DNS:", config[3])
        
        # Test local connection first
        print("\nTesting local connection...")
        try:
            sock = socket.socket()
            sock.settimeout(5)
            print("Connecting to gateway...")
            sock.connect((config[2], 80))
            print("Gateway connection successful!")
            sock.close()
            sock = None
        except Exception as e:
            print("Gateway connection failed:", str(e))
            if sock:
                sock.close()
                sock = None
        
        # Test internet connection
        print("\nTesting internet connection...")
        try:
            sock = socket.socket()
            sock.settimeout(5)
            print("Connecting to 8.8.8.8...")
            sock.connect(("8.8.8.8", 53))
            print("Internet connection successful!")
            sock.close()
            sock = None
        except Exception as e:
            print("Internet connection failed:", str(e))
            if sock:
                sock.close()
                sock = None
        
        # Test DNS resolution
        print("\nTesting DNS resolution...")
        try:
            print("Resolving api.thingspeak...")
            addr_info = socket.getaddrinfo("api.thingspeak", 80)
            print("DNS response:", addr_info)
            server_addr = addr_info[0][-1]
            print("Server address:", server_addr)
            
            sock = socket.socket()
            sock.settimeout(10)
            print("\nConnecting to ThingSpeak...")
            sock.connect(server_addr)
            print("ThingSpeak connection successful!")
            
            print("\nSending test request...")
            request = b"GET / HTTP/1.0\r\nHost: api.thingspeak\r\n\r\n"
            sock.write(request)
            
            print("Reading response...")
            response = sock.read(256)
            if response:
                print("Response received:", response)
            else:
                print("No response received")
                
        except Exception as e:
            print("ThingSpeak connection failed:", str(e))
            
        finally:
            if sock:
                sock.close()
                print("Socket closed")
        
        return True
        
    except Exception as e:
        print("\nTest failed:", str(e))
        if sock:
            try:
                sock.close()
            except:
                pass
        return False

def main():
    """Main diagnostic loop"""
    while True:
        try:
            # Initialize ethernet
            nic = init_ethernet()
            
            # Wait for DHCP
            print("\nWaiting for DHCP...")
            for _ in range(20):
                if nic.isconnected():
                    break
                print(".", end="")
                time.sleep(1)
            print()
            
            # Run network tests
            if test_network(nic):
                led.value(1)
                print("\nAll tests completed. Press Ctrl+C to exit.")
                while True:
                    time.sleep(1)
            
        except Exception as e:
            print("Error in main loop:", str(e))
            led.value(0)
            time.sleep(5)

if __name__ == "__main__":
    main() 

The result with errors I get is:

MPY: soft reboot

Initializing Ethernet... Initializing SPI... Initializing control pins... Performing hard reset sequence... Creating network interface... Activating interface and waiting for DHCP...

Attempt 1/5: Resetting interface... netif changed 10.10.1.6 Waiting for DHCP configuration

Network configured successfully: IP: 10.10.1.6 Subnet: 255.255.255.0 Gateway: 10.10.1.1 DNS: 10.10.1.1

Network interface ready!

Waiting for DHCP...

Testing network connection... Interface connected: True Interface active: None

Network configuration: IP: 10.10.1.6 Subnet: 255.255.255.0 Gateway: 10.10.1.1 DNS: 10.10.1.1

Testing local connection... Gateway connection failed: [Errno 107] ENOTCONN

Testing internet connection... Internet connection failed: [Errno 107] ENOTCONN

Testing DNS resolution... Resolving api.thingspeak... DNS response: [(2, 1, 0, '', ('54.172.245.49', 80))] Server address: ('54.172.245.49', 80) ThingSpeak connection failed: [Errno 107] ENOTCONN Socket closed

All tests completed. Press Ctrl+C to exit.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论