Exemplo n.º 1
0
 def update_poll(self):
     """
     Call this method inside your main event loop to get the server
     check for new incoming client requests. When a request comes in,
     the application callable will be invoked.
     """
     for sock in self._client_sock:
         if sock.available():
             environ = self._get_environ(sock)
             result = self.application(environ, self._start_response)
             self.finish_response(result, sock)
             self._client_sock.remove(sock)
             break
     for sock in self._client_sock:
         if sock.status == wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSED:
             self._client_sock.remove(sock)
     for _ in range(len(self._client_sock), MAX_SOCK_NUM):
         try:
             new_sock = socket.socket()
             new_sock.settimeout(self._timeout)
             new_sock.bind((None, self.port))
             new_sock.listen()
             self._client_sock.append(new_sock)
         except RuntimeError:
             pass
    def __init__(self, eth, mac_address, timeout=1, timeout_response=1, debug=False):
        self._debug = debug
        self._timeout = timeout
        self._response_timeout = timeout_response
        self._mac_address = mac_address

        # Initalize a new UDP socket for DHCP
        socket.set_interface(eth)
        self._sock = socket.socket(type=socket.SOCK_DGRAM)
        self._sock.settimeout(timeout)

        # DHCP state machine
        self._dhcp_state = STATE_DHCP_START
        self._initial_xid = 0
        self._transaction_id = 0

        # DHCP server configuration
        self.dhcp_server_ip = 0
        self.local_ip = 0
        self.gateway_ip = 0
        self.subnet_mask = 0
        self.dns_server_ip = 0
        # Lease configuration
        self._lease_time = 0
        self._last_check_lease_ms = 0
        self._renew_in_sec = 0
        self._rebind_in_sec = 0
        self._t1 = 0
        self._t2 = 0
Exemplo n.º 3
0
    def __init__(self, iface, dns_address, debug=False):
        self._debug = debug
        self._iface = iface
        socket.set_interface(iface)
        self._sock = socket.socket(type=socket.SOCK_DGRAM)
        self._sock.settimeout(1)

        self._dns_server = dns_address
        self._host = 0
        self._request_id = 0  # request identifier
        self._pkt_buf = bytearray()
Exemplo n.º 4
0
    def __init__(self, iface, ntp_address, utc, debug=False):
        self._debug = debug
        self._iface = iface
        socket.set_interface(self._iface)
        self._sock = socket.socket(type=socket.SOCK_DGRAM)
        self._sock.settimeout(1)
        self._utc = utc

        self._ntp_server = ntp_address
        self._host = 0
        self._request_id = 0  # request identifier

        self._pkt_buf_ = bytearray([0x23] + [0x00] * 55)
Exemplo n.º 5
0
 def start(self):
     """
     Starts the server and begins listening for incoming connections.
     Call update_poll in the main loop for the application callable to be
     invoked on receiving an incoming request.
     """
     for _ in range(MAX_SOCK_NUM):
         new_sock = socket.socket()
         new_sock.settimeout(self._timeout)
         new_sock.bind((None, self.port))
         new_sock.listen()
         self._client_sock.append(new_sock)
     if self._debug:
         ip = _the_interface.pretty_ip(_the_interface.ip_address)
         print("Server available at {0}:{1}".format(ip, self.port))
Exemplo n.º 6
0
 def update_poll(self):
     """
     Call this method inside your main event loop to get the server
     check for new incoming client requests. When a request comes in,
     the application callable will be invoked.
     """
     add_sock = []
     for sock in self._client_sock:
         if sock.available():
             environ = self._get_environ(sock)
             result = self.application(environ, self._start_response)
             self.finish_response(result, sock)
             self._client_sock.remove(sock)
             new_sock = socket.socket()
             new_sock.settimeout(self._timeout)
             new_sock.bind((None, self.port))
             new_sock.listen()
             add_sock.append(new_sock)
     self._client_sock.extend(add_sock)
    def __init__(self,
                 eth,
                 mac_address,
                 hostname=None,
                 response_timeout=3,
                 debug=False):
        self._debug = debug
        self._response_timeout = response_timeout
        self._mac_address = mac_address

        # Initalize a new UDP socket for DHCP
        socket.set_interface(eth)
        self._sock = socket.socket(type=socket.SOCK_DGRAM)
        self._sock.settimeout(response_timeout)

        # DHCP state machine
        self._dhcp_state = STATE_DHCP_START
        self._initial_xid = 0
        self._transaction_id = 0

        # DHCP server configuration
        self.dhcp_server_ip = 0
        self.local_ip = 0
        self.gateway_ip = 0
        self.subnet_mask = 0
        self.dns_server_ip = 0

        # Lease configuration
        self._lease_time = 0
        self._last_check_lease_ms = 0
        self._renew_in_sec = 0
        self._rebind_in_sec = 0
        self._t1 = 0
        self._t2 = 0

        # Host name
        mac_string = "".join("{:02X}".format(o) for o in mac_address)
        self._hostname = bytes(
            (hostname
             or "WIZnet{}").split(".")[0].format(mac_string)[:42], "utf-8")
Exemplo n.º 8
0
ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# edit host and port to match server
HOST = "192.168.10.10"
PORT = 5000
TIMEOUT = 5
INTERVAL = 5
MAXBUF = 256

while True:
    print("Create TCP Client Socket")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(TIMEOUT)

    print("Connecting")
    s.connect((HOST, PORT))

    size = s.send(b'Hello, world')
    print("Sent", size, "bytes")

    buf = s.recv(MAXBUF)
    print('Received', buf)

    s.close()

    time.sleep(INTERVAL)
Exemplo n.º 9
0
    def _dhcp_state_machine(self):
        """DHCP state machine without wait loops to enable cooperative multi tasking
        This state machine is used both by the initial blocking lease request and
        the non-blocking DHCP maintenance function"""
        if self._eth.link_status:
            if self._dhcp_state == STATE_DHCP_DISCONN:
                self._dhcp_state = STATE_DHCP_START
        else:
            if self._dhcp_state != STATE_DHCP_DISCONN:
                self._dhcp_state = STATE_DHCP_DISCONN
                self.dhcp_server_ip = BROADCAST_SERVER_ADDR
                self._last_lease_time = 0
                reset_ip = (0, 0, 0, 0)
                self._eth.ifconfig = (reset_ip, reset_ip, reset_ip, reset_ip)
                if self._sock is not None:
                    self._sock.close()
                    self._sock = None

        if self._dhcp_state == STATE_DHCP_START:
            self._start_time = time.monotonic()
            self._transaction_id = (self._transaction_id + 1) & 0x7FFFFFFF
            try:
                self._sock = socket.socket(type=socket.SOCK_DGRAM)
            except RuntimeError:
                if self._debug:
                    print("* DHCP: Failed to allocate socket")
                self._dhcp_state = STATE_DHCP_WAIT
            else:
                self._sock.settimeout(self._response_timeout)
                self._sock.bind((None, 68))
                self._sock.connect((self.dhcp_server_ip, DHCP_SERVER_PORT))
                if self._last_lease_time == 0 or time.monotonic() > (
                        self._last_lease_time + self._lease_time):
                    if self._debug:
                        print("* DHCP: Send discover to {}".format(
                            self.dhcp_server_ip))
                    self.send_dhcp_message(
                        STATE_DHCP_DISCOVER,
                        (time.monotonic() - self._start_time))
                    self._dhcp_state = STATE_DHCP_DISCOVER
                else:
                    if self._debug:
                        print("* DHCP: Send request to {}".format(
                            self.dhcp_server_ip))
                    self.send_dhcp_message(
                        DHCP_REQUEST, (time.monotonic() - self._start_time),
                        True)
                    self._dhcp_state = STATE_DHCP_REQUEST

        elif self._dhcp_state == STATE_DHCP_DISCOVER:
            if self._sock.available():
                if self._debug:
                    print("* DHCP: Parsing OFFER")
                msg_type, xid = self.parse_dhcp_response()
                if msg_type == DHCP_OFFER:
                    # Check if transaction ID matches, otherwise it may be an offer
                    # for another device
                    if htonl(self._transaction_id) == int.from_bytes(xid, "l"):
                        if self._debug:
                            print("* DHCP: Send request to {}".format(
                                self.dhcp_server_ip))
                        self._transaction_id = (self._transaction_id +
                                                1) & 0x7FFFFFFF
                        self.send_dhcp_message(
                            DHCP_REQUEST,
                            (time.monotonic() - self._start_time))
                        self._dhcp_state = STATE_DHCP_REQUEST
                    else:
                        if self._debug:
                            print(
                                "* DHCP: Received OFFER with non-matching xid")
                else:
                    if self._debug:
                        print("* DHCP: Received DHCP Message is not OFFER")

        elif self._dhcp_state == STATE_DHCP_REQUEST:
            if self._sock.available():
                if self._debug:
                    print("* DHCP: Parsing ACK")
                msg_type, xid = self.parse_dhcp_response()
                # Check if transaction ID matches, otherwise it may be
                # for another device
                if htonl(self._transaction_id) == int.from_bytes(xid, "l"):
                    if msg_type == DHCP_ACK:
                        if self._debug:
                            print("* DHCP: Successful lease")
                        self._sock.close()
                        self._sock = None
                        self._dhcp_state = STATE_DHCP_LEASED
                        self._last_lease_time = self._start_time
                        if self._lease_time == 0:
                            self._lease_time = DEFAULT_LEASE_TIME
                        if self._t1 == 0:
                            # T1 is 50% of _lease_time
                            self._t1 = self._lease_time >> 1
                        if self._t2 == 0:
                            # T2 is 87.5% of _lease_time
                            self._t2 = self._lease_time - (
                                self._lease_time >> 3)
                        self._renew_in_sec = self._t1
                        self._rebind_in_sec = self._t2
                        self._eth.ifconfig = (
                            self.local_ip,
                            self.subnet_mask,
                            self.gateway_ip,
                            self.dns_server_ip,
                        )
                        gc.collect()
                    else:
                        if self._debug:
                            print("* DHCP: Received DHCP Message is not ACK")
                else:
                    if self._debug:
                        print("* DHCP: Received non-matching xid")

        elif self._dhcp_state == STATE_DHCP_WAIT:
            if time.monotonic() > (self._start_time + DHCP_WAIT_TIME):
                if self._debug:
                    print("* DHCP: Begin retry")
                self._dhcp_state = STATE_DHCP_START
                if time.monotonic() > (self._last_lease_time +
                                       self._rebind_in_sec):
                    self.dhcp_server_ip = BROADCAST_SERVER_ADDR
                if time.monotonic() > (self._last_lease_time +
                                       self._lease_time):
                    reset_ip = (0, 0, 0, 0)
                    self._eth.ifconfig = (reset_ip, reset_ip, reset_ip,
                                          reset_ip)

        elif self._dhcp_state == STATE_DHCP_LEASED:
            if time.monotonic() > (self._last_lease_time + self._renew_in_sec):
                self._dhcp_state = STATE_DHCP_START
                if self._debug:
                    print("* DHCP: Time to renew lease")

        if (self._dhcp_state in (
                STATE_DHCP_DISCOVER,
                STATE_DHCP_REQUEST,
        ) and time.monotonic() > (self._start_time + self._response_timeout)):
            self._dhcp_state = STATE_DHCP_WAIT
            if self._sock is not None:
                self._sock.close()
                self._sock = None
Exemplo n.º 10
0
eth = WIZNET5K(spi_bus, cs, is_dhcp=True, debug=False)

ethernetRst = digitalio.DigitalInOut(W5x00_RSTn)
ethernetRst.direction = digitalio.Direction.OUTPUT
ethernetRst.value = False
time.sleep(1)
ethernetRst.value = True

# edit host and port to match server
HOST = "192.168.10.10"
PORT = 5000
TIMEOUT = 5
INTERVAL = 5
MAXBUF = 256

buf = bytearray(MAXBUF)
while True:
    print("Create UDP Client Socket")
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(TIMEOUT)

    size = s.sendto(b"Hello, world", (HOST, PORT))
    print("Sent", size, "bytes")

    size, addr = s.recvfrom_into(buf)
    print("Received", buf[:size], size, "bytes from", addr)

    s.close()

    time.sleep(INTERVAL)
import digitalio
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket

print("Wiznet5k SimpleServer Test")

# For Adafruit Ethernet FeatherWing
cs = digitalio.DigitalInOut(board.D10)
# For Particle Ethernet FeatherWing
# cs = digitalio.DigitalInOut(board.D5)
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)

# Initialize ethernet interface
eth = WIZNET5K(spi_bus, cs, is_dhcp=False)

# Initialize a socket for our server
socket.set_interface(eth)
server = socket.socket()  # Allocate socket for the server
server_ip = "192.168.10.1"  # IP address of server
server_port = 50007  # Port to listen on
server.bind((server_ip, server_port))  # Bind to IP and Port
server.listen()  # Begin listening for incoming clients

conn, addr = server.accept()  # Wait for a connection from a client.
while True:
    with conn:
        data = conn.recv(1024)
        if data:  # Wait for receiving data
            print(data)
            conn.send(data)  # Echo message back to client