├── AUTHORS ├── README.adoc ├── examples ├── AdvancedChatServer │ └── AdvancedChatServer.ino ├── BarometricPressureWebServer │ └── BarometricPressureWebServer.ino ├── ChatServer │ └── ChatServer.ino ├── DhcpAddressPrinter │ └── DhcpAddressPrinter.ino ├── DhcpChatServer │ └── DhcpChatServer.ino ├── LinkStatus │ └── LinkStatus.ino ├── TelnetClient │ └── TelnetClient.ino ├── UDPSendReceiveString │ └── UDPSendReceiveString.ino ├── UdpNtpClient │ └── UdpNtpClient.ino ├── WebClient │ └── WebClient.ino ├── WebClientRepeating │ └── WebClientRepeating.ino └── WebServer │ └── WebServer.ino ├── keywords.txt ├── library.properties └── src ├── Dhcp.cpp ├── Dhcp.h ├── Dns.cpp ├── Dns.h ├── Ethernet.cpp ├── Ethernet.h ├── EthernetClient.cpp ├── EthernetClient.h ├── EthernetServer.cpp ├── EthernetServer.h ├── EthernetUdp.cpp ├── EthernetUdp.h ├── socket.cpp └── utility ├── w5100.cpp └── w5100.h /AUTHORS: -------------------------------------------------------------------------------- 1 | 2 | Alberto Panu https://github.com/bigjohnson 3 | Alasdair Allan https://github.com/aallan 4 | Alice Pintus https://github.com/00alis 5 | Adrian McEwen https://github.com/amcewen 6 | Arduino LLC http://arduino.cc/ 7 | Arnie97 https://github.com/Arnie97 8 | Arturo Guadalupi https://github.com/agdl 9 | Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ 10 | chaveiro https://github.com/chaveiro 11 | Cristian Maglie https://github.com/cmaglie 12 | David A. Mellis https://github.com/damellis 13 | Dino Tinitigan https://github.com/bigdinotech 14 | Eddy https://github.com/eddyst 15 | Federico Vanzati https://github.com/Fede85 16 | Federico Fissore https://github.com/ffissore 17 | Jack Christensen https://github.com/JChristensen 18 | Johann Richard https://github.com/johannrichard 19 | Jordan Terrell https://github.com/iSynaptic 20 | Justin Paulin https://github.com/interwho 21 | lathoub https://github.com/lathoub 22 | Martino Facchin https://github.com/facchinm 23 | Matthias Hertel https://github.com/mathertel 24 | Matthijs Kooijman https://github.com/matthijskooijman 25 | Matt Robinson https://github.com/ribbons 26 | MCQN Ltd. http://mcqn.com/ 27 | Michael Amie https://github.com/michaelamie 28 | Michael Margolis https://github.com/michaelmargolis 29 | Norbert Truchsess https://github.com/ntruchsess 30 | Paul Stoffregen https://github.com/PaulStoffregen 31 | per1234 https://github.com/per1234 32 | Richard Sim 33 | Scott Fitzgerald https://github.com/shfitz 34 | Thibaut Viard https://github.com/aethaniel 35 | Tom Igoe https://github.com/tigoe 36 | WizNet http://www.wiznet.co.kr 37 | Zach Eveland https://github.com/zeveland 38 | 39 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Ethernet Library for Arduino = 2 | 3 | With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. 4 | 5 | For more information about this library please visit us at 6 | https://www.arduino.cc/en/Reference/Ethernet 7 | 8 | == License == 9 | 10 | Copyright (c) 2010 Arduino LLC. All right reserved. 11 | 12 | This library is free software; you can redistribute it and/or 13 | modify it under the terms of the GNU Lesser General Public 14 | License as published by the Free Software Foundation; either 15 | version 2.1 of the License, or (at your option) any later version. 16 | 17 | This library is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | Lesser General Public License for more details. 21 | 22 | You should have received a copy of the GNU Lesser General Public 23 | License along with this library; if not, write to the Free Software 24 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 25 | -------------------------------------------------------------------------------- /examples/AdvancedChatServer/AdvancedChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Advanced Chat Server 3 | 4 | A more advanced server that distributes any incoming messages 5 | to all connected clients but the client the message comes from. 6 | To use, telnet to your device's IP address and type. 7 | You can see the client's input in the serial monitor as well. 8 | Using an Arduino Wiznet Ethernet shield. 9 | 10 | Circuit: 11 | * Ethernet shield attached to pins 10, 11, 12, 13 12 | 13 | created 18 Dec 2009 14 | by David A. Mellis 15 | modified 9 Apr 2012 16 | by Tom Igoe 17 | redesigned to make use of operator== 25 Nov 2013 18 | by Norbert Truchsess 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | 25 | // Enter a MAC address and IP address for your controller below. 26 | // The IP address will be dependent on your local network. 27 | // gateway and subnet are optional: 28 | byte mac[] = { 29 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 30 | }; 31 | IPAddress ip(192, 168, 1, 177); 32 | IPAddress myDns(192, 168, 1, 1); 33 | IPAddress gateway(192, 168, 1, 1); 34 | IPAddress subnet(255, 255, 0, 0); 35 | 36 | 37 | // telnet defaults to port 23 38 | EthernetServer server(23); 39 | 40 | EthernetClient clients[8]; 41 | 42 | void setup() { 43 | // You can use Ethernet.init(pin) to configure the CS pin 44 | //Ethernet.init(10); // Most Arduino shields 45 | //Ethernet.init(5); // MKR ETH shield 46 | //Ethernet.init(0); // Teensy 2.0 47 | //Ethernet.init(20); // Teensy++ 2.0 48 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 49 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 50 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 51 | 52 | // initialize the Ethernet device 53 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 54 | 55 | // Open serial communications and wait for port to open: 56 | Serial.begin(9600); 57 | while (!Serial) { 58 | ; // wait for serial port to connect. Needed for native USB port only 59 | } 60 | 61 | // Check for Ethernet hardware present 62 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 63 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 64 | while (true) { 65 | delay(1); // do nothing, no point running without Ethernet hardware 66 | } 67 | } 68 | if (Ethernet.linkStatus() == LinkOFF) { 69 | Serial.println("Ethernet cable is not connected."); 70 | } 71 | 72 | // start listening for clients 73 | server.begin(); 74 | 75 | Serial.print("Chat server address:"); 76 | Serial.println(Ethernet.localIP()); 77 | } 78 | 79 | void loop() { 80 | // check for any new client connecting, and say hello (before any incoming data) 81 | EthernetClient newClient = server.accept(); 82 | if (newClient) { 83 | for (byte i=0; i < 8; i++) { 84 | if (!clients[i]) { 85 | Serial.print("We have a new client #"); 86 | Serial.println(i); 87 | newClient.print("Hello, client number: "); 88 | newClient.println(i); 89 | // Once we "accept", the client is no longer tracked by EthernetServer 90 | // so we must store it into our list of clients 91 | clients[i] = newClient; 92 | break; 93 | } 94 | } 95 | } 96 | 97 | // check for incoming data from all clients 98 | for (byte i=0; i < 8; i++) { 99 | if (clients[i] && clients[i].available() > 0) { 100 | // read bytes from a client 101 | byte buffer[80]; 102 | int count = clients[i].read(buffer, 80); 103 | // write the bytes to all other connected clients 104 | for (byte j=0; j < 8; j++) { 105 | if (j != i && clients[j].connected()) { 106 | clients[j].write(buffer, count); 107 | } 108 | } 109 | } 110 | } 111 | 112 | // stop any clients which disconnect 113 | for (byte i=0; i < 8; i++) { 114 | if (clients[i] && !clients[i].connected()) { 115 | Serial.print("disconnect client #"); 116 | Serial.println(i); 117 | clients[i].stop(); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /examples/BarometricPressureWebServer/BarometricPressureWebServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SCP1000 Barometric Pressure Sensor Display 3 | 4 | Serves the output of a Barometric Pressure Sensor as a web page. 5 | Uses the SPI library. For details on the sensor, see: 6 | http://www.sparkfun.com/commerce/product_info.php?products_id=8161 7 | 8 | This sketch adapted from Nathan Seidle's SCP1000 example for PIC: 9 | http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip 10 | 11 | TODO: this hardware is long obsolete. This example program should 12 | be rewritten to use https://www.sparkfun.com/products/9721 13 | 14 | Circuit: 15 | SCP1000 sensor attached to pins 6,7, and 11 - 13: 16 | DRDY: pin 6 17 | CSB: pin 7 18 | MOSI: pin 11 19 | MISO: pin 12 20 | SCK: pin 13 21 | 22 | created 31 July 2010 23 | by Tom Igoe 24 | */ 25 | 26 | #include 27 | // the sensor communicates using SPI, so include the library: 28 | #include 29 | 30 | 31 | // assign a MAC address for the Ethernet controller. 32 | // fill in your address here: 33 | byte mac[] = { 34 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 35 | }; 36 | // assign an IP address for the controller: 37 | IPAddress ip(192, 168, 1, 20); 38 | 39 | 40 | // Initialize the Ethernet server library 41 | // with the IP address and port you want to use 42 | // (port 80 is default for HTTP): 43 | EthernetServer server(80); 44 | 45 | 46 | //Sensor's memory register addresses: 47 | const int PRESSURE = 0x1F; //3 most significant bits of pressure 48 | const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure 49 | const int TEMPERATURE = 0x21; //16 bit temperature reading 50 | 51 | // pins used for the connection with the sensor 52 | // the others you need are controlled by the SPI library): 53 | const int dataReadyPin = 6; 54 | const int chipSelectPin = 7; 55 | 56 | float temperature = 0.0; 57 | long pressure = 0; 58 | long lastReadingTime = 0; 59 | 60 | void setup() { 61 | // You can use Ethernet.init(pin) to configure the CS pin 62 | //Ethernet.init(10); // Most Arduino shields 63 | //Ethernet.init(5); // MKR ETH shield 64 | //Ethernet.init(0); // Teensy 2.0 65 | //Ethernet.init(20); // Teensy++ 2.0 66 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 67 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 68 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 69 | 70 | // start the SPI library: 71 | SPI.begin(); 72 | 73 | // start the Ethernet connection 74 | Ethernet.begin(mac, ip); 75 | 76 | // Open serial communications and wait for port to open: 77 | Serial.begin(9600); 78 | while (!Serial) { 79 | ; // wait for serial port to connect. Needed for native USB port only 80 | } 81 | 82 | // Check for Ethernet hardware present 83 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 84 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 85 | while (true) { 86 | delay(1); // do nothing, no point running without Ethernet hardware 87 | } 88 | } 89 | if (Ethernet.linkStatus() == LinkOFF) { 90 | Serial.println("Ethernet cable is not connected."); 91 | } 92 | 93 | // start listening for clients 94 | server.begin(); 95 | 96 | // initalize the data ready and chip select pins: 97 | pinMode(dataReadyPin, INPUT); 98 | pinMode(chipSelectPin, OUTPUT); 99 | 100 | //Configure SCP1000 for low noise configuration: 101 | writeRegister(0x02, 0x2D); 102 | writeRegister(0x01, 0x03); 103 | writeRegister(0x03, 0x02); 104 | 105 | // give the sensor and Ethernet shield time to set up: 106 | delay(1000); 107 | 108 | //Set the sensor to high resolution mode tp start readings: 109 | writeRegister(0x03, 0x0A); 110 | 111 | } 112 | 113 | void loop() { 114 | // check for a reading no more than once a second. 115 | if (millis() - lastReadingTime > 1000) { 116 | // if there's a reading ready, read it: 117 | // don't do anything until the data ready pin is high: 118 | if (digitalRead(dataReadyPin) == HIGH) { 119 | getData(); 120 | // timestamp the last time you got a reading: 121 | lastReadingTime = millis(); 122 | } 123 | } 124 | 125 | // listen for incoming Ethernet connections: 126 | listenForEthernetClients(); 127 | } 128 | 129 | 130 | void getData() { 131 | Serial.println("Getting reading"); 132 | //Read the temperature data 133 | int tempData = readRegister(0x21, 2); 134 | 135 | // convert the temperature to celsius and display it: 136 | temperature = (float)tempData / 20.0; 137 | 138 | //Read the pressure data highest 3 bits: 139 | byte pressureDataHigh = readRegister(0x1F, 1); 140 | pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0 141 | 142 | //Read the pressure data lower 16 bits: 143 | unsigned int pressureDataLow = readRegister(0x20, 2); 144 | //combine the two parts into one 19-bit number: 145 | pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4; 146 | 147 | Serial.print("Temperature: "); 148 | Serial.print(temperature); 149 | Serial.println(" degrees C"); 150 | Serial.print("Pressure: " + String(pressure)); 151 | Serial.println(" Pa"); 152 | } 153 | 154 | void listenForEthernetClients() { 155 | // listen for incoming clients 156 | EthernetClient client = server.available(); 157 | if (client) { 158 | Serial.println("Got a client"); 159 | // an http request ends with a blank line 160 | bool currentLineIsBlank = true; 161 | while (client.connected()) { 162 | if (client.available()) { 163 | char c = client.read(); 164 | // if you've gotten to the end of the line (received a newline 165 | // character) and the line is blank, the http request has ended, 166 | // so you can send a reply 167 | if (c == '\n' && currentLineIsBlank) { 168 | // send a standard http response header 169 | client.println("HTTP/1.1 200 OK"); 170 | client.println("Content-Type: text/html"); 171 | client.println(); 172 | // print the current readings, in HTML format: 173 | client.print("Temperature: "); 174 | client.print(temperature); 175 | client.print(" degrees C"); 176 | client.println("
"); 177 | client.print("Pressure: " + String(pressure)); 178 | client.print(" Pa"); 179 | client.println("
"); 180 | break; 181 | } 182 | if (c == '\n') { 183 | // you're starting a new line 184 | currentLineIsBlank = true; 185 | } else if (c != '\r') { 186 | // you've gotten a character on the current line 187 | currentLineIsBlank = false; 188 | } 189 | } 190 | } 191 | // give the web browser time to receive the data 192 | delay(1); 193 | // close the connection: 194 | client.stop(); 195 | } 196 | } 197 | 198 | 199 | //Send a write command to SCP1000 200 | void writeRegister(byte registerName, byte registerValue) { 201 | // SCP1000 expects the register name in the upper 6 bits 202 | // of the byte: 203 | registerName <<= 2; 204 | // command (read or write) goes in the lower two bits: 205 | registerName |= 0b00000010; //Write command 206 | 207 | // take the chip select low to select the device: 208 | digitalWrite(chipSelectPin, LOW); 209 | 210 | SPI.transfer(registerName); //Send register location 211 | SPI.transfer(registerValue); //Send value to record into register 212 | 213 | // take the chip select high to de-select: 214 | digitalWrite(chipSelectPin, HIGH); 215 | } 216 | 217 | 218 | //Read register from the SCP1000: 219 | unsigned int readRegister(byte registerName, int numBytes) { 220 | byte inByte = 0; // incoming from the SPI read 221 | unsigned int result = 0; // result to return 222 | 223 | // SCP1000 expects the register name in the upper 6 bits 224 | // of the byte: 225 | registerName <<= 2; 226 | // command (read or write) goes in the lower two bits: 227 | registerName &= 0b11111100; //Read command 228 | 229 | // take the chip select low to select the device: 230 | digitalWrite(chipSelectPin, LOW); 231 | // send the device the register you want to read: 232 | //int command = SPI.transfer(registerName); 233 | SPI.transfer(registerName); 234 | // send a value of 0 to read the first byte returned: 235 | inByte = SPI.transfer(0x00); 236 | 237 | result = inByte; 238 | // if there's more than one byte returned, 239 | // shift the first byte then get the second byte: 240 | if (numBytes > 1) { 241 | result = inByte << 8; 242 | inByte = SPI.transfer(0x00); 243 | result = result | inByte; 244 | } 245 | // take the chip select high to de-select: 246 | digitalWrite(chipSelectPin, HIGH); 247 | // return the result: 248 | return (result); 249 | } 250 | -------------------------------------------------------------------------------- /examples/ChatServer/ChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Chat Server 3 | 4 | A simple server that distributes any incoming messages to all 5 | connected clients. To use, telnet to your device's IP address and type. 6 | You can see the client's input in the serial monitor as well. 7 | Using an Arduino Wiznet Ethernet shield. 8 | 9 | Circuit: 10 | * Ethernet shield attached to pins 10, 11, 12, 13 11 | 12 | created 18 Dec 2009 13 | by David A. Mellis 14 | modified 9 Apr 2012 15 | by Tom Igoe 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | // Enter a MAC address and IP address for your controller below. 23 | // The IP address will be dependent on your local network. 24 | // gateway and subnet are optional: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 27 | IPAddress ip(192, 168, 1, 177); 28 | IPAddress myDns(192, 168, 1, 1); 29 | IPAddress gateway(192, 168, 1, 1); 30 | IPAddress subnet(255, 255, 0, 0); 31 | 32 | 33 | // telnet defaults to port 23 34 | EthernetServer server(23); 35 | bool alreadyConnected = false; // whether or not the client was connected previously 36 | 37 | void setup() { 38 | // You can use Ethernet.init(pin) to configure the CS pin 39 | //Ethernet.init(10); // Most Arduino shields 40 | //Ethernet.init(5); // MKR ETH shield 41 | //Ethernet.init(0); // Teensy 2.0 42 | //Ethernet.init(20); // Teensy++ 2.0 43 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 44 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 45 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 46 | 47 | // initialize the ethernet device 48 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 49 | 50 | // Open serial communications and wait for port to open: 51 | Serial.begin(9600); 52 | while (!Serial) { 53 | ; // wait for serial port to connect. Needed for native USB port only 54 | } 55 | 56 | // Check for Ethernet hardware present 57 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 58 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 59 | while (true) { 60 | delay(1); // do nothing, no point running without Ethernet hardware 61 | } 62 | } 63 | if (Ethernet.linkStatus() == LinkOFF) { 64 | Serial.println("Ethernet cable is not connected."); 65 | } 66 | 67 | // start listening for clients 68 | server.begin(); 69 | 70 | Serial.print("Chat server address:"); 71 | Serial.println(Ethernet.localIP()); 72 | } 73 | 74 | void loop() { 75 | // wait for a new client: 76 | EthernetClient client = server.available(); 77 | 78 | // when the client sends the first byte, say hello: 79 | if (client) { 80 | if (!alreadyConnected) { 81 | // clear out the input buffer: 82 | client.flush(); 83 | Serial.println("We have a new client"); 84 | client.println("Hello, client!"); 85 | alreadyConnected = true; 86 | } 87 | 88 | if (client.available() > 0) { 89 | // read the bytes incoming from the client: 90 | char thisChar = client.read(); 91 | // echo the bytes back to the client: 92 | server.write(thisChar); 93 | // echo the bytes to the server as well: 94 | Serial.write(thisChar); 95 | } 96 | } 97 | } 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /examples/DhcpAddressPrinter/DhcpAddressPrinter.ino: -------------------------------------------------------------------------------- 1 | /* 2 | DHCP-based IP printer 3 | 4 | This sketch uses the DHCP extensions to the Ethernet library 5 | to get an IP address via DHCP and print the address obtained. 6 | using an Arduino Wiznet Ethernet shield. 7 | 8 | Circuit: 9 | Ethernet shield attached to pins 10, 11, 12, 13 10 | 11 | created 12 April 2011 12 | modified 9 Apr 2012 13 | by Tom Igoe 14 | modified 02 Sept 2015 15 | by Arturo Guadalupi 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | // Enter a MAC address for your controller below. 23 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 24 | byte mac[] = { 25 | 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 26 | }; 27 | 28 | void setup() { 29 | // You can use Ethernet.init(pin) to configure the CS pin 30 | //Ethernet.init(10); // Most Arduino shields 31 | //Ethernet.init(5); // MKR ETH shield 32 | //Ethernet.init(0); // Teensy 2.0 33 | //Ethernet.init(20); // Teensy++ 2.0 34 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 35 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 36 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 37 | 38 | // Open serial communications and wait for port to open: 39 | Serial.begin(9600); 40 | while (!Serial) { 41 | ; // wait for serial port to connect. Needed for native USB port only 42 | } 43 | 44 | // start the Ethernet connection: 45 | Serial.println("Initialize Ethernet with DHCP:"); 46 | if (Ethernet.begin(mac) == 0) { 47 | Serial.println("Failed to configure Ethernet using DHCP"); 48 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 49 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 50 | } else if (Ethernet.linkStatus() == LinkOFF) { 51 | Serial.println("Ethernet cable is not connected."); 52 | } 53 | // no point in carrying on, so do nothing forevermore: 54 | while (true) { 55 | delay(1); 56 | } 57 | } 58 | // print your local IP address: 59 | Serial.print("My IP address: "); 60 | Serial.println(Ethernet.localIP()); 61 | } 62 | 63 | void loop() { 64 | switch (Ethernet.maintain()) { 65 | case 1: 66 | //renewed fail 67 | Serial.println("Error: renewed fail"); 68 | break; 69 | 70 | case 2: 71 | //renewed success 72 | Serial.println("Renewed success"); 73 | //print your local IP address: 74 | Serial.print("My IP address: "); 75 | Serial.println(Ethernet.localIP()); 76 | break; 77 | 78 | case 3: 79 | //rebind fail 80 | Serial.println("Error: rebind fail"); 81 | break; 82 | 83 | case 4: 84 | //rebind success 85 | Serial.println("Rebind success"); 86 | //print your local IP address: 87 | Serial.print("My IP address: "); 88 | Serial.println(Ethernet.localIP()); 89 | break; 90 | 91 | default: 92 | //nothing happened 93 | break; 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /examples/DhcpChatServer/DhcpChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | DHCP Chat Server 3 | 4 | A simple server that distributes any incoming messages to all 5 | connected clients. To use, telnet to your device's IP address and type. 6 | You can see the client's input in the serial monitor as well. 7 | Using an Arduino Wiznet Ethernet shield. 8 | 9 | THis version attempts to get an IP address using DHCP 10 | 11 | Circuit: 12 | * Ethernet shield attached to pins 10, 11, 12, 13 13 | 14 | created 21 May 2011 15 | modified 9 Apr 2012 16 | by Tom Igoe 17 | modified 02 Sept 2015 18 | by Arturo Guadalupi 19 | Based on ChatServer example by David A. Mellis 20 | 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | // Enter a MAC address and IP address for your controller below. 27 | // The IP address will be dependent on your local network. 28 | // gateway and subnet are optional: 29 | byte mac[] = { 30 | 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 31 | }; 32 | IPAddress ip(192, 168, 1, 177); 33 | IPAddress myDns(192, 168, 1, 1); 34 | IPAddress gateway(192, 168, 1, 1); 35 | IPAddress subnet(255, 255, 0, 0); 36 | 37 | // telnet defaults to port 23 38 | EthernetServer server(23); 39 | bool gotAMessage = false; // whether or not you got a message from the client yet 40 | 41 | void setup() { 42 | // You can use Ethernet.init(pin) to configure the CS pin 43 | //Ethernet.init(10); // Most Arduino shields 44 | //Ethernet.init(5); // MKR ETH shield 45 | //Ethernet.init(0); // Teensy 2.0 46 | //Ethernet.init(20); // Teensy++ 2.0 47 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 48 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 49 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 50 | 51 | // Open serial communications and wait for port to open: 52 | Serial.begin(9600); 53 | while (!Serial) { 54 | ; // wait for serial port to connect. Needed for native USB port only 55 | } 56 | 57 | // start the Ethernet connection: 58 | Serial.println("Trying to get an IP address using DHCP"); 59 | if (Ethernet.begin(mac) == 0) { 60 | Serial.println("Failed to configure Ethernet using DHCP"); 61 | // Check for Ethernet hardware present 62 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 63 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 64 | while (true) { 65 | delay(1); // do nothing, no point running without Ethernet hardware 66 | } 67 | } 68 | if (Ethernet.linkStatus() == LinkOFF) { 69 | Serial.println("Ethernet cable is not connected."); 70 | } 71 | // initialize the Ethernet device not using DHCP: 72 | Ethernet.begin(mac, ip, myDns, gateway, subnet); 73 | } 74 | // print your local IP address: 75 | Serial.print("My IP address: "); 76 | Serial.println(Ethernet.localIP()); 77 | 78 | // start listening for clients 79 | server.begin(); 80 | } 81 | 82 | void loop() { 83 | // wait for a new client: 84 | EthernetClient client = server.available(); 85 | 86 | // when the client sends the first byte, say hello: 87 | if (client) { 88 | if (!gotAMessage) { 89 | Serial.println("We have a new client"); 90 | client.println("Hello, client!"); 91 | gotAMessage = true; 92 | } 93 | 94 | // read the bytes incoming from the client: 95 | char thisChar = client.read(); 96 | // echo the bytes back to the client: 97 | server.write(thisChar); 98 | // echo the bytes to the server as well: 99 | Serial.print(thisChar); 100 | Ethernet.maintain(); 101 | } 102 | } 103 | 104 | -------------------------------------------------------------------------------- /examples/LinkStatus/LinkStatus.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Link Status 3 | This sketch prints the ethernet link status. When the 4 | ethernet cable is connected the link status should go to "ON". 5 | NOTE: Only WizNet W5200 and W5500 are capable of reporting 6 | the link status. W5100 will report "Unknown". 7 | Hardware: 8 | - Ethernet shield or equivalent board/shield with WizNet 5200/5500 9 | Written by Cristian Maglie 10 | This example is public domain. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | void setup() { 17 | // You can use Ethernet.init(pin) to configure the CS pin 18 | //Ethernet.init(10); // Most Arduino shields 19 | //Ethernet.init(5); // MKR ETH shield 20 | //Ethernet.init(0); // Teensy 2.0 21 | //Ethernet.init(20); // Teensy++ 2.0 22 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 23 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 24 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 25 | 26 | Serial.begin(9600); 27 | } 28 | 29 | void loop() { 30 | auto link = Ethernet.linkStatus(); 31 | Serial.print("Link status: "); 32 | switch (link) { 33 | case Unknown: 34 | Serial.println("Unknown"); 35 | break; 36 | case LinkON: 37 | Serial.println("ON"); 38 | break; 39 | case LinkOFF: 40 | Serial.println("OFF"); 41 | break; 42 | } 43 | delay(1000); 44 | } 45 | -------------------------------------------------------------------------------- /examples/TelnetClient/TelnetClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Telnet client 3 | 4 | This sketch connects to a a telnet server (http://www.google.com) 5 | using an Arduino Wiznet Ethernet shield. You'll need a telnet server 6 | to test this with. 7 | Processing's ChatServer example (part of the network library) works well, 8 | running on port 10002. It can be found as part of the examples 9 | in the Processing application, available at 10 | http://processing.org/ 11 | 12 | Circuit: 13 | * Ethernet shield attached to pins 10, 11, 12, 13 14 | 15 | created 14 Sep 2010 16 | modified 9 Apr 2012 17 | by Tom Igoe 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | // Enter a MAC address and IP address for your controller below. 24 | // The IP address will be dependent on your local network: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 27 | }; 28 | IPAddress ip(192, 168, 1, 177); 29 | 30 | // Enter the IP address of the server you're connecting to: 31 | IPAddress server(1, 1, 1, 1); 32 | 33 | // Initialize the Ethernet client library 34 | // with the IP address and port of the server 35 | // that you want to connect to (port 23 is default for telnet; 36 | // if you're using Processing's ChatServer, use port 10002): 37 | EthernetClient client; 38 | 39 | void setup() { 40 | // You can use Ethernet.init(pin) to configure the CS pin 41 | //Ethernet.init(10); // Most Arduino shields 42 | //Ethernet.init(5); // MKR ETH shield 43 | //Ethernet.init(0); // Teensy 2.0 44 | //Ethernet.init(20); // Teensy++ 2.0 45 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 46 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 47 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 48 | 49 | // start the Ethernet connection: 50 | Ethernet.begin(mac, ip); 51 | 52 | // Open serial communications and wait for port to open: 53 | Serial.begin(9600); 54 | while (!Serial) { 55 | ; // wait for serial port to connect. Needed for native USB port only 56 | } 57 | 58 | // Check for Ethernet hardware present 59 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 60 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 61 | while (true) { 62 | delay(1); // do nothing, no point running without Ethernet hardware 63 | } 64 | } 65 | while (Ethernet.linkStatus() == LinkOFF) { 66 | Serial.println("Ethernet cable is not connected."); 67 | delay(500); 68 | } 69 | 70 | // give the Ethernet shield a second to initialize: 71 | delay(1000); 72 | Serial.println("connecting..."); 73 | 74 | // if you get a connection, report back via serial: 75 | if (client.connect(server, 10002)) { 76 | Serial.println("connected"); 77 | } else { 78 | // if you didn't get a connection to the server: 79 | Serial.println("connection failed"); 80 | } 81 | } 82 | 83 | void loop() { 84 | // if there are incoming bytes available 85 | // from the server, read them and print them: 86 | if (client.available()) { 87 | char c = client.read(); 88 | Serial.print(c); 89 | } 90 | 91 | // as long as there are bytes in the serial queue, 92 | // read them and send them out the socket if it's open: 93 | while (Serial.available() > 0) { 94 | char inChar = Serial.read(); 95 | if (client.connected()) { 96 | client.print(inChar); 97 | } 98 | } 99 | 100 | // if the server's disconnected, stop the client: 101 | if (!client.connected()) { 102 | Serial.println(); 103 | Serial.println("disconnecting."); 104 | client.stop(); 105 | // do nothing: 106 | while (true) { 107 | delay(1); 108 | } 109 | } 110 | } 111 | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /examples/UDPSendReceiveString/UDPSendReceiveString.ino: -------------------------------------------------------------------------------- 1 | /* 2 | UDPSendReceiveString: 3 | This sketch receives UDP message strings, prints them to the serial port 4 | and sends an "acknowledge" string back to the sender 5 | 6 | A Processing sketch is included at the end of file that can be used to send 7 | and received messages for testing with a computer. 8 | 9 | created 21 Aug 2010 10 | by Michael Margolis 11 | 12 | This code is in the public domain. 13 | */ 14 | 15 | 16 | #include 17 | #include 18 | 19 | // Enter a MAC address and IP address for your controller below. 20 | // The IP address will be dependent on your local network: 21 | byte mac[] = { 22 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 23 | }; 24 | IPAddress ip(192, 168, 1, 177); 25 | 26 | unsigned int localPort = 8888; // local port to listen on 27 | 28 | // buffers for receiving and sending data 29 | char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, 30 | char ReplyBuffer[] = "acknowledged"; // a string to send back 31 | 32 | // An EthernetUDP instance to let us send and receive packets over UDP 33 | EthernetUDP Udp; 34 | 35 | void setup() { 36 | // You can use Ethernet.init(pin) to configure the CS pin 37 | //Ethernet.init(10); // Most Arduino shields 38 | //Ethernet.init(5); // MKR ETH shield 39 | //Ethernet.init(0); // Teensy 2.0 40 | //Ethernet.init(20); // Teensy++ 2.0 41 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 42 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 43 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 44 | 45 | // start the Ethernet 46 | Ethernet.begin(mac, ip); 47 | 48 | // Open serial communications and wait for port to open: 49 | Serial.begin(9600); 50 | while (!Serial) { 51 | ; // wait for serial port to connect. Needed for native USB port only 52 | } 53 | 54 | // Check for Ethernet hardware present 55 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 56 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 57 | while (true) { 58 | delay(1); // do nothing, no point running without Ethernet hardware 59 | } 60 | } 61 | if (Ethernet.linkStatus() == LinkOFF) { 62 | Serial.println("Ethernet cable is not connected."); 63 | } 64 | 65 | // start UDP 66 | Udp.begin(localPort); 67 | } 68 | 69 | void loop() { 70 | // if there's data available, read a packet 71 | int packetSize = Udp.parsePacket(); 72 | if (packetSize) { 73 | Serial.print("Received packet of size "); 74 | Serial.println(packetSize); 75 | Serial.print("From "); 76 | IPAddress remote = Udp.remoteIP(); 77 | for (int i=0; i < 4; i++) { 78 | Serial.print(remote[i], DEC); 79 | if (i < 3) { 80 | Serial.print("."); 81 | } 82 | } 83 | Serial.print(", port "); 84 | Serial.println(Udp.remotePort()); 85 | 86 | // read the packet into packetBufffer 87 | Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); 88 | Serial.println("Contents:"); 89 | Serial.println(packetBuffer); 90 | 91 | // send a reply to the IP address and port that sent us the packet we received 92 | Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); 93 | Udp.write(ReplyBuffer); 94 | Udp.endPacket(); 95 | } 96 | delay(10); 97 | } 98 | 99 | 100 | /* 101 | Processing sketch to run with this example 102 | ===================================================== 103 | 104 | // Processing UDP example to send and receive string data from Arduino 105 | // press any key to send the "Hello Arduino" message 106 | 107 | 108 | import hypermedia.net.*; 109 | 110 | UDP udp; // define the UDP object 111 | 112 | 113 | void setup() { 114 | udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 115 | //udp.log( true ); // <-- printout the connection activity 116 | udp.listen( true ); // and wait for incoming message 117 | } 118 | 119 | void draw() 120 | { 121 | } 122 | 123 | void keyPressed() { 124 | String ip = "192.168.1.177"; // the remote IP address 125 | int port = 8888; // the destination port 126 | 127 | udp.send("Hello World", ip, port ); // the message to send 128 | 129 | } 130 | 131 | void receive( byte[] data ) { // <-- default handler 132 | //void receive( byte[] data, String ip, int port ) { // <-- extended handler 133 | 134 | for(int i=0; i < data.length; i++) 135 | print(char(data[i])); 136 | println(); 137 | } 138 | */ 139 | 140 | 141 | -------------------------------------------------------------------------------- /examples/UdpNtpClient/UdpNtpClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Udp NTP Client 4 | 5 | Get the time from a Network Time Protocol (NTP) time server 6 | Demonstrates use of UDP sendPacket and ReceivePacket 7 | For more on NTP time servers and the messages needed to communicate with them, 8 | see http://en.wikipedia.org/wiki/Network_Time_Protocol 9 | 10 | created 4 Sep 2010 11 | by Michael Margolis 12 | modified 9 Apr 2012 13 | by Tom Igoe 14 | modified 02 Sept 2015 15 | by Arturo Guadalupi 16 | 17 | This code is in the public domain. 18 | 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | // Enter a MAC address for your controller below. 26 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 27 | byte mac[] = { 28 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 29 | }; 30 | 31 | unsigned int localPort = 8888; // local port to listen for UDP packets 32 | 33 | const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server 34 | 35 | const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message 36 | 37 | byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 38 | 39 | // A UDP instance to let us send and receive packets over UDP 40 | EthernetUDP Udp; 41 | 42 | void setup() { 43 | // You can use Ethernet.init(pin) to configure the CS pin 44 | //Ethernet.init(10); // Most Arduino shields 45 | //Ethernet.init(5); // MKR ETH shield 46 | //Ethernet.init(0); // Teensy 2.0 47 | //Ethernet.init(20); // Teensy++ 2.0 48 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 49 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 50 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 51 | 52 | // Open serial communications and wait for port to open: 53 | Serial.begin(9600); 54 | while (!Serial) { 55 | ; // wait for serial port to connect. Needed for native USB port only 56 | } 57 | 58 | // start Ethernet and UDP 59 | if (Ethernet.begin(mac) == 0) { 60 | Serial.println("Failed to configure Ethernet using DHCP"); 61 | // Check for Ethernet hardware present 62 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 63 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 64 | } else if (Ethernet.linkStatus() == LinkOFF) { 65 | Serial.println("Ethernet cable is not connected."); 66 | } 67 | // no point in carrying on, so do nothing forevermore: 68 | while (true) { 69 | delay(1); 70 | } 71 | } 72 | Udp.begin(localPort); 73 | } 74 | 75 | void loop() { 76 | sendNTPpacket(timeServer); // send an NTP packet to a time server 77 | 78 | // wait to see if a reply is available 79 | delay(1000); 80 | if (Udp.parsePacket()) { 81 | // We've received a packet, read the data from it 82 | Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer 83 | 84 | // the timestamp starts at byte 40 of the received packet and is four bytes, 85 | // or two words, long. First, extract the two words: 86 | 87 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); 88 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); 89 | // combine the four bytes (two words) into a long integer 90 | // this is NTP time (seconds since Jan 1 1900): 91 | unsigned long secsSince1900 = highWord << 16 | lowWord; 92 | Serial.print("Seconds since Jan 1 1900 = "); 93 | Serial.println(secsSince1900); 94 | 95 | // now convert NTP time into everyday time: 96 | Serial.print("Unix time = "); 97 | // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: 98 | const unsigned long seventyYears = 2208988800UL; 99 | // subtract seventy years: 100 | unsigned long epoch = secsSince1900 - seventyYears; 101 | // print Unix time: 102 | Serial.println(epoch); 103 | 104 | 105 | // print the hour, minute and second: 106 | Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) 107 | Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) 108 | Serial.print(':'); 109 | if (((epoch % 3600) / 60) < 10) { 110 | // In the first 10 minutes of each hour, we'll want a leading '0' 111 | Serial.print('0'); 112 | } 113 | Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) 114 | Serial.print(':'); 115 | if ((epoch % 60) < 10) { 116 | // In the first 10 seconds of each minute, we'll want a leading '0' 117 | Serial.print('0'); 118 | } 119 | Serial.println(epoch % 60); // print the second 120 | } 121 | // wait ten seconds before asking for the time again 122 | delay(10000); 123 | Ethernet.maintain(); 124 | } 125 | 126 | // send an NTP request to the time server at the given address 127 | void sendNTPpacket(const char * address) { 128 | // set all bytes in the buffer to 0 129 | memset(packetBuffer, 0, NTP_PACKET_SIZE); 130 | // Initialize values needed to form NTP request 131 | // (see URL above for details on the packets) 132 | packetBuffer[0] = 0b11100011; // LI, Version, Mode 133 | packetBuffer[1] = 0; // Stratum, or type of clock 134 | packetBuffer[2] = 6; // Polling Interval 135 | packetBuffer[3] = 0xEC; // Peer Clock Precision 136 | // 8 bytes of zero for Root Delay & Root Dispersion 137 | packetBuffer[12] = 49; 138 | packetBuffer[13] = 0x4E; 139 | packetBuffer[14] = 49; 140 | packetBuffer[15] = 52; 141 | 142 | // all NTP fields have been given values, now 143 | // you can send a packet requesting a timestamp: 144 | Udp.beginPacket(address, 123); // NTP requests are to port 123 145 | Udp.write(packetBuffer, NTP_PACKET_SIZE); 146 | Udp.endPacket(); 147 | } 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /examples/WebClient/WebClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Web client 3 | 4 | This sketch connects to a website (http://www.google.com) 5 | using an Arduino Wiznet Ethernet shield. 6 | 7 | Circuit: 8 | * Ethernet shield attached to pins 10, 11, 12, 13 9 | 10 | created 18 Dec 2009 11 | by David A. Mellis 12 | modified 9 Apr 2012 13 | by Tom Igoe, based on work by Adrian McEwen 14 | 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | // Enter a MAC address for your controller below. 21 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 22 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 23 | 24 | // if you don't want to use DNS (and reduce your sketch size) 25 | // use the numeric IP instead of the name for the server: 26 | //IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) 27 | char server[] = "www.google.com"; // name address for Google (using DNS) 28 | 29 | // Set the static IP address to use if the DHCP fails to assign 30 | IPAddress ip(192, 168, 0, 177); 31 | IPAddress myDns(192, 168, 0, 1); 32 | 33 | // Initialize the Ethernet client library 34 | // with the IP address and port of the server 35 | // that you want to connect to (port 80 is default for HTTP): 36 | EthernetClient client; 37 | 38 | // Variables to measure the speed 39 | unsigned long beginMicros, endMicros; 40 | unsigned long byteCount = 0; 41 | bool printWebData = true; // set to false for better speed measurement 42 | 43 | void setup() { 44 | // You can use Ethernet.init(pin) to configure the CS pin 45 | //Ethernet.init(10); // Most Arduino shields 46 | //Ethernet.init(5); // MKR ETH shield 47 | //Ethernet.init(0); // Teensy 2.0 48 | //Ethernet.init(20); // Teensy++ 2.0 49 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 50 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 51 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 52 | 53 | // Open serial communications and wait for port to open: 54 | Serial.begin(9600); 55 | while (!Serial) { 56 | ; // wait for serial port to connect. Needed for native USB port only 57 | } 58 | 59 | // start the Ethernet connection: 60 | Serial.println("Initialize Ethernet with DHCP:"); 61 | if (Ethernet.begin(mac) == 0) { 62 | Serial.println("Failed to configure Ethernet using DHCP"); 63 | // Check for Ethernet hardware present 64 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 65 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 66 | while (true) { 67 | delay(1); // do nothing, no point running without Ethernet hardware 68 | } 69 | } 70 | if (Ethernet.linkStatus() == LinkOFF) { 71 | Serial.println("Ethernet cable is not connected."); 72 | } 73 | // try to congifure using IP address instead of DHCP: 74 | Ethernet.begin(mac, ip, myDns); 75 | } else { 76 | Serial.print(" DHCP assigned IP "); 77 | Serial.println(Ethernet.localIP()); 78 | } 79 | // give the Ethernet shield a second to initialize: 80 | delay(1000); 81 | Serial.print("connecting to "); 82 | Serial.print(server); 83 | Serial.println("..."); 84 | 85 | // if you get a connection, report back via serial: 86 | if (client.connect(server, 80)) { 87 | Serial.print("connected to "); 88 | Serial.println(client.remoteIP()); 89 | // Make a HTTP request: 90 | client.println("GET /search?q=arduino HTTP/1.1"); 91 | client.println("Host: www.google.com"); 92 | client.println("Connection: close"); 93 | client.println(); 94 | } else { 95 | // if you didn't get a connection to the server: 96 | Serial.println("connection failed"); 97 | } 98 | beginMicros = micros(); 99 | } 100 | 101 | void loop() { 102 | // if there are incoming bytes available 103 | // from the server, read them and print them: 104 | int len = client.available(); 105 | if (len > 0) { 106 | byte buffer[80]; 107 | if (len > 80) len = 80; 108 | client.read(buffer, len); 109 | if (printWebData) { 110 | Serial.write(buffer, len); // show in the serial monitor (slows some boards) 111 | } 112 | byteCount = byteCount + len; 113 | } 114 | 115 | // if the server's disconnected, stop the client: 116 | if (!client.connected()) { 117 | endMicros = micros(); 118 | Serial.println(); 119 | Serial.println("disconnecting."); 120 | client.stop(); 121 | Serial.print("Received "); 122 | Serial.print(byteCount); 123 | Serial.print(" bytes in "); 124 | float seconds = (float)(endMicros - beginMicros) / 1000000.0; 125 | Serial.print(seconds, 4); 126 | float rate = (float)byteCount / seconds / 1000.0; 127 | Serial.print(", rate = "); 128 | Serial.print(rate); 129 | Serial.print(" kbytes/second"); 130 | Serial.println(); 131 | 132 | // do nothing forevermore: 133 | while (true) { 134 | delay(1); 135 | } 136 | } 137 | } 138 | 139 | -------------------------------------------------------------------------------- /examples/WebClientRepeating/WebClientRepeating.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Repeating Web client 3 | 4 | This sketch connects to a a web server and makes a request 5 | using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or 6 | the Adafruit Ethernet shield, either one will work, as long as it's got 7 | a Wiznet Ethernet module on board. 8 | 9 | This example uses DNS, by assigning the Ethernet client with a MAC address, 10 | IP address, and DNS address. 11 | 12 | Circuit: 13 | * Ethernet shield attached to pins 10, 11, 12, 13 14 | 15 | created 19 Apr 2012 16 | by Tom Igoe 17 | modified 21 Jan 2014 18 | by Federico Vanzati 19 | 20 | http://www.arduino.cc/en/Tutorial/WebClientRepeating 21 | This code is in the public domain. 22 | 23 | */ 24 | 25 | #include 26 | #include 27 | 28 | // assign a MAC address for the ethernet controller. 29 | // fill in your address here: 30 | byte mac[] = { 31 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 32 | }; 33 | // Set the static IP address to use if the DHCP fails to assign 34 | IPAddress ip(192, 168, 0, 177); 35 | IPAddress myDns(192, 168, 0, 1); 36 | 37 | // initialize the library instance: 38 | EthernetClient client; 39 | 40 | char server[] = "www.arduino.cc"; // also change the Host line in httpRequest() 41 | //IPAddress server(64,131,82,241); 42 | 43 | unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds 44 | const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds 45 | 46 | void setup() { 47 | // You can use Ethernet.init(pin) to configure the CS pin 48 | //Ethernet.init(10); // Most Arduino shields 49 | //Ethernet.init(5); // MKR ETH shield 50 | //Ethernet.init(0); // Teensy 2.0 51 | //Ethernet.init(20); // Teensy++ 2.0 52 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 53 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 54 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 55 | 56 | // start serial port: 57 | Serial.begin(9600); 58 | while (!Serial) { 59 | ; // wait for serial port to connect. Needed for native USB port only 60 | } 61 | 62 | // start the Ethernet connection: 63 | Serial.println("Initialize Ethernet with DHCP:"); 64 | if (Ethernet.begin(mac) == 0) { 65 | Serial.println("Failed to configure Ethernet using DHCP"); 66 | // Check for Ethernet hardware present 67 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 68 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 69 | while (true) { 70 | delay(1); // do nothing, no point running without Ethernet hardware 71 | } 72 | } 73 | if (Ethernet.linkStatus() == LinkOFF) { 74 | Serial.println("Ethernet cable is not connected."); 75 | } 76 | // try to congifure using IP address instead of DHCP: 77 | Ethernet.begin(mac, ip, myDns); 78 | Serial.print("My IP address: "); 79 | Serial.println(Ethernet.localIP()); 80 | } else { 81 | Serial.print(" DHCP assigned IP "); 82 | Serial.println(Ethernet.localIP()); 83 | } 84 | // give the Ethernet shield a second to initialize: 85 | delay(1000); 86 | } 87 | 88 | void loop() { 89 | // if there's incoming data from the net connection. 90 | // send it out the serial port. This is for debugging 91 | // purposes only: 92 | if (client.available()) { 93 | char c = client.read(); 94 | Serial.write(c); 95 | } 96 | 97 | // if ten seconds have passed since your last connection, 98 | // then connect again and send data: 99 | if (millis() - lastConnectionTime > postingInterval) { 100 | httpRequest(); 101 | } 102 | 103 | } 104 | 105 | // this method makes a HTTP connection to the server: 106 | void httpRequest() { 107 | // close any connection before send a new request. 108 | // This will free the socket on the WiFi shield 109 | client.stop(); 110 | 111 | // if there's a successful connection: 112 | if (client.connect(server, 80)) { 113 | Serial.println("connecting..."); 114 | // send the HTTP GET request: 115 | client.println("GET /latest.txt HTTP/1.1"); 116 | client.println("Host: www.arduino.cc"); 117 | client.println("User-Agent: arduino-ethernet"); 118 | client.println("Connection: close"); 119 | client.println(); 120 | 121 | // note the time that the connection was made: 122 | lastConnectionTime = millis(); 123 | } else { 124 | // if you couldn't make a connection: 125 | Serial.println("connection failed"); 126 | } 127 | } 128 | 129 | 130 | 131 | 132 | -------------------------------------------------------------------------------- /examples/WebServer/WebServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Web Server 3 | 4 | A simple web server that shows the value of the analog input pins. 5 | using an Arduino Wiznet Ethernet shield. 6 | 7 | Circuit: 8 | * Ethernet shield attached to pins 10, 11, 12, 13 9 | * Analog inputs attached to pins A0 through A5 (optional) 10 | 11 | created 18 Dec 2009 12 | by David A. Mellis 13 | modified 9 Apr 2012 14 | by Tom Igoe 15 | modified 02 Sept 2015 16 | by Arturo Guadalupi 17 | 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | // Enter a MAC address and IP address for your controller below. 24 | // The IP address will be dependent on your local network: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 27 | }; 28 | IPAddress ip(192, 168, 1, 177); 29 | 30 | // Initialize the Ethernet server library 31 | // with the IP address and port you want to use 32 | // (port 80 is default for HTTP): 33 | EthernetServer server(80); 34 | 35 | void setup() { 36 | // You can use Ethernet.init(pin) to configure the CS pin 37 | //Ethernet.init(10); // Most Arduino shields 38 | //Ethernet.init(5); // MKR ETH shield 39 | //Ethernet.init(0); // Teensy 2.0 40 | //Ethernet.init(20); // Teensy++ 2.0 41 | //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet 42 | //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet 43 | //Ethernet.init(17); // WIZnet W5100S-EVB-Pico W5500-EVB-Pico 44 | 45 | // Open serial communications and wait for port to open: 46 | Serial.begin(9600); 47 | while (!Serial) { 48 | ; // wait for serial port to connect. Needed for native USB port only 49 | } 50 | Serial.println("Ethernet WebServer Example"); 51 | 52 | // start the Ethernet connection and the server: 53 | Ethernet.begin(mac, ip); 54 | 55 | // Check for Ethernet hardware present 56 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 57 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 58 | while (true) { 59 | delay(1); // do nothing, no point running without Ethernet hardware 60 | } 61 | } 62 | if (Ethernet.linkStatus() == LinkOFF) { 63 | Serial.println("Ethernet cable is not connected."); 64 | } 65 | 66 | // start the server 67 | server.begin(); 68 | Serial.print("server is at "); 69 | Serial.println(Ethernet.localIP()); 70 | } 71 | 72 | 73 | void loop() { 74 | // listen for incoming clients 75 | EthernetClient client = server.available(); 76 | if (client) { 77 | Serial.println("new client"); 78 | // an http request ends with a blank line 79 | bool currentLineIsBlank = true; 80 | while (client.connected()) { 81 | if (client.available()) { 82 | char c = client.read(); 83 | Serial.write(c); 84 | // if you've gotten to the end of the line (received a newline 85 | // character) and the line is blank, the http request has ended, 86 | // so you can send a reply 87 | if (c == '\n' && currentLineIsBlank) { 88 | // send a standard http response header 89 | client.println("HTTP/1.1 200 OK"); 90 | client.println("Content-Type: text/html"); 91 | client.println("Connection: close"); // the connection will be closed after completion of the response 92 | client.println("Refresh: 5"); // refresh the page automatically every 5 sec 93 | client.println(); 94 | client.println(""); 95 | client.println(""); 96 | // output the value of each analog input pin 97 | for (int analogChannel = 0; analogChannel < 6; analogChannel++) { 98 | int sensorReading = analogRead(analogChannel); 99 | client.print("analog input "); 100 | client.print(analogChannel); 101 | client.print(" is "); 102 | client.print(sensorReading); 103 | client.println("
"); 104 | } 105 | client.println(""); 106 | break; 107 | } 108 | if (c == '\n') { 109 | // you're starting a new line 110 | currentLineIsBlank = true; 111 | } else if (c != '\r') { 112 | // you've gotten a character on the current line 113 | currentLineIsBlank = false; 114 | } 115 | } 116 | } 117 | // give the web browser time to receive the data 118 | delay(1); 119 | // close the connection: 120 | client.stop(); 121 | Serial.println("client disconnected"); 122 | } 123 | } 124 | 125 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For Ethernet 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | Ethernet KEYWORD1 Ethernet 10 | EthernetClient KEYWORD1 EthernetClient 11 | EthernetServer KEYWORD1 EthernetServer 12 | IPAddress KEYWORD1 EthernetIPAddress 13 | 14 | ####################################### 15 | # Methods and Functions (KEYWORD2) 16 | ####################################### 17 | 18 | status KEYWORD2 19 | connect KEYWORD2 20 | write KEYWORD2 21 | available KEYWORD2 22 | availableForWrite KEYWORD2 23 | read KEYWORD2 24 | peek KEYWORD2 25 | flush KEYWORD2 26 | stop KEYWORD2 27 | connected KEYWORD2 28 | accept KEYWORD2 29 | begin KEYWORD2 30 | beginMulticast KEYWORD2 31 | beginPacket KEYWORD2 32 | endPacket KEYWORD2 33 | parsePacket KEYWORD2 34 | remoteIP KEYWORD2 35 | remotePort KEYWORD2 36 | getSocketNumber KEYWORD2 37 | localIP KEYWORD2 38 | localPort KEYWORD2 39 | maintain KEYWORD2 40 | linkStatus KEYWORD2 41 | hardwareStatus KEYWORD2 42 | MACAddress KEYWORD2 43 | subnetMask KEYWORD2 44 | gatewayIP KEYWORD2 45 | dnsServerIP KEYWORD2 46 | setMACAddress KEYWORD2 47 | setLocalIP KEYWORD2 48 | setSubnetMask KEYWORD2 49 | setGatewayIP KEYWORD2 50 | setDnsServerIP KEYWORD2 51 | setRetransmissionTimeout KEYWORD2 52 | setRetransmissionCount KEYWORD2 53 | setConnectionTimeout KEYWORD2 54 | 55 | ####################################### 56 | # Constants (LITERAL1) 57 | ####################################### 58 | 59 | EthernetLinkStatus LITERAL1 60 | Unknown LITERAL1 61 | LinkON LITERAL1 62 | LinkOFF LITERAL1 63 | EthernetHardwareStatus LITERAL1 64 | EthernetNoHardware LITERAL1 65 | EthernetW5100 LITERAL1 66 | EthernetW5200 LITERAL1 67 | EthernetW5500 LITERAL1 68 | EthernetW6100 LITERAL1 69 | EthernetW5100S LITERAL1 70 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=Ethernet 2 | version=2.0.0 3 | author=Various (see AUTHORS file for details) 4 | maintainer=Paul Stoffregen , Arduino 5 | sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. 6 | paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both Client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS. 7 | category=Communication 8 | url=http://www.arduino.cc/en/Reference/Ethernet 9 | architectures=* 10 | includes=Ethernet.h 11 | -------------------------------------------------------------------------------- /src/Dhcp.cpp: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #include 5 | #include "Ethernet.h" 6 | #include "Dhcp.h" 7 | #include "utility/w5100.h" 8 | 9 | int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 10 | { 11 | _dhcpLeaseTime=0; 12 | _dhcpT1=0; 13 | _dhcpT2=0; 14 | _timeout = timeout; 15 | _responseTimeout = responseTimeout; 16 | 17 | // zero out _dhcpMacAddr 18 | memset(_dhcpMacAddr, 0, 6); 19 | reset_DHCP_lease(); 20 | 21 | memcpy((void*)_dhcpMacAddr, (void*)mac, 6); 22 | _dhcp_state = STATE_DHCP_START; 23 | return request_DHCP_lease(); 24 | } 25 | 26 | void DhcpClass::reset_DHCP_lease() 27 | { 28 | // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp 29 | memset(_dhcpLocalIp, 0, 20); 30 | } 31 | 32 | //return:0 on error, 1 if request is sent and response is received 33 | int DhcpClass::request_DHCP_lease() 34 | { 35 | uint8_t messageType = 0; 36 | 37 | // Pick an initial transaction ID 38 | _dhcpTransactionId = random(1UL, 2000UL); 39 | _dhcpInitialTransactionId = _dhcpTransactionId; 40 | 41 | _dhcpUdpSocket.stop(); 42 | if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) { 43 | // Couldn't get a socket 44 | return 0; 45 | } 46 | 47 | presend_DHCP(); 48 | 49 | int result = 0; 50 | 51 | unsigned long startTime = millis(); 52 | 53 | while (_dhcp_state != STATE_DHCP_LEASED) { 54 | if (_dhcp_state == STATE_DHCP_START) { 55 | _dhcpTransactionId++; 56 | send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); 57 | _dhcp_state = STATE_DHCP_DISCOVER; 58 | } else if (_dhcp_state == STATE_DHCP_REREQUEST) { 59 | _dhcpTransactionId++; 60 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); 61 | _dhcp_state = STATE_DHCP_REQUEST; 62 | } else if (_dhcp_state == STATE_DHCP_DISCOVER) { 63 | uint32_t respId; 64 | messageType = parseDHCPResponse(_responseTimeout, respId); 65 | if (messageType == DHCP_OFFER) { 66 | // We'll use the transaction ID that the offer came with, 67 | // rather than the one we were up to 68 | _dhcpTransactionId = respId; 69 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); 70 | _dhcp_state = STATE_DHCP_REQUEST; 71 | } 72 | } else if (_dhcp_state == STATE_DHCP_REQUEST) { 73 | uint32_t respId; 74 | messageType = parseDHCPResponse(_responseTimeout, respId); 75 | if (messageType == DHCP_ACK) { 76 | _dhcp_state = STATE_DHCP_LEASED; 77 | result = 1; 78 | //use default lease time if we didn't get it 79 | if (_dhcpLeaseTime == 0) { 80 | _dhcpLeaseTime = DEFAULT_LEASE; 81 | } 82 | // Calculate T1 & T2 if we didn't get it 83 | if (_dhcpT1 == 0) { 84 | // T1 should be 50% of _dhcpLeaseTime 85 | _dhcpT1 = _dhcpLeaseTime >> 1; 86 | } 87 | if (_dhcpT2 == 0) { 88 | // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime 89 | _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3); 90 | } 91 | _renewInSec = _dhcpT1; 92 | _rebindInSec = _dhcpT2; 93 | } else if (messageType == DHCP_NAK) { 94 | _dhcp_state = STATE_DHCP_START; 95 | } 96 | } 97 | 98 | if (messageType == 255) { 99 | messageType = 0; 100 | _dhcp_state = STATE_DHCP_START; 101 | } 102 | 103 | if (result != 1 && ((millis() - startTime) > _timeout)) 104 | break; 105 | } 106 | 107 | // We're done with the socket now 108 | _dhcpUdpSocket.stop(); 109 | _dhcpTransactionId++; 110 | 111 | _lastCheckLeaseMillis = millis(); 112 | return result; 113 | } 114 | 115 | void DhcpClass::presend_DHCP() 116 | { 117 | } 118 | 119 | void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) 120 | { 121 | uint8_t buffer[32]; 122 | memset(buffer, 0, 32); 123 | IPAddress dest_addr(255, 255, 255, 255); // Broadcast address 124 | 125 | if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) { 126 | //Serial.printf("DHCP transmit error\n"); 127 | // FIXME Need to return errors 128 | return; 129 | } 130 | 131 | buffer[0] = DHCP_BOOTREQUEST; // op 132 | buffer[1] = DHCP_HTYPE10MB; // htype 133 | buffer[2] = DHCP_HLENETHERNET; // hlen 134 | buffer[3] = DHCP_HOPS; // hops 135 | 136 | // xid 137 | unsigned long xid = htonl(_dhcpTransactionId); 138 | memcpy(buffer + 4, &(xid), 4); 139 | 140 | // 8, 9 - seconds elapsed 141 | buffer[8] = ((secondsElapsed & 0xff00) >> 8); 142 | buffer[9] = (secondsElapsed & 0x00ff); 143 | 144 | // flags 145 | unsigned short flags = htons(DHCP_FLAGSBROADCAST); 146 | memcpy(buffer + 10, &(flags), 2); 147 | 148 | // ciaddr: already zeroed 149 | // yiaddr: already zeroed 150 | // siaddr: already zeroed 151 | // giaddr: already zeroed 152 | 153 | //put data in W5100 transmit buffer 154 | _dhcpUdpSocket.write(buffer, 28); 155 | 156 | memset(buffer, 0, 32); // clear local buffer 157 | 158 | memcpy(buffer, _dhcpMacAddr, 6); // chaddr 159 | 160 | //put data in W5100 transmit buffer 161 | _dhcpUdpSocket.write(buffer, 16); 162 | 163 | memset(buffer, 0, 32); // clear local buffer 164 | 165 | // leave zeroed out for sname && file 166 | // put in W5100 transmit buffer x 6 (192 bytes) 167 | 168 | for(int i = 0; i < 6; i++) { 169 | _dhcpUdpSocket.write(buffer, 32); 170 | } 171 | 172 | // OPT - Magic Cookie 173 | buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); 174 | buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); 175 | buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); 176 | buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); 177 | 178 | // OPT - message type 179 | buffer[4] = dhcpMessageType; 180 | buffer[5] = 0x01; 181 | buffer[6] = messageType; //DHCP_REQUEST; 182 | 183 | // OPT - client identifier 184 | buffer[7] = dhcpClientIdentifier; 185 | buffer[8] = 0x07; 186 | buffer[9] = 0x01; 187 | memcpy(buffer + 10, _dhcpMacAddr, 6); 188 | 189 | // OPT - host name 190 | buffer[16] = hostName; 191 | buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address 192 | strcpy((char*)&(buffer[18]), HOST_NAME); 193 | 194 | printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); 195 | printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); 196 | printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); 197 | 198 | //put data in W5100 transmit buffer 199 | _dhcpUdpSocket.write(buffer, 30); 200 | 201 | if (messageType == DHCP_REQUEST) { 202 | buffer[0] = dhcpRequestedIPaddr; 203 | buffer[1] = 0x04; 204 | buffer[2] = _dhcpLocalIp[0]; 205 | buffer[3] = _dhcpLocalIp[1]; 206 | buffer[4] = _dhcpLocalIp[2]; 207 | buffer[5] = _dhcpLocalIp[3]; 208 | 209 | buffer[6] = dhcpServerIdentifier; 210 | buffer[7] = 0x04; 211 | buffer[8] = _dhcpDhcpServerIp[0]; 212 | buffer[9] = _dhcpDhcpServerIp[1]; 213 | buffer[10] = _dhcpDhcpServerIp[2]; 214 | buffer[11] = _dhcpDhcpServerIp[3]; 215 | 216 | //put data in W5100 transmit buffer 217 | _dhcpUdpSocket.write(buffer, 12); 218 | } 219 | 220 | buffer[0] = dhcpParamRequest; 221 | buffer[1] = 0x06; 222 | buffer[2] = subnetMask; 223 | buffer[3] = routersOnSubnet; 224 | buffer[4] = dns; 225 | buffer[5] = domainName; 226 | buffer[6] = dhcpT1value; 227 | buffer[7] = dhcpT2value; 228 | buffer[8] = endOption; 229 | 230 | //put data in W5100 transmit buffer 231 | _dhcpUdpSocket.write(buffer, 9); 232 | 233 | _dhcpUdpSocket.endPacket(); 234 | } 235 | 236 | uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) 237 | { 238 | uint8_t type = 0; 239 | uint8_t opt_len = 0; 240 | 241 | unsigned long startTime = millis(); 242 | 243 | while (_dhcpUdpSocket.parsePacket() <= 0) { 244 | if ((millis() - startTime) > responseTimeout) { 245 | return 255; 246 | } 247 | delay(50); 248 | } 249 | // start reading in the packet 250 | RIP_MSG_FIXED fixedMsg; 251 | _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); 252 | 253 | if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) { 254 | transactionId = ntohl(fixedMsg.xid); 255 | if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || 256 | (transactionId < _dhcpInitialTransactionId) || 257 | (transactionId > _dhcpTransactionId)) { 258 | // Need to read the rest of the packet here regardless 259 | _dhcpUdpSocket.flush(); // FIXME 260 | return 0; 261 | } 262 | 263 | memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); 264 | 265 | // Skip to the option part 266 | _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED)); 267 | 268 | while (_dhcpUdpSocket.available() > 0) { 269 | switch (_dhcpUdpSocket.read()) { 270 | case endOption : 271 | break; 272 | 273 | case padOption : 274 | break; 275 | 276 | case dhcpMessageType : 277 | opt_len = _dhcpUdpSocket.read(); 278 | type = _dhcpUdpSocket.read(); 279 | break; 280 | 281 | case subnetMask : 282 | opt_len = _dhcpUdpSocket.read(); 283 | _dhcpUdpSocket.read(_dhcpSubnetMask, 4); 284 | break; 285 | 286 | case routersOnSubnet : 287 | opt_len = _dhcpUdpSocket.read(); 288 | _dhcpUdpSocket.read(_dhcpGatewayIp, 4); 289 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 290 | break; 291 | 292 | case dns : 293 | opt_len = _dhcpUdpSocket.read(); 294 | _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); 295 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 296 | break; 297 | 298 | case dhcpServerIdentifier : 299 | opt_len = _dhcpUdpSocket.read(); 300 | if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) || 301 | IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) { 302 | _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); 303 | } else { 304 | // Skip over the rest of this option 305 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 306 | } 307 | break; 308 | 309 | case dhcpT1value : 310 | opt_len = _dhcpUdpSocket.read(); 311 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); 312 | _dhcpT1 = ntohl(_dhcpT1); 313 | break; 314 | 315 | case dhcpT2value : 316 | opt_len = _dhcpUdpSocket.read(); 317 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); 318 | _dhcpT2 = ntohl(_dhcpT2); 319 | break; 320 | 321 | case dhcpIPaddrLeaseTime : 322 | opt_len = _dhcpUdpSocket.read(); 323 | _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); 324 | _dhcpLeaseTime = ntohl(_dhcpLeaseTime); 325 | _renewInSec = _dhcpLeaseTime; 326 | break; 327 | 328 | default : 329 | opt_len = _dhcpUdpSocket.read(); 330 | // Skip over the rest of this option 331 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 332 | break; 333 | } 334 | } 335 | } 336 | 337 | // Need to skip to end of the packet regardless here 338 | _dhcpUdpSocket.flush(); // FIXME 339 | 340 | return type; 341 | } 342 | 343 | 344 | /* 345 | returns: 346 | 0/DHCP_CHECK_NONE: nothing happened 347 | 1/DHCP_CHECK_RENEW_FAIL: renew failed 348 | 2/DHCP_CHECK_RENEW_OK: renew success 349 | 3/DHCP_CHECK_REBIND_FAIL: rebind fail 350 | 4/DHCP_CHECK_REBIND_OK: rebind success 351 | */ 352 | int DhcpClass::checkLease() 353 | { 354 | int rc = DHCP_CHECK_NONE; 355 | 356 | unsigned long now = millis(); 357 | unsigned long elapsed = now - _lastCheckLeaseMillis; 358 | 359 | // if more then one sec passed, reduce the counters accordingly 360 | if (elapsed >= 1000) { 361 | // set the new timestamps 362 | _lastCheckLeaseMillis = now - (elapsed % 1000); 363 | elapsed = elapsed / 1000; 364 | 365 | // decrease the counters by elapsed seconds 366 | // we assume that the cycle time (elapsed) is fairly constant 367 | // if the remainder is less than cycle time * 2 368 | // do it early instead of late 369 | if (_renewInSec < elapsed * 2) { 370 | _renewInSec = 0; 371 | } else { 372 | _renewInSec -= elapsed; 373 | } 374 | if (_rebindInSec < elapsed * 2) { 375 | _rebindInSec = 0; 376 | } else { 377 | _rebindInSec -= elapsed; 378 | } 379 | } 380 | 381 | // if we have a lease but should renew, do it 382 | if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) { 383 | _dhcp_state = STATE_DHCP_REREQUEST; 384 | rc = 1 + request_DHCP_lease(); 385 | } 386 | 387 | // if we have a lease or is renewing but should bind, do it 388 | if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED || 389 | _dhcp_state == STATE_DHCP_START)) { 390 | // this should basically restart completely 391 | _dhcp_state = STATE_DHCP_START; 392 | reset_DHCP_lease(); 393 | rc = 3 + request_DHCP_lease(); 394 | } 395 | return rc; 396 | } 397 | 398 | IPAddress DhcpClass::getLocalIp() 399 | { 400 | return IPAddress(_dhcpLocalIp); 401 | } 402 | 403 | IPAddress DhcpClass::getSubnetMask() 404 | { 405 | return IPAddress(_dhcpSubnetMask); 406 | } 407 | 408 | IPAddress DhcpClass::getGatewayIp() 409 | { 410 | return IPAddress(_dhcpGatewayIp); 411 | } 412 | 413 | IPAddress DhcpClass::getDhcpServerIp() 414 | { 415 | return IPAddress(_dhcpDhcpServerIp); 416 | } 417 | 418 | IPAddress DhcpClass::getDnsServerIp() 419 | { 420 | return IPAddress(_dhcpDnsServerIp); 421 | } 422 | 423 | void DhcpClass::printByte(char * buf, uint8_t n ) 424 | { 425 | char *str = &buf[1]; 426 | buf[0]='0'; 427 | do { 428 | unsigned long m = n; 429 | n /= 16; 430 | char c = m - 16 * n; 431 | *str-- = c < 10 ? c + '0' : c + 'A' - 10; 432 | } while(n); 433 | } 434 | -------------------------------------------------------------------------------- /src/Dhcp.h: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #ifndef Dhcp_h 5 | #define Dhcp_h 6 | 7 | /* DHCP state machine. */ 8 | #define STATE_DHCP_START 0 9 | #define STATE_DHCP_DISCOVER 1 10 | #define STATE_DHCP_REQUEST 2 11 | #define STATE_DHCP_LEASED 3 12 | #define STATE_DHCP_REREQUEST 4 13 | #define STATE_DHCP_RELEASE 5 14 | 15 | #define DHCP_FLAGSBROADCAST 0x8000 16 | 17 | /* UDP port numbers for DHCP */ 18 | #define DHCP_SERVER_PORT 67 /* from server to client */ 19 | #define DHCP_CLIENT_PORT 68 /* from client to server */ 20 | 21 | /* DHCP message OP code */ 22 | #define DHCP_BOOTREQUEST 1 23 | #define DHCP_BOOTREPLY 2 24 | 25 | /* DHCP message type */ 26 | #define DHCP_DISCOVER 1 27 | #define DHCP_OFFER 2 28 | #define DHCP_REQUEST 3 29 | #define DHCP_DECLINE 4 30 | #define DHCP_ACK 5 31 | #define DHCP_NAK 6 32 | #define DHCP_RELEASE 7 33 | #define DHCP_INFORM 8 34 | 35 | #define DHCP_HTYPE10MB 1 36 | #define DHCP_HTYPE100MB 2 37 | 38 | #define DHCP_HLENETHERNET 6 39 | #define DHCP_HOPS 0 40 | #define DHCP_SECS 0 41 | 42 | #define MAGIC_COOKIE 0x63825363 43 | #define MAX_DHCP_OPT 16 44 | 45 | #define HOST_NAME "WIZnet" 46 | #define DEFAULT_LEASE (900) //default lease time in seconds 47 | 48 | #define DHCP_CHECK_NONE (0) 49 | #define DHCP_CHECK_RENEW_FAIL (1) 50 | #define DHCP_CHECK_RENEW_OK (2) 51 | #define DHCP_CHECK_REBIND_FAIL (3) 52 | #define DHCP_CHECK_REBIND_OK (4) 53 | 54 | enum 55 | { 56 | padOption = 0, 57 | subnetMask = 1, 58 | timerOffset = 2, 59 | routersOnSubnet = 3, 60 | /* timeServer = 4, 61 | nameServer = 5,*/ 62 | dns = 6, 63 | /*logServer = 7, 64 | cookieServer = 8, 65 | lprServer = 9, 66 | impressServer = 10, 67 | resourceLocationServer = 11,*/ 68 | hostName = 12, 69 | /*bootFileSize = 13, 70 | meritDumpFile = 14,*/ 71 | domainName = 15, 72 | /*swapServer = 16, 73 | rootPath = 17, 74 | extentionsPath = 18, 75 | IPforwarding = 19, 76 | nonLocalSourceRouting = 20, 77 | policyFilter = 21, 78 | maxDgramReasmSize = 22, 79 | defaultIPTTL = 23, 80 | pathMTUagingTimeout = 24, 81 | pathMTUplateauTable = 25, 82 | ifMTU = 26, 83 | allSubnetsLocal = 27, 84 | broadcastAddr = 28, 85 | performMaskDiscovery = 29, 86 | maskSupplier = 30, 87 | performRouterDiscovery = 31, 88 | routerSolicitationAddr = 32, 89 | staticRoute = 33, 90 | trailerEncapsulation = 34, 91 | arpCacheTimeout = 35, 92 | ethernetEncapsulation = 36, 93 | tcpDefaultTTL = 37, 94 | tcpKeepaliveInterval = 38, 95 | tcpKeepaliveGarbage = 39, 96 | nisDomainName = 40, 97 | nisServers = 41, 98 | ntpServers = 42, 99 | vendorSpecificInfo = 43, 100 | netBIOSnameServer = 44, 101 | netBIOSdgramDistServer = 45, 102 | netBIOSnodeType = 46, 103 | netBIOSscope = 47, 104 | xFontServer = 48, 105 | xDisplayManager = 49,*/ 106 | dhcpRequestedIPaddr = 50, 107 | dhcpIPaddrLeaseTime = 51, 108 | /*dhcpOptionOverload = 52,*/ 109 | dhcpMessageType = 53, 110 | dhcpServerIdentifier = 54, 111 | dhcpParamRequest = 55, 112 | /*dhcpMsg = 56, 113 | dhcpMaxMsgSize = 57,*/ 114 | dhcpT1value = 58, 115 | dhcpT2value = 59, 116 | /*dhcpClassIdentifier = 60,*/ 117 | dhcpClientIdentifier = 61, 118 | endOption = 255 119 | }; 120 | 121 | typedef struct _RIP_MSG_FIXED 122 | { 123 | uint8_t op; 124 | uint8_t htype; 125 | uint8_t hlen; 126 | uint8_t hops; 127 | uint32_t xid; 128 | uint16_t secs; 129 | uint16_t flags; 130 | uint8_t ciaddr[4]; 131 | uint8_t yiaddr[4]; 132 | uint8_t siaddr[4]; 133 | uint8_t giaddr[4]; 134 | uint8_t chaddr[6]; 135 | } RIP_MSG_FIXED; 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /src/Dns.cpp: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WizNet5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #include 6 | #include "Ethernet.h" 7 | #include "Dns.h" 8 | #include "utility/w5100.h" 9 | 10 | 11 | #define SOCKET_NONE 255 12 | // Various flags and header field values for a DNS message 13 | #define UDP_HEADER_SIZE 8 14 | #define DNS_HEADER_SIZE 12 15 | #define TTL_SIZE 4 16 | #define QUERY_FLAG (0) 17 | #define RESPONSE_FLAG (1<<15) 18 | #define QUERY_RESPONSE_MASK (1<<15) 19 | #define OPCODE_STANDARD_QUERY (0) 20 | #define OPCODE_INVERSE_QUERY (1<<11) 21 | #define OPCODE_STATUS_REQUEST (2<<11) 22 | #define OPCODE_MASK (15<<11) 23 | #define AUTHORITATIVE_FLAG (1<<10) 24 | #define TRUNCATION_FLAG (1<<9) 25 | #define RECURSION_DESIRED_FLAG (1<<8) 26 | #define RECURSION_AVAILABLE_FLAG (1<<7) 27 | #define RESP_NO_ERROR (0) 28 | #define RESP_FORMAT_ERROR (1) 29 | #define RESP_SERVER_FAILURE (2) 30 | #define RESP_NAME_ERROR (3) 31 | #define RESP_NOT_IMPLEMENTED (4) 32 | #define RESP_REFUSED (5) 33 | #define RESP_MASK (15) 34 | #define TYPE_A (0x0001) 35 | #define CLASS_IN (0x0001) 36 | #define LABEL_COMPRESSION_MASK (0xC0) 37 | // Port number that DNS servers listen on 38 | #define DNS_PORT 53 39 | 40 | // Possible return codes from ProcessResponse 41 | #define SUCCESS 1 42 | #define TIMED_OUT -1 43 | #define INVALID_SERVER -2 44 | #define TRUNCATED -3 45 | #define INVALID_RESPONSE -4 46 | 47 | void DNSClient::begin(const IPAddress& aDNSServer) 48 | { 49 | iDNSServer = aDNSServer; 50 | iRequestId = 0; 51 | } 52 | 53 | 54 | int DNSClient::inet_aton(const char* address, IPAddress& result) 55 | { 56 | uint16_t acc = 0; // Accumulator 57 | uint8_t dots = 0; 58 | 59 | while (*address) { 60 | char c = *address++; 61 | if (c >= '0' && c <= '9') { 62 | acc = acc * 10 + (c - '0'); 63 | if (acc > 255) { 64 | // Value out of [0..255] range 65 | return 0; 66 | } 67 | } else if (c == '.') { 68 | if (dots == 3) { 69 | // Too much dots (there must be 3 dots) 70 | return 0; 71 | } 72 | result[dots++] = acc; 73 | acc = 0; 74 | } else { 75 | // Invalid char 76 | return 0; 77 | } 78 | } 79 | 80 | if (dots != 3) { 81 | // Too few dots (there must be 3 dots) 82 | return 0; 83 | } 84 | result[3] = acc; 85 | return 1; 86 | } 87 | 88 | int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout) 89 | { 90 | int ret = 0; 91 | 92 | // See if it's a numeric IP address 93 | if (inet_aton(aHostname, aResult)) { 94 | // It is, our work here is done 95 | return 1; 96 | } 97 | 98 | // Check we've got a valid DNS server to use 99 | if (iDNSServer == INADDR_NONE) { 100 | return INVALID_SERVER; 101 | } 102 | 103 | // Find a socket to use 104 | if (iUdp.begin(1024+(millis() & 0xF)) == 1) { 105 | // Try up to three times 106 | int retries = 0; 107 | // while ((retries < 3) && (ret <= 0)) { 108 | // Send DNS request 109 | ret = iUdp.beginPacket(iDNSServer, DNS_PORT); 110 | if (ret != 0) { 111 | // Now output the request data 112 | ret = BuildRequest(aHostname); 113 | if (ret != 0) { 114 | // And finally send the request 115 | ret = iUdp.endPacket(); 116 | if (ret != 0) { 117 | // Now wait for a response 118 | int wait_retries = 0; 119 | ret = TIMED_OUT; 120 | while ((wait_retries < 3) && (ret == TIMED_OUT)) { 121 | ret = ProcessResponse(timeout, aResult); 122 | wait_retries++; 123 | } 124 | } 125 | } 126 | } 127 | retries++; 128 | //} 129 | 130 | // We're done with the socket now 131 | iUdp.stop(); 132 | } 133 | 134 | return ret; 135 | } 136 | 137 | uint16_t DNSClient::BuildRequest(const char* aName) 138 | { 139 | // Build header 140 | // 1 1 1 1 1 1 141 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 142 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 143 | // | ID | 144 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 145 | // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | 146 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 147 | // | QDCOUNT | 148 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 149 | // | ANCOUNT | 150 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 151 | // | NSCOUNT | 152 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 153 | // | ARCOUNT | 154 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 155 | // As we only support one request at a time at present, we can simplify 156 | // some of this header 157 | iRequestId = millis(); // generate a random ID 158 | uint16_t twoByteBuffer; 159 | 160 | // FIXME We should also check that there's enough space available to write to, rather 161 | // FIXME than assume there's enough space (as the code does at present) 162 | iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); 163 | 164 | twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); 165 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 166 | 167 | twoByteBuffer = htons(1); // One question record 168 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 169 | 170 | twoByteBuffer = 0; // Zero answer records 171 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 172 | 173 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 174 | // and zero additional records 175 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 176 | 177 | // Build question 178 | const char* start =aName; 179 | const char* end =start; 180 | uint8_t len; 181 | // Run through the name being requested 182 | while (*end) { 183 | // Find out how long this section of the name is 184 | end = start; 185 | while (*end && (*end != '.') ) { 186 | end++; 187 | } 188 | 189 | if (end-start > 0) { 190 | // Write out the size of this section 191 | len = end-start; 192 | iUdp.write(&len, sizeof(len)); 193 | // And then write out the section 194 | iUdp.write((uint8_t*)start, end-start); 195 | } 196 | start = end+1; 197 | } 198 | 199 | // We've got to the end of the question name, so 200 | // terminate it with a zero-length section 201 | len = 0; 202 | iUdp.write(&len, sizeof(len)); 203 | // Finally the type and class of question 204 | twoByteBuffer = htons(TYPE_A); 205 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 206 | 207 | twoByteBuffer = htons(CLASS_IN); // Internet class of question 208 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 209 | // Success! Everything buffered okay 210 | return 1; 211 | } 212 | 213 | 214 | uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) 215 | { 216 | uint32_t startTime = millis(); 217 | 218 | // Wait for a response packet 219 | while (iUdp.parsePacket() <= 0) { 220 | if ((millis() - startTime) > aTimeout) { 221 | return TIMED_OUT; 222 | } 223 | delay(50); 224 | } 225 | 226 | // We've had a reply! 227 | // Read the UDP header 228 | //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 229 | union { 230 | uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 231 | uint16_t word[DNS_HEADER_SIZE/2]; 232 | } header; 233 | 234 | // Check that it's a response from the right server and the right port 235 | if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) { 236 | // It's not from who we expected 237 | return INVALID_SERVER; 238 | } 239 | 240 | // Read through the rest of the response 241 | if (iUdp.available() < DNS_HEADER_SIZE) { 242 | return TRUNCATED; 243 | } 244 | iUdp.read(header.byte, DNS_HEADER_SIZE); 245 | 246 | uint16_t header_flags = htons(header.word[1]); 247 | // Check that it's a response to this request 248 | if ((iRequestId != (header.word[0])) || 249 | ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) { 250 | // Mark the entire packet as read 251 | iUdp.flush(); // FIXME 252 | return INVALID_RESPONSE; 253 | } 254 | // Check for any errors in the response (or in our request) 255 | // although we don't do anything to get round these 256 | if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) { 257 | // Mark the entire packet as read 258 | iUdp.flush(); // FIXME 259 | return -5; //INVALID_RESPONSE; 260 | } 261 | 262 | // And make sure we've got (at least) one answer 263 | uint16_t answerCount = htons(header.word[3]); 264 | if (answerCount == 0) { 265 | // Mark the entire packet as read 266 | iUdp.flush(); // FIXME 267 | return -6; //INVALID_RESPONSE; 268 | } 269 | 270 | // Skip over any questions 271 | for (uint16_t i=0; i < htons(header.word[2]); i++) { 272 | // Skip over the name 273 | uint8_t len; 274 | do { 275 | iUdp.read(&len, sizeof(len)); 276 | if (len > 0) { 277 | // Don't need to actually read the data out for the string, just 278 | // advance ptr to beyond it 279 | iUdp.read((uint8_t *)NULL, (size_t)len); 280 | } 281 | } while (len != 0); 282 | 283 | // Now jump over the type and class 284 | iUdp.read((uint8_t *)NULL, 4); 285 | } 286 | 287 | // Now we're up to the bit we're interested in, the answer 288 | // There might be more than one answer (although we'll just use the first 289 | // type A answer) and some authority and additional resource records but 290 | // we're going to ignore all of them. 291 | 292 | for (uint16_t i=0; i < answerCount; i++) { 293 | // Skip the name 294 | uint8_t len; 295 | do { 296 | iUdp.read(&len, sizeof(len)); 297 | if ((len & LABEL_COMPRESSION_MASK) == 0) { 298 | // It's just a normal label 299 | if (len > 0) { 300 | // And it's got a length 301 | // Don't need to actually read the data out for the string, 302 | // just advance ptr to beyond it 303 | iUdp.read((uint8_t *)NULL, len); 304 | } 305 | } else { 306 | // This is a pointer to a somewhere else in the message for the 307 | // rest of the name. We don't care about the name, and RFC1035 308 | // says that a name is either a sequence of labels ended with a 309 | // 0 length octet or a pointer or a sequence of labels ending in 310 | // a pointer. Either way, when we get here we're at the end of 311 | // the name 312 | // Skip over the pointer 313 | iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte 314 | // And set len so that we drop out of the name loop 315 | len = 0; 316 | } 317 | } while (len != 0); 318 | 319 | // Check the type and class 320 | uint16_t answerType; 321 | uint16_t answerClass; 322 | iUdp.read((uint8_t*)&answerType, sizeof(answerType)); 323 | iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); 324 | 325 | // Ignore the Time-To-Live as we don't do any caching 326 | iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes 327 | 328 | // And read out the length of this answer 329 | // Don't need header_flags anymore, so we can reuse it here 330 | iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); 331 | 332 | if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) { 333 | if (htons(header_flags) != 4) { 334 | // It's a weird size 335 | // Mark the entire packet as read 336 | iUdp.flush(); // FIXME 337 | return -9;//INVALID_RESPONSE; 338 | } 339 | // FIXME: seeems to lock up here on ESP8266, but why?? 340 | iUdp.read(aAddress.raw_address(), 4); 341 | return SUCCESS; 342 | } else { 343 | // This isn't an answer type we're after, move onto the next one 344 | iUdp.read((uint8_t *)NULL, htons(header_flags)); 345 | } 346 | } 347 | 348 | // Mark the entire packet as read 349 | iUdp.flush(); // FIXME 350 | 351 | // If we get here then we haven't found an answer 352 | return -10; //INVALID_RESPONSE; 353 | } 354 | 355 | -------------------------------------------------------------------------------- /src/Dns.h: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WizNet5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #ifndef DNSClient_h 6 | #define DNSClient_h 7 | 8 | #include "Ethernet.h" 9 | 10 | class DNSClient 11 | { 12 | public: 13 | void begin(const IPAddress& aDNSServer); 14 | 15 | /** Convert a numeric IP address string into a four-byte IP address. 16 | @param aIPAddrString IP address to convert 17 | @param aResult IPAddress structure to store the returned IP address 18 | @result 1 if aIPAddrString was successfully converted to an IP address, 19 | else error code 20 | */ 21 | int inet_aton(const char *aIPAddrString, IPAddress& aResult); 22 | 23 | /** Resolve the given hostname to an IP address. 24 | @param aHostname Name to be resolved 25 | @param aResult IPAddress structure to store the returned IP address 26 | @result 1 if aIPAddrString was successfully converted to an IP address, 27 | else error code 28 | */ 29 | int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000); 30 | 31 | protected: 32 | uint16_t BuildRequest(const char* aName); 33 | uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); 34 | 35 | IPAddress iDNSServer; 36 | uint16_t iRequestId; 37 | EthernetUDP iUdp; 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /src/Ethernet.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | #include "Dhcp.h" 25 | 26 | IPAddress EthernetClass::_dnsServerAddress; 27 | DhcpClass* EthernetClass::_dhcp = NULL; 28 | 29 | int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 30 | { 31 | static DhcpClass s_dhcp; 32 | _dhcp = &s_dhcp; 33 | 34 | // Initialise the basic info 35 | if (W5100.init() == 0) return 0; 36 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 37 | W5100.setMACAddress(mac); 38 | W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); 39 | SPI.endTransaction(); 40 | 41 | // Now try to get our config info from a DHCP server 42 | int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout); 43 | if (ret == 1) { 44 | // We've successfully found a DHCP server and got our configuration 45 | // info, so set things accordingly 46 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 47 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 48 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 49 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 50 | SPI.endTransaction(); 51 | _dnsServerAddress = _dhcp->getDnsServerIp(); 52 | socketPortRand(micros()); 53 | } 54 | return ret; 55 | } 56 | 57 | void EthernetClass::begin(uint8_t *mac, IPAddress ip) 58 | { 59 | // Assume the DNS server will be the machine on the same network as the local IP 60 | // but with last octet being '1' 61 | IPAddress dns = ip; 62 | dns[3] = 1; 63 | begin(mac, ip, dns); 64 | } 65 | 66 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns) 67 | { 68 | // Assume the gateway will be the machine on the same network as the local IP 69 | // but with last octet being '1' 70 | IPAddress gateway = ip; 71 | gateway[3] = 1; 72 | begin(mac, ip, dns, gateway); 73 | } 74 | 75 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) 76 | { 77 | IPAddress subnet(255, 255, 255, 0); 78 | begin(mac, ip, dns, gateway, subnet); 79 | } 80 | 81 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) 82 | { 83 | if (W5100.init() == 0) return; 84 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 85 | W5100.setMACAddress(mac); 86 | #if ARDUINO > 106 || TEENSYDUINO > 121 87 | W5100.setIPAddress(ip._address.bytes); 88 | W5100.setGatewayIp(gateway._address.bytes); 89 | W5100.setSubnetMask(subnet._address.bytes); 90 | #else 91 | W5100.setIPAddress(ip._address); 92 | W5100.setGatewayIp(gateway._address); 93 | W5100.setSubnetMask(subnet._address); 94 | #endif 95 | SPI.endTransaction(); 96 | _dnsServerAddress = dns; 97 | } 98 | 99 | void EthernetClass::init(uint8_t sspin) 100 | { 101 | W5100.setSS(sspin); 102 | } 103 | 104 | EthernetLinkStatus EthernetClass::linkStatus() 105 | { 106 | switch (W5100.getLinkStatus()) { 107 | case UNKNOWN: return Unknown; 108 | case LINK_ON: return LinkON; 109 | case LINK_OFF: return LinkOFF; 110 | default: return Unknown; 111 | } 112 | } 113 | 114 | EthernetHardwareStatus EthernetClass::hardwareStatus() 115 | { 116 | switch (W5100.getChip()) { 117 | case 50: return EthernetW5100S; 118 | case 51: return EthernetW5100; 119 | case 52: return EthernetW5200; 120 | case 55: return EthernetW5500; 121 | case 61: return EthernetW6100; 122 | default: return EthernetNoHardware; 123 | } 124 | } 125 | 126 | int EthernetClass::maintain() 127 | { 128 | int rc = DHCP_CHECK_NONE; 129 | if (_dhcp != NULL) { 130 | // we have a pointer to dhcp, use it 131 | rc = _dhcp->checkLease(); 132 | switch (rc) { 133 | case DHCP_CHECK_NONE: 134 | //nothing done 135 | break; 136 | case DHCP_CHECK_RENEW_OK: 137 | case DHCP_CHECK_REBIND_OK: 138 | //we might have got a new IP. 139 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 140 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 141 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 142 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 143 | SPI.endTransaction(); 144 | _dnsServerAddress = _dhcp->getDnsServerIp(); 145 | break; 146 | default: 147 | //this is actually an error, it will retry though 148 | break; 149 | } 150 | } 151 | return rc; 152 | } 153 | 154 | 155 | void EthernetClass::MACAddress(uint8_t *mac_address) 156 | { 157 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 158 | W5100.getMACAddress(mac_address); 159 | SPI.endTransaction(); 160 | } 161 | 162 | IPAddress EthernetClass::localIP() 163 | { 164 | IPAddress ret; 165 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 166 | W5100.getIPAddress(ret.raw_address()); 167 | SPI.endTransaction(); 168 | return ret; 169 | } 170 | 171 | IPAddress EthernetClass::subnetMask() 172 | { 173 | IPAddress ret; 174 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 175 | W5100.getSubnetMask(ret.raw_address()); 176 | SPI.endTransaction(); 177 | return ret; 178 | } 179 | 180 | IPAddress EthernetClass::gatewayIP() 181 | { 182 | IPAddress ret; 183 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 184 | W5100.getGatewayIp(ret.raw_address()); 185 | SPI.endTransaction(); 186 | return ret; 187 | } 188 | 189 | void EthernetClass::setMACAddress(const uint8_t *mac_address) 190 | { 191 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 192 | W5100.setMACAddress(mac_address); 193 | SPI.endTransaction(); 194 | } 195 | 196 | void EthernetClass::setLocalIP(const IPAddress local_ip) 197 | { 198 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 199 | IPAddress ip = local_ip; 200 | W5100.setIPAddress(ip.raw_address()); 201 | SPI.endTransaction(); 202 | } 203 | 204 | void EthernetClass::setSubnetMask(const IPAddress subnet) 205 | { 206 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 207 | IPAddress ip = subnet; 208 | W5100.setSubnetMask(ip.raw_address()); 209 | SPI.endTransaction(); 210 | } 211 | 212 | void EthernetClass::setGatewayIP(const IPAddress gateway) 213 | { 214 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 215 | IPAddress ip = gateway; 216 | W5100.setGatewayIp(ip.raw_address()); 217 | SPI.endTransaction(); 218 | } 219 | 220 | void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds) 221 | { 222 | if (milliseconds > 6553) milliseconds = 6553; 223 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 224 | W5100.setRetransmissionTime(milliseconds * 10); 225 | SPI.endTransaction(); 226 | } 227 | 228 | void EthernetClass::setRetransmissionCount(uint8_t num) 229 | { 230 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 231 | W5100.setRetransmissionCount(num); 232 | SPI.endTransaction(); 233 | } 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | EthernetClass Ethernet; 245 | -------------------------------------------------------------------------------- /src/Ethernet.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #ifndef ethernet_h_ 22 | #define ethernet_h_ 23 | 24 | // All symbols exposed to Arduino sketches are contained in this header file 25 | // 26 | // Older versions had much of this stuff in EthernetClient.h, EthernetServer.h, 27 | // and socket.h. Including headers in different order could cause trouble, so 28 | // these "friend" classes are now defined in the same header file. socket.h 29 | // was removed to avoid possible conflict with the C library header files. 30 | 31 | 32 | // Configure the maximum number of sockets to support. W5100 chips can have 33 | // up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes 34 | // of RAM are used for each socket. Reducing the maximum can save RAM, but 35 | // you are limited to fewer simultaneous connections. 36 | #if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048) 37 | #define MAX_SOCK_NUM 4 38 | #else 39 | #define MAX_SOCK_NUM 8 40 | #endif 41 | 42 | // By default, each socket uses 2K buffers inside the Wiznet chip. If 43 | // MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting 44 | // this will use larger buffers within the Wiznet chip. Large buffers 45 | // can really help with UDP protocols like Artnet. In theory larger 46 | // buffers should allow faster TCP over high-latency links, but this 47 | // does not always seem to work in practice (maybe Wiznet bugs?) 48 | //#define ETHERNET_LARGE_BUFFERS 49 | 50 | //#define USE_SERIAL_DEBUG_PRINT 51 | 52 | #ifdef USE_SERIAL_DEBUG_PRINT 53 | #define PRINTLINE_DEF(var) \ 54 | PRINTLINE(); \ 55 | Serial.println("PRINTLINE_DEF("#var")"); 56 | #else 57 | #define PRINTLINE_DEF(var) 58 | #endif 59 | 60 | #ifdef USE_SERIAL_DEBUG_PRINT 61 | #define PRINTLINE() \ 62 | Serial.print("\r\n"); \ 63 | Serial.print(__FILE__); \ 64 | Serial.print(" "); \ 65 | Serial.println(__LINE__); 66 | #else 67 | #define PRINTLINE() 68 | #endif 69 | 70 | #ifdef USE_SERIAL_DEBUG_PRINT 71 | #define PRINTVAR_HEX(var) \ 72 | PRINTLINE(); \ 73 | Serial.print("PRINTVAR_HEX("#var")"); \ 74 | Serial.print(" = 0x"); \ 75 | Serial.println(var, HEX); 76 | #else 77 | #define PRINTVAR_HEX(var) 78 | #endif 79 | 80 | #ifdef USE_SERIAL_DEBUG_PRINT 81 | #define PRINTVAR_HEXD(var1, var2) \ 82 | PRINTLINE(); \ 83 | Serial.print("PRINTVAR_HEXD("#var1", "#var2")"); \ 84 | Serial.print(" = 0x"); \ 85 | Serial.print(var1, HEX); \ 86 | Serial.print(" = 0x"); \ 87 | Serial.println(var2, HEX); 88 | #else 89 | #define PRINTVAR_HEXD(var1, var2) 90 | #endif 91 | 92 | #ifdef USE_SERIAL_DEBUG_PRINT 93 | #define PRINTVAR_HEXT(var1, var2, var3) \ 94 | PRINTLINE(); \ 95 | Serial.print("PRINTVAR_HEXT("#var1", "#var2", "#var3")"); \ 96 | Serial.print(" = 0x"); \ 97 | Serial.print(var1, HEX); \ 98 | Serial.print(" = 0x"); \ 99 | Serial.print(var2, HEX); \ 100 | Serial.print(" = 0x"); \ 101 | Serial.println(var3, HEX); 102 | #else 103 | #define PRINTVAR_HEXT(var1, var2, var3) 104 | #endif 105 | 106 | #ifdef USE_SERIAL_DEBUG_PRINT 107 | #define PRINTVAR(var) \ 108 | PRINTLINE(); \ 109 | Serial.print("PRINTVAR("#var")"); \ 110 | Serial.print(" = "); \ 111 | Serial.println(var); 112 | #else 113 | #define PRINTVAR(var) 114 | #endif 115 | 116 | #ifdef USE_SERIAL_DEBUG_PRINT 117 | #define PRINTSTR(var) \ 118 | PRINTLINE(); \ 119 | Serial.println("PRINTVAR_STR("#var")"); 120 | #else 121 | #define PRINTSTR(var) 122 | #endif 123 | 124 | #include 125 | #include "Client.h" 126 | #include "Server.h" 127 | #include "Udp.h" 128 | 129 | enum EthernetLinkStatus { 130 | Unknown, 131 | LinkON, 132 | LinkOFF 133 | }; 134 | 135 | enum EthernetHardwareStatus { 136 | EthernetNoHardware, 137 | EthernetW5100, 138 | EthernetW5200, 139 | EthernetW5500, 140 | EthernetW6100, 141 | EthernetW5100S 142 | }; 143 | 144 | class EthernetUDP; 145 | class EthernetClient; 146 | class EthernetServer; 147 | class DhcpClass; 148 | 149 | class EthernetClass { 150 | private: 151 | static IPAddress _dnsServerAddress; 152 | static DhcpClass* _dhcp; 153 | public: 154 | // Initialise the Ethernet shield to use the provided MAC address and 155 | // gain the rest of the configuration through DHCP. 156 | // Returns 0 if the DHCP configuration failed, and 1 if it succeeded 157 | static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 158 | static int maintain(); 159 | static EthernetLinkStatus linkStatus(); 160 | static EthernetHardwareStatus hardwareStatus(); 161 | 162 | // Manaul configuration 163 | static void begin(uint8_t *mac, IPAddress ip); 164 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); 165 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); 166 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); 167 | static void init(uint8_t sspin = 10); 168 | 169 | static void MACAddress(uint8_t *mac_address); 170 | static IPAddress localIP(); 171 | static IPAddress subnetMask(); 172 | static IPAddress gatewayIP(); 173 | static IPAddress dnsServerIP() { return _dnsServerAddress; } 174 | 175 | void setMACAddress(const uint8_t *mac_address); 176 | void setLocalIP(const IPAddress local_ip); 177 | void setSubnetMask(const IPAddress subnet); 178 | void setGatewayIP(const IPAddress gateway); 179 | void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; } 180 | void setRetransmissionTimeout(uint16_t milliseconds); 181 | void setRetransmissionCount(uint8_t num); 182 | 183 | friend class EthernetClient; 184 | friend class EthernetServer; 185 | friend class EthernetUDP; 186 | private: 187 | // Opens a socket(TCP or UDP or IP_RAW mode) 188 | static uint8_t socketBegin(uint8_t protocol, uint16_t port); 189 | static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port); 190 | static uint8_t socketStatus(uint8_t s); 191 | // Close socket 192 | static void socketClose(uint8_t s); 193 | // Establish TCP connection (Active connection) 194 | static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port); 195 | // disconnect the connection 196 | static void socketDisconnect(uint8_t s); 197 | // Establish TCP connection (Passive connection) 198 | static uint8_t socketListen(uint8_t s); 199 | // Send data (TCP) 200 | static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len); 201 | static uint16_t socketSendAvailable(uint8_t s); 202 | // Receive data (TCP) 203 | static int socketRecv(uint8_t s, uint8_t * buf, int16_t len); 204 | static uint16_t socketRecvAvailable(uint8_t s); 205 | static uint8_t socketPeek(uint8_t s); 206 | // sets up a UDP datagram, the data for which will be provided by one 207 | // or more calls to bufferData and then finally sent with sendUDP. 208 | // return true if the datagram was successfully set up, or false if there was an error 209 | static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port); 210 | // copy up to len bytes of data from buf into a UDP datagram to be 211 | // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. 212 | // return Number of bytes successfully buffered 213 | static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len); 214 | // Send a UDP datagram built up from a sequence of startUDP followed by one or more 215 | // calls to bufferData. 216 | // return true if the datagram was successfully sent, or false if there was an error 217 | static bool socketSendUDP(uint8_t s); 218 | // Initialize the "random" source port number 219 | static void socketPortRand(uint16_t n); 220 | }; 221 | 222 | extern EthernetClass Ethernet; 223 | 224 | 225 | #define UDP_TX_PACKET_MAX_SIZE 24 226 | 227 | class EthernetUDP : public UDP { 228 | private: 229 | uint16_t _port; // local port to listen on 230 | IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed 231 | uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed 232 | uint16_t _offset; // offset into the packet being sent 233 | 234 | protected: 235 | uint8_t sockindex; 236 | uint16_t _remaining; // remaining bytes of incoming packet yet to be processed 237 | 238 | public: 239 | EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor 240 | virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use 241 | virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use 242 | virtual void stop(); // Finish with the UDP socket 243 | 244 | // Sending UDP packets 245 | 246 | // Start building up a packet to send to the remote host specific in ip and port 247 | // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port 248 | virtual int beginPacket(IPAddress ip, uint16_t port); 249 | // Start building up a packet to send to the remote host specific in host and port 250 | // Returns 1 if successful, 0 if there was a problem resolving the hostname or port 251 | virtual int beginPacket(const char *host, uint16_t port); 252 | // Finish off this packet and send it 253 | // Returns 1 if the packet was sent successfully, 0 if there was an error 254 | virtual int endPacket(); 255 | // Write a single byte into the packet 256 | virtual size_t write(uint8_t); 257 | // Write size bytes from buffer into the packet 258 | virtual size_t write(const uint8_t *buffer, size_t size); 259 | 260 | using Print::write; 261 | 262 | // Start processing the next available incoming packet 263 | // Returns the size of the packet in bytes, or 0 if no packets are available 264 | virtual int parsePacket(); 265 | // Number of bytes remaining in the current packet 266 | virtual int available(); 267 | // Read a single byte from the current packet 268 | virtual int read(); 269 | // Read up to len bytes from the current packet and place them into buffer 270 | // Returns the number of bytes read, or 0 if none are available 271 | virtual int read(unsigned char* buffer, size_t len); 272 | // Read up to len characters from the current packet and place them into buffer 273 | // Returns the number of characters read, or 0 if none are available 274 | virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; 275 | // Return the next byte from the current packet without moving on to the next byte 276 | virtual int peek(); 277 | virtual void flush(); // Finish reading the current packet 278 | 279 | // Return the IP address of the host who sent the current incoming packet 280 | virtual IPAddress remoteIP() { return _remoteIP; }; 281 | // Return the port of the host who sent the current incoming packet 282 | virtual uint16_t remotePort() { return _remotePort; }; 283 | virtual uint16_t localPort() { return _port; } 284 | }; 285 | 286 | 287 | 288 | 289 | class EthernetClient : public Client { 290 | public: 291 | EthernetClient() : sockindex(MAX_SOCK_NUM), _timeout(1000) { } 292 | EthernetClient(uint8_t s) : sockindex(s), _timeout(1000) { } 293 | 294 | uint8_t status(); 295 | virtual int connect(IPAddress ip, uint16_t port); 296 | virtual int connect(const char *host, uint16_t port); 297 | virtual int availableForWrite(void); 298 | virtual size_t write(uint8_t); 299 | virtual size_t write(const uint8_t *buf, size_t size); 300 | virtual int available(); 301 | virtual int read(); 302 | virtual int read(uint8_t *buf, size_t size); 303 | virtual int peek(); 304 | virtual void flush(); 305 | virtual void stop(); 306 | virtual uint8_t connected(); 307 | virtual operator bool() { return sockindex < MAX_SOCK_NUM; } 308 | virtual bool operator==(const bool value) { return bool() == value; } 309 | virtual bool operator!=(const bool value) { return bool() != value; } 310 | virtual bool operator==(const EthernetClient&); 311 | virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } 312 | uint8_t getSocketNumber() const { return sockindex; } 313 | virtual uint16_t localPort(); 314 | virtual IPAddress remoteIP(); 315 | virtual uint16_t remotePort(); 316 | virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; } 317 | 318 | friend class EthernetServer; 319 | 320 | using Print::write; 321 | 322 | private: 323 | uint8_t sockindex; // MAX_SOCK_NUM means client not in use 324 | uint16_t _timeout; 325 | }; 326 | 327 | 328 | class EthernetServer : public Server { 329 | private: 330 | uint16_t _port; 331 | public: 332 | EthernetServer(uint16_t port) : _port(port) { } 333 | EthernetClient available(); 334 | EthernetClient accept(); 335 | virtual void begin(); 336 | virtual size_t write(uint8_t); 337 | virtual size_t write(const uint8_t *buf, size_t size); 338 | virtual operator bool(); 339 | using Print::write; 340 | //void statusreport(); 341 | 342 | // TODO: make private when socket allocation moves to EthernetClass 343 | static uint16_t server_port[MAX_SOCK_NUM]; 344 | }; 345 | 346 | 347 | class DhcpClass { 348 | private: 349 | uint32_t _dhcpInitialTransactionId; 350 | uint32_t _dhcpTransactionId; 351 | uint8_t _dhcpMacAddr[6]; 352 | #ifdef __arm__ 353 | uint8_t _dhcpLocalIp[4] __attribute__((aligned(4))); 354 | uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4))); 355 | uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4))); 356 | uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4))); 357 | uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4))); 358 | #else 359 | uint8_t _dhcpLocalIp[4]; 360 | uint8_t _dhcpSubnetMask[4]; 361 | uint8_t _dhcpGatewayIp[4]; 362 | uint8_t _dhcpDhcpServerIp[4]; 363 | uint8_t _dhcpDnsServerIp[4]; 364 | #endif 365 | uint32_t _dhcpLeaseTime; 366 | uint32_t _dhcpT1, _dhcpT2; 367 | uint32_t _renewInSec; 368 | uint32_t _rebindInSec; 369 | unsigned long _timeout; 370 | unsigned long _responseTimeout; 371 | unsigned long _lastCheckLeaseMillis; 372 | uint8_t _dhcp_state; 373 | EthernetUDP _dhcpUdpSocket; 374 | 375 | int request_DHCP_lease(); 376 | void reset_DHCP_lease(); 377 | void presend_DHCP(); 378 | void send_DHCP_MESSAGE(uint8_t, uint16_t); 379 | void printByte(char *, uint8_t); 380 | 381 | uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); 382 | public: 383 | IPAddress getLocalIp(); 384 | IPAddress getSubnetMask(); 385 | IPAddress getGatewayIp(); 386 | IPAddress getDhcpServerIp(); 387 | IPAddress getDnsServerIp(); 388 | 389 | int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 390 | int checkLease(); 391 | }; 392 | 393 | 394 | 395 | 396 | 397 | #endif 398 | -------------------------------------------------------------------------------- /src/EthernetClient.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "Dns.h" 24 | #include "utility/w5100.h" 25 | 26 | int EthernetClient::connect(const char * host, uint16_t port) 27 | { 28 | DNSClient dns; // Look up the host first 29 | IPAddress remote_addr; 30 | 31 | if (sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { 33 | Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? 34 | } 35 | sockindex = MAX_SOCK_NUM; 36 | } 37 | dns.begin(Ethernet.dnsServerIP()); 38 | if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout 39 | return connect(remote_addr, port); 40 | } 41 | 42 | int EthernetClient::connect(IPAddress ip, uint16_t port) 43 | { 44 | if (sockindex < MAX_SOCK_NUM) { 45 | if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { 46 | Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? 47 | } 48 | sockindex = MAX_SOCK_NUM; 49 | } 50 | #if defined(ESP8266) || defined(ESP32) 51 | if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; 52 | #else 53 | if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; 54 | #endif 55 | sockindex = Ethernet.socketBegin(SnMR::TCP, 0); 56 | if (sockindex >= MAX_SOCK_NUM) return 0; 57 | Ethernet.socketConnect(sockindex, rawIPAddress(ip), port); 58 | uint32_t start = millis(); 59 | while (1) { 60 | uint8_t stat = Ethernet.socketStatus(sockindex); 61 | if (stat == SnSR::ESTABLISHED) return 1; 62 | if (stat == SnSR::CLOSE_WAIT) return 1; 63 | if (stat == SnSR::CLOSED) return 0; 64 | if (millis() - start > _timeout) break; 65 | delay(1); 66 | } 67 | Ethernet.socketClose(sockindex); 68 | sockindex = MAX_SOCK_NUM; 69 | return 0; 70 | } 71 | 72 | int EthernetClient::availableForWrite(void) 73 | { 74 | if (sockindex >= MAX_SOCK_NUM) return 0; 75 | return Ethernet.socketSendAvailable(sockindex); 76 | } 77 | 78 | size_t EthernetClient::write(uint8_t b) 79 | { 80 | return write(&b, 1); 81 | } 82 | 83 | size_t EthernetClient::write(const uint8_t *buf, size_t size) 84 | { 85 | if (sockindex >= MAX_SOCK_NUM) return 0; 86 | if (Ethernet.socketSend(sockindex, buf, size)) return size; 87 | setWriteError(); 88 | return 0; 89 | } 90 | 91 | int EthernetClient::available() 92 | { 93 | if (sockindex >= MAX_SOCK_NUM) return 0; 94 | return Ethernet.socketRecvAvailable(sockindex); 95 | // TODO: do the Wiznet chips automatically retransmit TCP ACK 96 | // packets if they are lost by the network? Someday this should 97 | // be checked by a man-in-the-middle test which discards certain 98 | // packets. If ACKs aren't resent, we would need to check for 99 | // returning 0 here and after a timeout do another Sock_RECV 100 | // command to cause the Wiznet chip to resend the ACK packet. 101 | } 102 | 103 | int EthernetClient::read(uint8_t *buf, size_t size) 104 | { 105 | if (sockindex >= MAX_SOCK_NUM) return 0; 106 | return Ethernet.socketRecv(sockindex, buf, size); 107 | } 108 | 109 | int EthernetClient::peek() 110 | { 111 | if (sockindex >= MAX_SOCK_NUM) return -1; 112 | if (!available()) return -1; 113 | return Ethernet.socketPeek(sockindex); 114 | } 115 | 116 | int EthernetClient::read() 117 | { 118 | uint8_t b; 119 | if (Ethernet.socketRecv(sockindex, &b, 1) > 0) return b; 120 | return -1; 121 | } 122 | 123 | void EthernetClient::flush() 124 | { 125 | while (sockindex < MAX_SOCK_NUM) { 126 | uint8_t stat = Ethernet.socketStatus(sockindex); 127 | if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; 128 | if (Ethernet.socketSendAvailable(sockindex) >= W5100.SSIZE) return; 129 | } 130 | } 131 | 132 | void EthernetClient::stop() 133 | { 134 | if (sockindex >= MAX_SOCK_NUM) return; 135 | 136 | // attempt to close the connection gracefully (send a FIN to other side) 137 | Ethernet.socketDisconnect(sockindex); 138 | unsigned long start = millis(); 139 | 140 | // wait up to a second for the connection to close 141 | do { 142 | if (Ethernet.socketStatus(sockindex) == SnSR::CLOSED) { 143 | sockindex = MAX_SOCK_NUM; 144 | return; // exit the loop 145 | } 146 | delay(1); 147 | } while (millis() - start < _timeout); 148 | 149 | // if it hasn't closed, close it forcefully 150 | Ethernet.socketClose(sockindex); 151 | sockindex = MAX_SOCK_NUM; 152 | } 153 | 154 | uint8_t EthernetClient::connected() 155 | { 156 | if (sockindex >= MAX_SOCK_NUM) return 0; 157 | 158 | uint8_t s = Ethernet.socketStatus(sockindex); 159 | return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || 160 | (s == SnSR::CLOSE_WAIT && !available())); 161 | } 162 | 163 | uint8_t EthernetClient::status() 164 | { 165 | if (sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; 166 | return Ethernet.socketStatus(sockindex); 167 | } 168 | 169 | // the next function allows us to use the client returned by 170 | // EthernetServer::available() as the condition in an if-statement. 171 | bool EthernetClient::operator==(const EthernetClient& rhs) 172 | { 173 | if (sockindex != rhs.sockindex) return false; 174 | if (sockindex >= MAX_SOCK_NUM) return false; 175 | if (rhs.sockindex >= MAX_SOCK_NUM) return false; 176 | return true; 177 | } 178 | 179 | // https://github.com/per1234/EthernetMod 180 | // from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd 181 | uint16_t EthernetClient::localPort() 182 | { 183 | if (sockindex >= MAX_SOCK_NUM) return 0; 184 | uint16_t port; 185 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 186 | port = W5100.readSnPORT(sockindex); 187 | SPI.endTransaction(); 188 | return port; 189 | } 190 | 191 | // https://github.com/per1234/EthernetMod 192 | // returns the remote IP address: http://forum.arduino.cc/index.php?topic=82416.0 193 | IPAddress EthernetClient::remoteIP() 194 | { 195 | if (sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); 196 | uint8_t remoteIParray[4]; 197 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 198 | W5100.readSnDIPR(sockindex, remoteIParray); 199 | SPI.endTransaction(); 200 | return IPAddress(remoteIParray); 201 | } 202 | 203 | // https://github.com/per1234/EthernetMod 204 | // from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75 205 | uint16_t EthernetClient::remotePort() 206 | { 207 | if (sockindex >= MAX_SOCK_NUM) return 0; 208 | uint16_t port; 209 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 210 | port = W5100.readSnDPORT(sockindex); 211 | SPI.endTransaction(); 212 | return port; 213 | } 214 | 215 | 216 | -------------------------------------------------------------------------------- /src/EthernetClient.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /src/EthernetServer.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | 25 | uint16_t EthernetServer::server_port[MAX_SOCK_NUM]; 26 | 27 | 28 | void EthernetServer::begin() 29 | { 30 | uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port); 31 | if (sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketListen(sockindex)) { 33 | server_port[sockindex] = _port; 34 | } else { 35 | Ethernet.socketDisconnect(sockindex); 36 | } 37 | } 38 | } 39 | 40 | EthernetClient EthernetServer::available() 41 | { 42 | bool listening = false; 43 | uint8_t sockindex = MAX_SOCK_NUM; 44 | uint8_t chip, maxindex=MAX_SOCK_NUM; 45 | 46 | chip = W5100.getChip(); 47 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 48 | #if MAX_SOCK_NUM > 4 49 | if (chip == 51 || chip == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 50 | #endif 51 | for (uint8_t i=0; i < maxindex; i++) { 52 | if (server_port[i] == _port) { 53 | uint8_t stat = Ethernet.socketStatus(i); 54 | if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) { 55 | if (Ethernet.socketRecvAvailable(i) > 0) { 56 | sockindex = i; 57 | } else { 58 | // remote host closed connection, our end still open 59 | if (stat == SnSR::CLOSE_WAIT) { 60 | Ethernet.socketDisconnect(i); 61 | // status becomes LAST_ACK for short time 62 | } 63 | } 64 | } else if (stat == SnSR::LISTEN) { 65 | listening = true; 66 | } else if (stat == SnSR::CLOSED) { 67 | server_port[i] = 0; 68 | } 69 | } 70 | } 71 | if (!listening) begin(); 72 | return EthernetClient(sockindex); 73 | } 74 | 75 | EthernetClient EthernetServer::accept() 76 | { 77 | bool listening = false; 78 | uint8_t sockindex = MAX_SOCK_NUM; 79 | uint8_t chip, maxindex=MAX_SOCK_NUM; 80 | 81 | chip = W5100.getChip(); 82 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 83 | #if MAX_SOCK_NUM > 4 84 | if (chip == 51 || chip == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 85 | #endif 86 | for (uint8_t i=0; i < maxindex; i++) { 87 | if (server_port[i] == _port) { 88 | uint8_t stat = Ethernet.socketStatus(i); 89 | if (sockindex == MAX_SOCK_NUM && 90 | (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) { 91 | // Return the connected client even if no data received. 92 | // Some protocols like FTP expect the server to send the 93 | // first data. 94 | sockindex = i; 95 | server_port[i] = 0; // only return the client once 96 | } else if (stat == SnSR::LISTEN) { 97 | listening = true; 98 | } else if (stat == SnSR::CLOSED) { 99 | server_port[i] = 0; 100 | } 101 | } 102 | } 103 | if (!listening) begin(); 104 | return EthernetClient(sockindex); 105 | } 106 | 107 | EthernetServer::operator bool() 108 | { 109 | uint8_t maxindex=MAX_SOCK_NUM; 110 | #if MAX_SOCK_NUM > 4 111 | if (W5100.getChip() == 51 || W5100.getChip() == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 112 | #endif 113 | for (uint8_t i=0; i < maxindex; i++) { 114 | if (server_port[i] == _port) { 115 | if (Ethernet.socketStatus(i) == SnSR::LISTEN) { 116 | return true; // server is listening for incoming clients 117 | } 118 | } 119 | } 120 | return false; 121 | } 122 | 123 | #if 0 124 | void EthernetServer::statusreport() 125 | { 126 | Serial.printf("EthernetServer, port=%d\n", _port); 127 | for (uint8_t i=0; i < MAX_SOCK_NUM; i++) { 128 | uint16_t port = server_port[i]; 129 | uint8_t stat = Ethernet.socketStatus(i); 130 | const char *name; 131 | switch (stat) { 132 | case 0x00: name = "CLOSED"; break; 133 | case 0x13: name = "INIT"; break; 134 | case 0x14: name = "LISTEN"; break; 135 | case 0x15: name = "SYNSENT"; break; 136 | case 0x16: name = "SYNRECV"; break; 137 | case 0x17: name = "ESTABLISHED"; break; 138 | case 0x18: name = "FIN_WAIT"; break; 139 | case 0x1A: name = "CLOSING"; break; 140 | case 0x1B: name = "TIME_WAIT"; break; 141 | case 0x1C: name = "CLOSE_WAIT"; break; 142 | case 0x1D: name = "LAST_ACK"; break; 143 | case 0x22: name = "UDP"; break; 144 | case 0x32: name = "IPRAW"; break; 145 | case 0x42: name = "MACRAW"; break; 146 | case 0x5F: name = "PPPOE"; break; 147 | default: name = "???"; 148 | } 149 | int avail = Ethernet.socketRecvAvailable(i); 150 | Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n", 151 | i, port, name, stat, avail); 152 | } 153 | } 154 | #endif 155 | 156 | size_t EthernetServer::write(uint8_t b) 157 | { 158 | return write(&b, 1); 159 | } 160 | 161 | size_t EthernetServer::write(const uint8_t *buffer, size_t size) 162 | { 163 | uint8_t chip, maxindex=MAX_SOCK_NUM; 164 | 165 | chip = W5100.getChip(); 166 | if (!chip) return 0; 167 | #if MAX_SOCK_NUM > 4 168 | if (chip == 51 || chip == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 169 | #endif 170 | available(); 171 | for (uint8_t i=0; i < maxindex; i++) { 172 | if (server_port[i] == _port) { 173 | if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) { 174 | Ethernet.socketSend(i, buffer, size); 175 | } 176 | } 177 | } 178 | return size; 179 | } 180 | -------------------------------------------------------------------------------- /src/EthernetServer.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /src/EthernetUdp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * MIT License: 7 | * Copyright (c) 2008 Bjoern Hartmann 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | * 26 | * bjoern@cs.stanford.edu 12/30/2008 27 | */ 28 | 29 | #include 30 | #include "Ethernet.h" 31 | #include "Dns.h" 32 | #include "utility/w5100.h" 33 | 34 | /* Start EthernetUDP socket, listening at local port PORT */ 35 | uint8_t EthernetUDP::begin(uint16_t port) 36 | { 37 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); 38 | sockindex = Ethernet.socketBegin(SnMR::UDP, port); 39 | if (sockindex >= MAX_SOCK_NUM) return 0; 40 | _port = port; 41 | _remaining = 0; 42 | return 1; 43 | } 44 | 45 | /* return number of bytes available in the current packet, 46 | will return zero if parsePacket hasn't been called yet */ 47 | int EthernetUDP::available() 48 | { 49 | return _remaining; 50 | } 51 | 52 | /* Release any resources being used by this EthernetUDP instance */ 53 | void EthernetUDP::stop() 54 | { 55 | if (sockindex < MAX_SOCK_NUM) { 56 | Ethernet.socketClose(sockindex); 57 | sockindex = MAX_SOCK_NUM; 58 | } 59 | } 60 | 61 | int EthernetUDP::beginPacket(const char *host, uint16_t port) 62 | { 63 | // Look up the host first 64 | int ret = 0; 65 | DNSClient dns; 66 | IPAddress remote_addr; 67 | 68 | dns.begin(Ethernet.dnsServerIP()); 69 | ret = dns.getHostByName(host, remote_addr); 70 | if (ret != 1) return ret; 71 | return beginPacket(remote_addr, port); 72 | } 73 | 74 | int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) 75 | { 76 | _offset = 0; 77 | //Serial.printf("UDP beginPacket\n"); 78 | return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port); 79 | } 80 | 81 | int EthernetUDP::endPacket() 82 | { 83 | return Ethernet.socketSendUDP(sockindex); 84 | } 85 | 86 | size_t EthernetUDP::write(uint8_t byte) 87 | { 88 | return write(&byte, 1); 89 | } 90 | 91 | size_t EthernetUDP::write(const uint8_t *buffer, size_t size) 92 | { 93 | //Serial.printf("UDP write %d\n", size); 94 | uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size); 95 | _offset += bytes_written; 96 | return bytes_written; 97 | } 98 | 99 | int EthernetUDP::parsePacket() 100 | { 101 | // discard any remaining bytes in the last packet 102 | while (_remaining) { 103 | // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? 104 | // should only occur if recv fails after telling us the data is there, lets 105 | // hope the w5100 always behaves :) 106 | read((uint8_t *)NULL, _remaining); 107 | } 108 | 109 | if (Ethernet.socketRecvAvailable(sockindex) > 0) { 110 | //HACK - hand-parse the UDP packet using TCP recv method 111 | uint8_t tmpBuf[20]; 112 | int ret=0; 113 | 114 | if(W5100.getChip() == 61) { 115 | //read 2 header bytes and get one IPv4 or IPv6 116 | ret = Ethernet.socketRecv(sockindex, tmpBuf, 2); 117 | if(ret > 0) { 118 | _remaining = (tmpBuf[0] & (0x7))<<8 | tmpBuf[1]; 119 | 120 | if((tmpBuf[0] & W6100_UDP_HEADER_IPV) == W6100_UDP_HEADER_IPV6) { 121 | // IPv6 UDP Recived 122 | // 0 1 123 | // 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 124 | // 18 19 125 | 126 | //read 16 header bytes and get IP and port from it 127 | ret = Ethernet.socketRecv(sockindex, &tmpBuf[2], 18); 128 | _remoteIP = &tmpBuf[2]; 129 | _remotePort = (tmpBuf[18]<<8) | tmpBuf[19]; 130 | } else { 131 | // IPv4 UDP Recived 132 | // 0 1 133 | // 2 3 4 5 134 | // 6 7 135 | 136 | //read 6 header bytes and get IP and port from it 137 | ret = Ethernet.socketRecv(sockindex, &tmpBuf[2], 6); 138 | _remoteIP = &tmpBuf[2]; 139 | _remotePort = (tmpBuf[6]<<8) | tmpBuf[7]; 140 | } 141 | 142 | ret = _remaining; 143 | } 144 | } else { 145 | //read 8 header bytes and get IP and port from it 146 | ret = Ethernet.socketRecv(sockindex, tmpBuf, 8); 147 | 148 | if (ret > 0) { 149 | 150 | _remoteIP = tmpBuf; 151 | _remotePort = tmpBuf[4]; 152 | _remotePort = (_remotePort << 8) + tmpBuf[5]; 153 | _remaining = tmpBuf[6]; 154 | _remaining = (_remaining << 8) + tmpBuf[7]; 155 | 156 | // When we get here, any remaining bytes are the data 157 | ret = _remaining; 158 | } 159 | } 160 | return ret; 161 | } 162 | // There aren't any packets available 163 | return 0; 164 | } 165 | 166 | int EthernetUDP::read() 167 | { 168 | uint8_t byte; 169 | 170 | if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) { 171 | // We read things without any problems 172 | _remaining--; 173 | return byte; 174 | } 175 | 176 | // If we get here, there's no data available 177 | return -1; 178 | } 179 | 180 | int EthernetUDP::read(unsigned char *buffer, size_t len) 181 | { 182 | if (_remaining > 0) { 183 | int got; 184 | if (_remaining <= len) { 185 | // data should fit in the buffer 186 | got = Ethernet.socketRecv(sockindex, buffer, _remaining); 187 | } else { 188 | // too much data for the buffer, 189 | // grab as much as will fit 190 | got = Ethernet.socketRecv(sockindex, buffer, len); 191 | } 192 | if (got > 0) { 193 | _remaining -= got; 194 | //Serial.printf("UDP read %d\n", got); 195 | return got; 196 | } 197 | } 198 | // If we get here, there's no data available or recv failed 199 | return -1; 200 | } 201 | 202 | int EthernetUDP::peek() 203 | { 204 | // Unlike recv, peek doesn't check to see if there's any data available, so we must. 205 | // If the user hasn't called parsePacket yet then return nothing otherwise they 206 | // may get the UDP header 207 | if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1; 208 | return Ethernet.socketPeek(sockindex); 209 | } 210 | 211 | void EthernetUDP::flush() 212 | { 213 | // TODO: we should wait for TX buffer to be emptied 214 | } 215 | 216 | /* Start EthernetUDP socket, listening at local port PORT */ 217 | uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port) 218 | { 219 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); 220 | sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port); 221 | if (sockindex >= MAX_SOCK_NUM) return 0; 222 | _port = port; 223 | _remaining = 0; 224 | return 1; 225 | } 226 | 227 | -------------------------------------------------------------------------------- /src/EthernetUdp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) 7 | * 1) UDP does not guarantee the order in which assembled UDP packets are received. This 8 | * might not happen often in practice, but in larger network topologies, a UDP 9 | * packet can be received out of sequence. 10 | * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being 11 | * aware of it. Again, this may not be a concern in practice on small local networks. 12 | * For more information, see http://www.cafeaulait.org/course/week12/35.html 13 | * 14 | * MIT License: 15 | * Copyright (c) 2008 Bjoern Hartmann 16 | * Permission is hereby granted, free of charge, to any person obtaining a copy 17 | * of this software and associated documentation files (the "Software"), to deal 18 | * in the Software without restriction, including without limitation the rights 19 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 | * copies of the Software, and to permit persons to whom the Software is 21 | * furnished to do so, subject to the following conditions: 22 | * 23 | * The above copyright notice and this permission notice shall be included in 24 | * all copies or substantial portions of the Software. 25 | * 26 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 29 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 32 | * THE SOFTWARE. 33 | * 34 | * bjoern@cs.stanford.edu 12/30/2008 35 | */ 36 | 37 | #include "Ethernet.h" 38 | 39 | -------------------------------------------------------------------------------- /src/socket.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | 25 | #if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32) 26 | extern void yield(void); 27 | #else 28 | #define yield() 29 | #endif 30 | 31 | // TODO: randomize this when not using DHCP, but how? 32 | static uint16_t local_port = 49152; // 49152 to 65535 33 | 34 | typedef struct { 35 | uint16_t RX_RSR; // Number of bytes received 36 | uint16_t RX_RD; // Address to read 37 | uint16_t TX_FSR; // Free space ready for transmit 38 | uint8_t RX_inc; // how much have we advanced RX_RD 39 | } socketstate_t; 40 | 41 | static socketstate_t state[MAX_SOCK_NUM]; 42 | 43 | 44 | static uint16_t getSnTX_FSR(uint8_t s); 45 | static uint16_t getSnRX_RSR(uint8_t s); 46 | static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len); 47 | static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len); 48 | 49 | 50 | 51 | /*****************************************/ 52 | /* Socket management */ 53 | /*****************************************/ 54 | 55 | 56 | void EthernetClass::socketPortRand(uint16_t n) 57 | { 58 | n &= 0x3FFF; 59 | local_port ^= n; 60 | //Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port); 61 | } 62 | 63 | uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port) 64 | { 65 | uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; 66 | 67 | // first check hardware compatibility 68 | chip = W5100.getChip(); 69 | if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected 70 | #if MAX_SOCK_NUM > 4 71 | if (chip == 51 || chip == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 72 | #endif 73 | //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); 74 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 75 | // look at all the hardware sockets, use any that are closed (unused) 76 | for (s=0; s < maxindex; s++) { 77 | status[s] = W5100.readSnSR(s); 78 | if (status[s] == SnSR::CLOSED) goto makesocket; 79 | } 80 | //Serial.printf("W5000socket step2\n"); 81 | // as a last resort, forcibly close any already closing 82 | for (s=0; s < maxindex; s++) { 83 | uint8_t stat = status[s]; 84 | if (stat == SnSR::LAST_ACK) goto closemakesocket; 85 | if (stat == SnSR::TIME_WAIT) goto closemakesocket; 86 | if (stat == SnSR::FIN_WAIT) goto closemakesocket; 87 | if (stat == SnSR::CLOSING) goto closemakesocket; 88 | } 89 | #if 0 90 | Serial.printf("W5000socket step3\n"); 91 | // next, use any that are effectively closed 92 | for (s=0; s < MAX_SOCK_NUM; s++) { 93 | uint8_t stat = status[s]; 94 | // TODO: this also needs to check if no more data 95 | if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; 96 | } 97 | #endif 98 | SPI.endTransaction(); 99 | return MAX_SOCK_NUM; // all sockets are in use 100 | closemakesocket: 101 | //Serial.printf("W5000socket close\n"); 102 | W5100.execCmdSn(s, Sock_CLOSE); 103 | makesocket: 104 | //Serial.printf("W5000socket %d\n", s); 105 | EthernetServer::server_port[s] = 0; 106 | delayMicroseconds(250); // TODO: is this needed?? 107 | W5100.writeSnMR(s, protocol); 108 | W5100.writeSnIR(s, 0xFF); 109 | if (port > 0) { 110 | W5100.writeSnPORT(s, port); 111 | } else { 112 | // if don't set the source port, set local_port number. 113 | if (++local_port < 49152) local_port = 49152; 114 | W5100.writeSnPORT(s, local_port); 115 | } 116 | W5100.execCmdSn(s, Sock_OPEN); 117 | state[s].RX_RSR = 0; 118 | state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? 119 | state[s].RX_inc = 0; 120 | state[s].TX_FSR = 0; 121 | //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); 122 | SPI.endTransaction(); 123 | return s; 124 | } 125 | 126 | // multicast version to set fields before open thd 127 | uint8_t EthernetClass::socketBeginMulticast(uint8_t protocol, IPAddress ip, uint16_t port) 128 | { 129 | uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; 130 | 131 | // first check hardware compatibility 132 | chip = W5100.getChip(); 133 | if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected 134 | #if MAX_SOCK_NUM > 4 135 | if (chip == 51 || chip == 50) maxindex = 4; // W5100 chip never supports more than 4 sockets 136 | #endif 137 | //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); 138 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 139 | // look at all the hardware sockets, use any that are closed (unused) 140 | for (s=0; s < maxindex; s++) { 141 | status[s] = W5100.readSnSR(s); 142 | if (status[s] == SnSR::CLOSED) goto makesocket; 143 | } 144 | //Serial.printf("W5000socket step2\n"); 145 | // as a last resort, forcibly close any already closing 146 | for (s=0; s < maxindex; s++) { 147 | uint8_t stat = status[s]; 148 | if (stat == SnSR::LAST_ACK) goto closemakesocket; 149 | if (stat == SnSR::TIME_WAIT) goto closemakesocket; 150 | if (stat == SnSR::FIN_WAIT) goto closemakesocket; 151 | if (stat == SnSR::CLOSING) goto closemakesocket; 152 | } 153 | #if 0 154 | Serial.printf("W5000socket step3\n"); 155 | // next, use any that are effectively closed 156 | for (s=0; s < MAX_SOCK_NUM; s++) { 157 | uint8_t stat = status[s]; 158 | // TODO: this also needs to check if no more data 159 | if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; 160 | } 161 | #endif 162 | SPI.endTransaction(); 163 | return MAX_SOCK_NUM; // all sockets are in use 164 | closemakesocket: 165 | //Serial.printf("W5000socket close\n"); 166 | W5100.execCmdSn(s, Sock_CLOSE); 167 | makesocket: 168 | //Serial.printf("W5000socket %d\n", s); 169 | EthernetServer::server_port[s] = 0; 170 | delayMicroseconds(250); // TODO: is this needed?? 171 | W5100.writeSnMR(s, protocol); 172 | W5100.writeSnIR(s, 0xFF); 173 | if (port > 0) { 174 | W5100.writeSnPORT(s, port); 175 | } else { 176 | // if don't set the source port, set local_port number. 177 | if (++local_port < 49152) local_port = 49152; 178 | W5100.writeSnPORT(s, local_port); 179 | } 180 | // Calculate MAC address from Multicast IP Address 181 | byte mac[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00 }; 182 | mac[3] = ip[1] & 0x7F; 183 | mac[4] = ip[2]; 184 | mac[5] = ip[3]; 185 | W5100.writeSnDIPR(s, ip.raw_address()); //239.255.0.1 186 | W5100.writeSnDPORT(s, port); 187 | W5100.writeSnDHAR(s, mac); 188 | W5100.execCmdSn(s, Sock_OPEN); 189 | state[s].RX_RSR = 0; 190 | state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? 191 | state[s].RX_inc = 0; 192 | state[s].TX_FSR = 0; 193 | //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); 194 | SPI.endTransaction(); 195 | return s; 196 | } 197 | // Return the socket's status 198 | // 199 | uint8_t EthernetClass::socketStatus(uint8_t s) 200 | { 201 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 202 | uint8_t status = W5100.readSnSR(s); 203 | SPI.endTransaction(); 204 | return status; 205 | } 206 | 207 | // Immediately close. If a TCP connection is established, the 208 | // remote host is left unaware we closed. 209 | // 210 | void EthernetClass::socketClose(uint8_t s) 211 | { 212 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 213 | W5100.execCmdSn(s, Sock_CLOSE); 214 | SPI.endTransaction(); 215 | } 216 | 217 | 218 | // Place the socket in listening (server) mode 219 | // 220 | uint8_t EthernetClass::socketListen(uint8_t s) 221 | { 222 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 223 | if (W5100.readSnSR(s) != SnSR::INIT) { 224 | SPI.endTransaction(); 225 | return 0; 226 | } 227 | W5100.execCmdSn(s, Sock_LISTEN); 228 | SPI.endTransaction(); 229 | return 1; 230 | } 231 | 232 | 233 | // establish a TCP connection in Active (client) mode. 234 | // 235 | void EthernetClass::socketConnect(uint8_t s, uint8_t * addr, uint16_t port) 236 | { 237 | // set destination IP 238 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 239 | W5100.writeSnDIPR(s, addr); 240 | W5100.writeSnDPORT(s, port); 241 | W5100.execCmdSn(s, Sock_CONNECT); 242 | SPI.endTransaction(); 243 | } 244 | 245 | 246 | 247 | // Gracefully disconnect a TCP connection. 248 | // 249 | void EthernetClass::socketDisconnect(uint8_t s) 250 | { 251 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 252 | W5100.execCmdSn(s, Sock_DISCON); 253 | SPI.endTransaction(); 254 | } 255 | 256 | 257 | 258 | /*****************************************/ 259 | /* Socket Data Receive Functions */ 260 | /*****************************************/ 261 | 262 | 263 | static uint16_t getSnRX_RSR(uint8_t s) 264 | { 265 | #if 1 266 | uint16_t val, prev; 267 | 268 | prev = W5100.readSnRX_RSR(s); 269 | while (1) { 270 | val = W5100.readSnRX_RSR(s); 271 | if (val == prev) { 272 | return val; 273 | } 274 | prev = val; 275 | } 276 | #else 277 | uint16_t val = W5100.readSnRX_RSR(s); 278 | return val; 279 | #endif 280 | } 281 | 282 | static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len) 283 | { 284 | uint16_t size; 285 | uint16_t src_mask; 286 | uint16_t src_ptr; 287 | 288 | //Serial.printf("read_data, len=%d, at:%d\n", len, src); 289 | src_mask = (uint16_t)src & W5100.SMASK; 290 | src_ptr = W5100.RBASE(s) + src_mask; 291 | 292 | if (W5100.hasOffsetAddressMapping() || src_mask + len <= W5100.SSIZE) { 293 | W5100.read(src_ptr, dst, len); 294 | } else { 295 | size = W5100.SSIZE - src_mask; 296 | W5100.read(src_ptr, dst, size); 297 | dst += size; 298 | W5100.read(W5100.RBASE(s), dst, len - size); 299 | } 300 | } 301 | 302 | // Receive data. Returns size, or -1 for no data, or 0 if connection closed 303 | // 304 | int EthernetClass::socketRecv(uint8_t s, uint8_t *buf, int16_t len) 305 | { 306 | // Check how much data is available 307 | int ret = state[s].RX_RSR; 308 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 309 | if (ret < len) { 310 | uint16_t rsr = getSnRX_RSR(s); 311 | ret = rsr - state[s].RX_inc; 312 | state[s].RX_RSR = ret; 313 | //Serial.printf("Sock_RECV, RX_RSR=%d, RX_inc=%d\n", ret, state[s].RX_inc); 314 | } 315 | if (ret == 0) { 316 | // No data available. 317 | uint8_t status = W5100.readSnSR(s); 318 | if ( status == SnSR::LISTEN || status == SnSR::CLOSED || 319 | status == SnSR::CLOSE_WAIT ) { 320 | // The remote end has closed its side of the connection, 321 | // so this is the eof state 322 | ret = 0; 323 | } else { 324 | // The connection is still up, but there's no data waiting to be read 325 | ret = -1; 326 | } 327 | } else { 328 | if (ret > len) ret = len; // more data available than buffer length 329 | uint16_t ptr = state[s].RX_RD; 330 | if (buf) read_data(s, ptr, buf, ret); 331 | ptr += ret; 332 | state[s].RX_RD = ptr; 333 | state[s].RX_RSR -= ret; 334 | uint16_t inc = state[s].RX_inc + ret; 335 | if (inc >= 250 || state[s].RX_RSR == 0) { 336 | state[s].RX_inc = 0; 337 | W5100.writeSnRX_RD(s, ptr); 338 | W5100.execCmdSn(s, Sock_RECV); 339 | //Serial.printf("Sock_RECV cmd, RX_RD=%d, RX_RSR=%d\n", 340 | // state[s].RX_RD, state[s].RX_RSR); 341 | } else { 342 | state[s].RX_inc = inc; 343 | } 344 | } 345 | SPI.endTransaction(); 346 | //Serial.printf("socketRecv, ret=%d\n", ret); 347 | return ret; 348 | } 349 | 350 | uint16_t EthernetClass::socketRecvAvailable(uint8_t s) 351 | { 352 | uint16_t ret = state[s].RX_RSR; 353 | if (ret == 0) { 354 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 355 | uint16_t rsr = getSnRX_RSR(s); 356 | SPI.endTransaction(); 357 | ret = rsr - state[s].RX_inc; 358 | state[s].RX_RSR = ret; 359 | //Serial.printf("sockRecvAvailable s=%d, RX_RSR=%d\n", s, ret); 360 | } 361 | return ret; 362 | } 363 | 364 | // get the first byte in the receive queue (no checking) 365 | // 366 | uint8_t EthernetClass::socketPeek(uint8_t s) 367 | { 368 | uint8_t b; 369 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 370 | uint16_t ptr = state[s].RX_RD; 371 | W5100.read((ptr & W5100.SMASK) + W5100.RBASE(s), &b, 1); 372 | SPI.endTransaction(); 373 | return b; 374 | } 375 | 376 | 377 | 378 | /*****************************************/ 379 | /* Socket Data Transmit Functions */ 380 | /*****************************************/ 381 | 382 | static uint16_t getSnTX_FSR(uint8_t s) 383 | { 384 | uint16_t val, prev; 385 | 386 | prev = W5100.readSnTX_FSR(s); 387 | while (1) { 388 | val = W5100.readSnTX_FSR(s); 389 | if (val == prev) { 390 | state[s].TX_FSR = val; 391 | return val; 392 | } 393 | prev = val; 394 | } 395 | } 396 | 397 | 398 | static void write_data(uint8_t s, uint16_t data_offset, const uint8_t *data, uint16_t len) 399 | { 400 | uint16_t ptr = W5100.readSnTX_WR(s); 401 | ptr += data_offset; 402 | uint16_t offset = ptr & W5100.SMASK; 403 | uint16_t dstAddr = offset + W5100.SBASE(s); 404 | 405 | if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) { 406 | W5100.write(dstAddr, data, len); 407 | } else { 408 | // Wrap around circular buffer 409 | uint16_t size = W5100.SSIZE - offset; 410 | W5100.write(dstAddr, data, size); 411 | W5100.write(W5100.SBASE(s), data + size, len - size); 412 | } 413 | ptr += len; 414 | W5100.writeSnTX_WR(s, ptr); 415 | } 416 | 417 | 418 | /** 419 | * @brief This function used to send the data in TCP mode 420 | * @return 1 for success else 0. 421 | */ 422 | uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len) 423 | { 424 | uint8_t status=0; 425 | uint16_t ret=0; 426 | uint16_t freesize=0; 427 | 428 | if (len > W5100.SSIZE) { 429 | ret = W5100.SSIZE; // check size not to exceed MAX size. 430 | } else { 431 | ret = len; 432 | } 433 | 434 | // if freebuf is available, start. 435 | do { 436 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 437 | freesize = getSnTX_FSR(s); 438 | status = W5100.readSnSR(s); 439 | SPI.endTransaction(); 440 | if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) { 441 | ret = 0; 442 | break; 443 | } 444 | yield(); 445 | } while (freesize < ret); 446 | 447 | // copy data 448 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 449 | write_data(s, 0, (uint8_t *)buf, ret); 450 | W5100.execCmdSn(s, Sock_SEND); 451 | 452 | /* +2008.01 bj */ 453 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { 454 | /* m2008.01 [bj] : reduce code */ 455 | if ( W5100.readSnSR(s) == SnSR::CLOSED ) { 456 | SPI.endTransaction(); 457 | return 0; 458 | } 459 | SPI.endTransaction(); 460 | yield(); 461 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 462 | } 463 | /* +2008.01 bj */ 464 | W5100.writeSnIR(s, SnIR::SEND_OK); 465 | SPI.endTransaction(); 466 | return ret; 467 | } 468 | 469 | uint16_t EthernetClass::socketSendAvailable(uint8_t s) 470 | { 471 | uint8_t status=0; 472 | uint16_t freesize=0; 473 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 474 | freesize = getSnTX_FSR(s); 475 | status = W5100.readSnSR(s); 476 | SPI.endTransaction(); 477 | if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) { 478 | return freesize; 479 | } 480 | return 0; 481 | } 482 | 483 | uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len) 484 | { 485 | //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len); 486 | uint16_t ret =0; 487 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 488 | uint16_t txfree = getSnTX_FSR(s); 489 | if (len > txfree) { 490 | ret = txfree; // check size not to exceed MAX size. 491 | } else { 492 | ret = len; 493 | } 494 | write_data(s, offset, buf, ret); 495 | SPI.endTransaction(); 496 | return ret; 497 | } 498 | 499 | bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port) 500 | { 501 | if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || 502 | ((port == 0x00)) ) { 503 | return false; 504 | } 505 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 506 | W5100.writeSnDIPR(s, addr); 507 | W5100.writeSnDPORT(s, port); 508 | SPI.endTransaction(); 509 | return true; 510 | } 511 | 512 | bool EthernetClass::socketSendUDP(uint8_t s) 513 | { 514 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 515 | W5100.execCmdSn(s, Sock_SEND); 516 | 517 | /* +2008.01 bj */ 518 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { 519 | if (W5100.readSnIR(s) & SnIR::TIMEOUT) { 520 | /* +2008.01 [bj]: clear interrupt */ 521 | W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT)); 522 | SPI.endTransaction(); 523 | //Serial.printf("sendUDP timeout\n"); 524 | return false; 525 | } 526 | SPI.endTransaction(); 527 | yield(); 528 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 529 | } 530 | 531 | /* +2008.01 bj */ 532 | W5100.writeSnIR(s, SnIR::SEND_OK); 533 | SPI.endTransaction(); 534 | 535 | //Serial.printf("sendUDP ok\n"); 536 | /* Sent ok */ 537 | return true; 538 | } 539 | 540 | -------------------------------------------------------------------------------- /src/utility/w5100.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Paul Stoffregen 3 | * Copyright (c) 2010 by Cristian Maglie 4 | * 5 | * This file is free software; you can redistribute it and/or modify 6 | * it under the terms of either the GNU General Public License version 2 7 | * or the GNU Lesser General Public License version 2.1, both as 8 | * published by the Free Software Foundation. 9 | */ 10 | 11 | #include 12 | #include "Ethernet.h" 13 | #include "w5100.h" 14 | 15 | 16 | /***************************************************/ 17 | /** Default SS pin setting **/ 18 | /***************************************************/ 19 | 20 | // If variant.h or other headers specifically define the 21 | // default SS pin for ethernet, use it. 22 | #if defined(PIN_SPI_SS_ETHERNET_LIB) 23 | #define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB 24 | 25 | // MKR boards default to pin 5 for MKR ETH 26 | // Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10 27 | #elif defined(USE_ARDUINO_MKR_PIN_LAYOUT) || defined(ARDUINO_SAMD_MKRZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRVIDOR4000) 28 | #define SS_PIN_DEFAULT 5 29 | 30 | // For boards using AVR, assume shields with SS on pin 10 31 | // will be used. This allows for Arduino Mega (where 32 | // SS is pin 53) and Arduino Leonardo (where SS is pin 17) 33 | // to work by default with Arduino Ethernet Shield R2 & R3. 34 | #elif defined(__AVR__) 35 | #define SS_PIN_DEFAULT 10 36 | 37 | // If variant.h or other headers define these names 38 | // use them if none of the other cases match 39 | #elif defined(PIN_SPI_SS) 40 | #define SS_PIN_DEFAULT PIN_SPI_SS 41 | #elif defined(CORE_SS0_PIN) 42 | #define SS_PIN_DEFAULT CORE_SS0_PIN 43 | 44 | // As a final fallback, use pin 10 45 | #else 46 | #define SS_PIN_DEFAULT 10 47 | #endif 48 | 49 | 50 | 51 | 52 | // W5100 controller instance 53 | uint8_t W5100Class::chip = 0; 54 | uint8_t W5100Class::CH_BASE_MSB; 55 | uint16_t W5100Class::CH_SIZE; 56 | uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT; 57 | #ifdef ETHERNET_LARGE_BUFFERS 58 | uint16_t W5100Class::SSIZE = 2048; 59 | uint16_t W5100Class::SMASK = 0x07FF; 60 | #endif 61 | W5100Class W5100; 62 | 63 | // pointers and bitmasks for optimized SS pin 64 | #if defined(__AVR__) 65 | volatile uint8_t * W5100Class::ss_pin_reg; 66 | uint8_t W5100Class::ss_pin_mask; 67 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) 68 | volatile uint8_t * W5100Class::ss_pin_reg; 69 | #elif defined(__MKL26Z64__) 70 | volatile uint8_t * W5100Class::ss_pin_reg; 71 | uint8_t W5100Class::ss_pin_mask; 72 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) 73 | volatile uint32_t * W5100Class::ss_pin_reg; 74 | uint32_t W5100Class::ss_pin_mask; 75 | #elif defined(__PIC32MX__) 76 | volatile uint32_t * W5100Class::ss_pin_reg; 77 | uint32_t W5100Class::ss_pin_mask; 78 | #elif defined(ARDUINO_ARCH_ESP8266) 79 | volatile uint32_t * W5100Class::ss_pin_reg; 80 | uint32_t W5100Class::ss_pin_mask; 81 | #elif defined(__SAMD21G18A__) 82 | volatile uint32_t * W5100Class::ss_pin_reg; 83 | uint32_t W5100Class::ss_pin_mask; 84 | #endif 85 | 86 | 87 | uint8_t W5100Class::init(void) 88 | { 89 | static bool initialized = false; 90 | uint8_t i; 91 | 92 | if (initialized) return 1; 93 | 94 | // Many Ethernet shields have a CAT811 or similar reset chip 95 | // connected to W5100 or W5200 chips. The W5200 will not work at 96 | // all, and may even drive its MISO pin, until given an active low 97 | // reset pulse! The CAT811 has a 240 ms typical pulse length, and 98 | // a 400 ms worst case maximum pulse length. MAX811 has a worst 99 | // case maximum 560 ms pulse length. This delay is meant to wait 100 | // until the reset pulse is ended. If your hardware has a shorter 101 | // reset time, this can be edited or removed. 102 | delay(560); 103 | //Serial.println("w5100 init"); 104 | 105 | CH_SIZE = 0x0100; // Default except W6100 106 | 107 | SPI.begin(); 108 | initSS(); 109 | resetSS(); 110 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 111 | 112 | // Attempt W5200 detection first, because W5200 does not properly 113 | // reset its SPI state when CS goes high (inactive). Communication 114 | // from detecting the other chips can leave the W5200 in a state 115 | // where it won't recover, unless given a reset pulse. 116 | if (isW5200()) { 117 | CH_BASE_MSB = 0x40; 118 | #ifdef ETHERNET_LARGE_BUFFERS 119 | #if MAX_SOCK_NUM <= 1 120 | SSIZE = 16384; 121 | #elif MAX_SOCK_NUM <= 2 122 | SSIZE = 8192; 123 | #elif MAX_SOCK_NUM <= 4 124 | SSIZE = 4096; 125 | #else 126 | SSIZE = 2048; 127 | #endif 128 | SMASK = SSIZE - 1; 129 | #endif 130 | for (i=0; i> 10); 132 | writeSnTX_SIZE(i, SSIZE >> 10); 133 | } 134 | for (; i<8; i++) { 135 | writeSnRX_SIZE(i, 0); 136 | writeSnTX_SIZE(i, 0); 137 | } 138 | // Try W5500 next. Wiznet finally seems to have implemented 139 | // SPI well with this chip. It appears to be very resilient, 140 | // so try it after the fragile W5200 141 | } else if (isW5500()) { 142 | CH_BASE_MSB = 0x10; 143 | #ifdef ETHERNET_LARGE_BUFFERS 144 | #if MAX_SOCK_NUM <= 1 145 | SSIZE = 16384; 146 | #elif MAX_SOCK_NUM <= 2 147 | SSIZE = 8192; 148 | #elif MAX_SOCK_NUM <= 4 149 | SSIZE = 4096; 150 | #else 151 | SSIZE = 2048; 152 | #endif 153 | SMASK = SSIZE - 1; 154 | for (i=0; i> 10); 156 | writeSnTX_SIZE(i, SSIZE >> 10); 157 | } 158 | for (; i<8; i++) { 159 | writeSnRX_SIZE(i, 0); 160 | writeSnTX_SIZE(i, 0); 161 | } 162 | #endif 163 | // Try W5100S. Brandnew based W5100. 164 | } else if (isW5100S()) { 165 | CH_BASE_MSB = 0x04; 166 | #ifdef ETHERNET_LARGE_BUFFERS 167 | #if MAX_SOCK_NUM <= 1 168 | SSIZE = 8192; 169 | writeTMSR(0x03); 170 | writeRMSR(0x03); 171 | #elif MAX_SOCK_NUM <= 2 172 | SSIZE = 4096; 173 | writeTMSR(0x0A); 174 | writeRMSR(0x0A); 175 | #else 176 | SSIZE = 2048; 177 | writeTMSR(0x55); 178 | writeRMSR(0x55); 179 | #endif 180 | SMASK = SSIZE - 1; 181 | #else 182 | writeTMSR(0x55); 183 | writeRMSR(0x55); 184 | #endif 185 | // Try W5100 last. This simple chip uses fixed 4 byte frames 186 | // for every 8 bit access. Terribly inefficient, but so simple 187 | // it recovers from "hearing" unsuccessful W5100 or W5200 188 | // communication. W5100 is also the only chip without a VERSIONR 189 | // register for identification, so we check this last. 190 | } else if (isW5100()) { 191 | CH_BASE_MSB = 0x04; 192 | #ifdef ETHERNET_LARGE_BUFFERS 193 | #if MAX_SOCK_NUM <= 1 194 | SSIZE = 8192; 195 | writeTMSR(0x03); 196 | writeRMSR(0x03); 197 | #elif MAX_SOCK_NUM <= 2 198 | SSIZE = 4096; 199 | writeTMSR(0x0A); 200 | writeRMSR(0x0A); 201 | #else 202 | SSIZE = 2048; 203 | writeTMSR(0x55); 204 | writeRMSR(0x55); 205 | #endif 206 | SMASK = SSIZE - 1; 207 | #else 208 | writeTMSR(0x55); 209 | writeRMSR(0x55); 210 | #endif 211 | // Try W6100. Brandnew based W5500. 212 | } else if (isW6100()) { 213 | CH_BASE_MSB = 0x60; 214 | CH_SIZE = 0x0400; // W6100 215 | #ifdef ETHERNET_LARGE_BUFFERS 216 | #if MAX_SOCK_NUM <= 1 217 | SSIZE = 16384; 218 | #elif MAX_SOCK_NUM <= 2 219 | SSIZE = 8192; 220 | #elif MAX_SOCK_NUM <= 4 221 | SSIZE = 4096; 222 | #else 223 | SSIZE = 2048; 224 | #endif 225 | SMASK = SSIZE - 1; 226 | for (i=0; i> 10); 228 | writeSnTX_SIZE(i, SSIZE >> 10); 229 | } 230 | for (; i<8; i++) { 231 | writeSnRX_SIZE(i, 0); 232 | writeSnTX_SIZE(i, 0); 233 | } 234 | #endif 235 | // No hardware seems to be present. Or it could be a W5200 236 | // that's heard other SPI communication if its chip select 237 | // pin wasn't high when a SD card or other SPI chip was used. 238 | } else { 239 | //Serial.println("no chip :-("); 240 | chip = 0; 241 | SPI.endTransaction(); 242 | return 0; // no known chip is responding :-( 243 | } 244 | SPI.endTransaction(); 245 | initialized = true; 246 | return 1; // successful init 247 | } 248 | 249 | // Soft reset the Wiznet chip, by writing to its MR register reset bit 250 | uint8_t W5100Class::softReset(void) 251 | { 252 | uint16_t count=0; 253 | 254 | if(chip == 61) { 255 | writeCHPLCKR_W6100(W6100_CHPLCKR_UNLOCK); // Unlock SYSR[CHPL] 256 | count = 0; 257 | do{ // Wait Unlock Complete 258 | if(++count > 20) { // Check retry count 259 | return 0; // Over Limit retry count 260 | } 261 | } while ((readSYSR_W6100() & W6100_SYSR_CHPL_LOCK) ^ W6100_SYSR_CHPL_ULOCK); // Exit Wait Unlock Complete 262 | 263 | writeSYCR0(0x0); // Software Reset 264 | 265 | do{ // Wait Lock Complete 266 | if(++count > 20) { // Check retry count 267 | return 0; // Over Limit retry count 268 | } 269 | 270 | } while ((readSYSR_W6100() & W6100_SYSR_CHPL_LOCK) ^ W6100_SYSR_CHPL_LOCK); // Exit Wait Lock Complete 271 | 272 | return 1; 273 | } else { 274 | count = 0; 275 | 276 | //Serial.println("Wiznet soft reset"); 277 | // write to reset bit 278 | writeMR(0x80); 279 | // then wait for soft reset to complete 280 | do { 281 | uint8_t mr = readMR(); 282 | //Serial.print("mr="); 283 | //Serial.println(mr, HEX); 284 | if (mr == 0 || (mr == 3 && chip == 50)) return 1; 285 | delay(1); 286 | } while (++count < 20); 287 | return 0; 288 | } 289 | } 290 | 291 | uint8_t W5100Class::isW6100(void) 292 | { 293 | chip = 61; 294 | CH_BASE_MSB = 0x80; 295 | 296 | if (!softReset()) return 0; 297 | 298 | // Unlock 299 | writeCHPLCKR_W6100(W6100_CHPLCKR_UNLOCK); 300 | writeNETLCKR_W6100(W6100_NETLCKR_UNLOCK); 301 | writePHYLCKR_W6100(W6100_PHYLCKR_UNLOCK); 302 | 303 | // W6100 CIDR0 304 | // Version 97(dec) 0x61(hex) 305 | int ver = readVERSIONR_W6100(); 306 | 307 | //Serial.print("version = 0x"); 308 | //Serial.println(ver, HEX); 309 | 310 | if (ver != 97) return 0; 311 | //Serial.println("chip is W6100"); 312 | return 1; 313 | } 314 | 315 | uint8_t W5100Class::isW5100(void) 316 | { 317 | chip = 51; 318 | //Serial.println("w5100.cpp: detect W5100 chip"); 319 | if (!softReset()) return 0; 320 | writeMR(0x10); 321 | if (readMR() != 0x10) return 0; 322 | writeMR(0x12); 323 | if (readMR() != 0x12) return 0; 324 | writeMR(0x00); 325 | if (readMR() != 0x00) return 0; 326 | //Serial.println("chip is W5100"); 327 | return 1; 328 | } 329 | 330 | uint8_t W5100Class::isW5100S(void) 331 | { 332 | chip = 50; 333 | //Serial.println("w5100.cpp: detect W5100S chip"); 334 | if (!softReset()) return 0; 335 | writeMR(0x13); 336 | if (readMR() != 0x13) return 0; 337 | writeMR(0x03); 338 | if (readMR() != 0x03) return 0; 339 | int ver = readVERSIONR_W5100S(); 340 | //Serial.print("version="); 341 | //Serial.println(ver); 342 | if (ver != 81) return 0; 343 | //Serial.println("chip is W5100S"); 344 | return 1; 345 | } 346 | 347 | uint8_t W5100Class::isW5200(void) 348 | { 349 | chip = 52; 350 | //Serial.println("w5100.cpp: detect W5200 chip"); 351 | if (!softReset()) return 0; 352 | writeMR(0x08); 353 | if (readMR() != 0x08) return 0; 354 | writeMR(0x10); 355 | if (readMR() != 0x10) return 0; 356 | writeMR(0x00); 357 | if (readMR() != 0x00) return 0; 358 | int ver = readVERSIONR_W5200(); 359 | //Serial.print("version="); 360 | //Serial.println(ver); 361 | if (ver != 3) return 0; 362 | //Serial.println("chip is W5200"); 363 | return 1; 364 | } 365 | 366 | uint8_t W5100Class::isW5500(void) 367 | { 368 | chip = 55; 369 | //Serial.println("w5100.cpp: detect W5500 chip"); 370 | if (!softReset()) return 0; 371 | writeMR(0x08); 372 | if (readMR() != 0x08) return 0; 373 | writeMR(0x10); 374 | if (readMR() != 0x10) return 0; 375 | writeMR(0x00); 376 | if (readMR() != 0x00) return 0; 377 | int ver = readVERSIONR_W5500(); 378 | //Serial.print("version="); 379 | //Serial.println(ver); 380 | if (ver != 4) return 0; 381 | //Serial.println("chip is W5500"); 382 | return 1; 383 | } 384 | 385 | W5100Linkstatus W5100Class::getLinkStatus() 386 | { 387 | uint8_t phystatus; 388 | 389 | if (!init()) return UNKNOWN; 390 | switch (chip) { 391 | case 50: 392 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 393 | phystatus = readPHYCFGR_W5100S(); 394 | SPI.endTransaction(); 395 | if (phystatus & 0x01) return LINK_ON; 396 | return LINK_OFF; 397 | case 52: 398 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 399 | phystatus = readPSTATUS_W5200(); 400 | SPI.endTransaction(); 401 | if (phystatus & 0x20) return LINK_ON; 402 | return LINK_OFF; 403 | case 55: 404 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 405 | phystatus = readPHYCFGR_W5500(); 406 | SPI.endTransaction(); 407 | if (phystatus & 0x01) return LINK_ON; 408 | return LINK_OFF; 409 | case 61: 410 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 411 | phystatus = readPHYCFGR_W6100(); 412 | SPI.endTransaction(); 413 | if (phystatus & 0x01) return LINK_ON; 414 | return LINK_OFF; 415 | default: 416 | return UNKNOWN; 417 | } 418 | } 419 | 420 | uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len) 421 | { 422 | uint8_t cmd[8]; 423 | 424 | if (chip == 51 || chip == 50) { 425 | for (uint16_t i=0; i> 8); 429 | SPI.transfer(addr & 0xFF); 430 | addr++; 431 | SPI.transfer(buf[i]); 432 | resetSS(); 433 | } 434 | } else if (chip == 52) { 435 | setSS(); 436 | cmd[0] = addr >> 8; 437 | cmd[1] = addr & 0xFF; 438 | cmd[2] = ((len >> 8) & 0x7F) | 0x80; 439 | cmd[3] = len & 0xFF; 440 | SPI.transfer(cmd, 4); 441 | #ifdef SPI_HAS_TRANSFER_BUF 442 | SPI.transfer(buf, NULL, len); 443 | #else 444 | // TODO: copy 8 bytes at a time to cmd[] and block transfer 445 | for (uint16_t i=0; i < len; i++) { 446 | SPI.transfer(buf[i]); 447 | } 448 | #endif 449 | resetSS(); 450 | } else if (chip == 61) { // chip == 61 451 | setSS(); 452 | 453 | if (addr < CH_BASE()) { 454 | // common registers 455 | 456 | cmd[0] = (addr>>8) & 0x7F; 457 | cmd[1] = addr & 0xFF; 458 | cmd[2] = W6100_SPI_FRAME_CTL_BSB_BLK(0) 459 | | W6100_SPI_FRAME_CTL_BSB_COMM 460 | | W6100_SPI_FRAME_CTL_WD 461 | | W6100_SPI_FRAME_CTL_OPM_VDM 462 | ; 463 | } else if (addr < W6100_TX_BASE_ADDR) { 464 | // socket registers 465 | 466 | cmd[0] = (addr>>8) & 0x3; 467 | cmd[1] = addr & 0xFF; 468 | cmd[2] = W6100_SPI_FRAME_CTL_BSB_BLK((addr>>10)&0x7) 469 | | W6100_SPI_FRAME_CTL_BSB_SOCK 470 | | W6100_SPI_FRAME_CTL_WD 471 | | W6100_SPI_FRAME_CTL_OPM_VDM 472 | ; 473 | } else if (addr < W6100_RX_BASE_ADDR) { 474 | // transmit buffers 475 | 476 | cmd[0] = addr>>8; 477 | cmd[1] = addr & 0xFF; 478 | 479 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 480 | cmd[2] = 0; // 16K buffers 481 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 482 | cmd[2] = ((addr >> 8) & 0x20); // 8K buffers 483 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 484 | cmd[2] = ((addr >> 7) & 0x60); // 4K buffers 485 | #else 486 | cmd[2] = ((addr >> 6) & 0xE0); // 2K buffers 487 | #endif 488 | 489 | cmd[2] |= W6100_SPI_FRAME_CTL_BSB_BLK(0) 490 | | W6100_SPI_FRAME_CTL_BSB_TXBF 491 | | W6100_SPI_FRAME_CTL_WD 492 | | W6100_SPI_FRAME_CTL_OPM_VDM 493 | ; 494 | } else { 495 | // receive buffers 496 | 497 | cmd[0] = addr>>8; 498 | cmd[1] = addr & 0xFF; 499 | 500 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 501 | cmd[2] = 0; // 16K buffers 502 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 503 | cmd[2] = ((addr >> 8) & 0x20); // 8K buffers 504 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 505 | cmd[2] = ((addr >> 7) & 0x60); // 4K buffers 506 | #else 507 | cmd[2] = ((addr >> 6) & 0xE0); // 2K buffers 508 | #endif 509 | 510 | cmd[2] |= W6100_SPI_FRAME_CTL_BSB_BLK(0) 511 | | W6100_SPI_FRAME_CTL_BSB_RXBF 512 | | W6100_SPI_FRAME_CTL_WD 513 | | W6100_SPI_FRAME_CTL_OPM_VDM 514 | ; 515 | } 516 | if (len <= 5) { 517 | for (uint8_t i=0; i < len; i++) { 518 | cmd[i + 3] = buf[i]; 519 | } 520 | SPI.transfer(cmd, len + 3); 521 | } else { 522 | SPI.transfer(cmd, 3); 523 | #ifdef SPI_HAS_TRANSFER_BUF 524 | SPI.transfer(buf, NULL, len); 525 | #else 526 | // TODO: copy 8 bytes at a time to cmd[] and block transfer 527 | for (uint16_t i=0; i < len; i++) { 528 | SPI.transfer(buf[i]); 529 | } 530 | #endif 531 | } 532 | resetSS(); 533 | } else { // chip == 55 534 | setSS(); 535 | if (addr < 0x100) { 536 | // common registers 00nn 537 | cmd[0] = 0; 538 | cmd[1] = addr & 0xFF; 539 | cmd[2] = 0x04; 540 | } else if (addr < 0x8000) { 541 | // socket registers 10nn, 11nn, 12nn, 13nn, etc 542 | cmd[0] = 0; 543 | cmd[1] = addr & 0xFF; 544 | cmd[2] = ((addr >> 3) & 0xE0) | 0x0C; 545 | } else if (addr < 0xC000) { 546 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc 547 | // 10## #nnn nnnn nnnn 548 | cmd[0] = addr >> 8; 549 | cmd[1] = addr & 0xFF; 550 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 551 | cmd[2] = 0x14; // 16K buffers 552 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 553 | cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers 554 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 555 | cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers 556 | #else 557 | cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers 558 | #endif 559 | } else { 560 | // receive buffers 561 | cmd[0] = addr >> 8; 562 | cmd[1] = addr & 0xFF; 563 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 564 | cmd[2] = 0x1C; // 16K buffers 565 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 566 | cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers 567 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 568 | cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers 569 | #else 570 | cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers 571 | #endif 572 | } 573 | if (len <= 5) { 574 | for (uint8_t i=0; i < len; i++) { 575 | cmd[i + 3] = buf[i]; 576 | } 577 | SPI.transfer(cmd, len + 3); 578 | } else { 579 | SPI.transfer(cmd, 3); 580 | #ifdef SPI_HAS_TRANSFER_BUF 581 | SPI.transfer(buf, NULL, len); 582 | #else 583 | // TODO: copy 8 bytes at a time to cmd[] and block transfer 584 | for (uint16_t i=0; i < len; i++) { 585 | SPI.transfer(buf[i]); 586 | } 587 | #endif 588 | } 589 | resetSS(); 590 | } 591 | return len; 592 | } 593 | 594 | uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len) 595 | { 596 | uint8_t cmd[4]; 597 | 598 | if (chip == 51 || chip == 50) { 599 | for (uint16_t i=0; i < len; i++) { 600 | setSS(); 601 | #if 1 602 | SPI.transfer(0x0F); 603 | SPI.transfer(addr >> 8); 604 | SPI.transfer(addr & 0xFF); 605 | addr++; 606 | buf[i] = SPI.transfer(0); 607 | #else 608 | cmd[0] = 0x0F; 609 | cmd[1] = addr >> 8; 610 | cmd[2] = addr & 0xFF; 611 | cmd[3] = 0; 612 | SPI.transfer(cmd, 4); // TODO: why doesn't this work? 613 | buf[i] = cmd[3]; 614 | addr++; 615 | #endif 616 | resetSS(); 617 | } 618 | } else if (chip == 52) { 619 | setSS(); 620 | cmd[0] = addr >> 8; 621 | cmd[1] = addr & 0xFF; 622 | cmd[2] = (len >> 8) & 0x7F; 623 | cmd[3] = len & 0xFF; 624 | SPI.transfer(cmd, 4); 625 | memset(buf, 0, len); 626 | SPI.transfer(buf, len); 627 | resetSS(); 628 | } else if (chip == 61) { // chip == 61 629 | setSS(); 630 | 631 | if (addr < CH_BASE()) { 632 | // common registers 633 | 634 | cmd[0] = (addr>>8) & 0x7F; 635 | cmd[1] = addr & 0xFF; 636 | cmd[2] = W6100_SPI_FRAME_CTL_BSB_BLK(0) 637 | | W6100_SPI_FRAME_CTL_BSB_COMM 638 | | W6100_SPI_FRAME_CTL_RD 639 | | W6100_SPI_FRAME_CTL_OPM_VDM 640 | ; 641 | } else if (addr < W6100_TX_BASE_ADDR) { 642 | // socket registers 643 | 644 | cmd[0] = (addr>>8) & 0x3; 645 | cmd[1] = addr & 0xFF; 646 | cmd[2] = W6100_SPI_FRAME_CTL_BSB_BLK((addr>>10)&0x7) 647 | | W6100_SPI_FRAME_CTL_BSB_SOCK 648 | | W6100_SPI_FRAME_CTL_RD 649 | | W6100_SPI_FRAME_CTL_OPM_VDM 650 | ; 651 | } else if (addr < W6100_RX_BASE_ADDR) { 652 | // transmit buffers 653 | 654 | cmd[0] = addr>>8; 655 | cmd[1] = addr & 0xFF; 656 | 657 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 658 | cmd[2] = 0; // 16K buffers 659 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 660 | cmd[2] = ((addr >> 8) & 0x20); // 8K buffers 661 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 662 | cmd[2] = ((addr >> 7) & 0x60); // 4K buffers 663 | #else 664 | cmd[2] = ((addr >> 6) & 0xE0); // 2K buffers 665 | #endif 666 | 667 | cmd[2] |= W6100_SPI_FRAME_CTL_BSB_BLK(0) 668 | | W6100_SPI_FRAME_CTL_BSB_TXBF 669 | | W6100_SPI_FRAME_CTL_RD 670 | | W6100_SPI_FRAME_CTL_OPM_VDM 671 | ; 672 | } else { 673 | // receive buffers 674 | 675 | cmd[0] = addr>>8; 676 | cmd[1] = addr & 0xFF; 677 | 678 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 679 | cmd[2] = 0; // 16K buffers 680 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 681 | cmd[2] = ((addr >> 8) & 0x20); // 8K buffers 682 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 683 | cmd[2] = ((addr >> 7) & 0x60); // 4K buffers 684 | #else 685 | cmd[2] = ((addr >> 6) & 0xE0); // 2K buffers 686 | #endif 687 | 688 | cmd[2] |= W6100_SPI_FRAME_CTL_BSB_BLK(0) 689 | | W6100_SPI_FRAME_CTL_BSB_RXBF 690 | | W6100_SPI_FRAME_CTL_RD 691 | | W6100_SPI_FRAME_CTL_OPM_VDM 692 | ; 693 | } 694 | SPI.transfer(cmd, 3); 695 | memset(buf, 0, len); 696 | SPI.transfer(buf, len); 697 | resetSS(); 698 | } else { // chip == 55 699 | setSS(); 700 | if (addr < 0x100) { 701 | // common registers 00nn 702 | cmd[0] = 0; 703 | cmd[1] = addr & 0xFF; 704 | cmd[2] = 0x00; 705 | } else if (addr < 0x8000) { 706 | // socket registers 10nn, 11nn, 12nn, 13nn, etc 707 | cmd[0] = 0; 708 | cmd[1] = addr & 0xFF; 709 | cmd[2] = ((addr >> 3) & 0xE0) | 0x08; 710 | } else if (addr < 0xC000) { 711 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc 712 | // 10## #nnn nnnn nnnn 713 | cmd[0] = addr >> 8; 714 | cmd[1] = addr & 0xFF; 715 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 716 | cmd[2] = 0x10; // 16K buffers 717 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 718 | cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers 719 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 720 | cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers 721 | #else 722 | cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers 723 | #endif 724 | } else { 725 | // receive buffers 726 | cmd[0] = addr >> 8; 727 | cmd[1] = addr & 0xFF; 728 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 729 | cmd[2] = 0x18; // 16K buffers 730 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 731 | cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers 732 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 733 | cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers 734 | #else 735 | cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers 736 | #endif 737 | } 738 | SPI.transfer(cmd, 3); 739 | memset(buf, 0, len); 740 | SPI.transfer(buf, len); 741 | resetSS(); 742 | } 743 | return len; 744 | } 745 | 746 | void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) 747 | { 748 | // Send command to socket 749 | writeSnCR(s, _cmd); 750 | // Wait for command to complete 751 | while (readSnCR(s)) ; 752 | } 753 | -------------------------------------------------------------------------------- /src/utility/w5100.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Paul Stoffregen 3 | * Copyright (c) 2010 by Cristian Maglie 4 | * 5 | * This file is free software; you can redistribute it and/or modify 6 | * it under the terms of either the GNU General Public License version 2 7 | * or the GNU Lesser General Public License version 2.1, both as 8 | * published by the Free Software Foundation. 9 | */ 10 | 11 | // w5100.h contains private W5x00 hardware "driver" level definitions 12 | // which are not meant to be exposed to other libraries or Arduino users 13 | 14 | #ifndef W5100_H_INCLUDED 15 | #define W5100_H_INCLUDED 16 | 17 | #include 18 | #include 19 | 20 | // Safe for all chips 21 | #define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0) 22 | 23 | // Safe for W5200 and W5500, but too fast for W5100 24 | // Uncomment this if you know you'll never need W5100 support. 25 | // Higher SPI clock only results in faster transfer to hosts on a LAN 26 | // or with very low packet latency. With ordinary internet latency, 27 | // the TCP window size & packet loss determine your overall speed. 28 | //#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0) 29 | 30 | 31 | // Require Ethernet.h, because we need MAX_SOCK_NUM 32 | #ifndef ethernet_h_ 33 | #error "Ethernet.h must be included before w5100.h" 34 | #endif 35 | 36 | 37 | // Arduino 101's SPI can not run faster than 8 MHz. 38 | #if defined(ARDUINO_ARCH_ARC32) 39 | #undef SPI_ETHERNET_SETTINGS 40 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) 41 | #endif 42 | 43 | // Arduino Zero can't use W5100-based shields faster than 8 MHz 44 | // https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848 45 | // W5500 does seem to work at 12 MHz. Delete this if only using W5500 46 | #if defined(__SAMD21G18A__) 47 | #undef SPI_ETHERNET_SETTINGS 48 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) 49 | #endif 50 | 51 | 52 | typedef uint8_t SOCKET; 53 | 54 | class SnMR { 55 | public: 56 | static const uint8_t CLOSE = 0x00; 57 | static const uint8_t TCP = 0x21; 58 | static const uint8_t UDP = 0x02; 59 | static const uint8_t IPRAW = 0x03; 60 | static const uint8_t MACRAW = 0x04; 61 | static const uint8_t PPPOE = 0x05; 62 | static const uint8_t ND = 0x20; 63 | static const uint8_t MULTI = 0x80; 64 | }; 65 | 66 | enum SockCMD { 67 | Sock_OPEN = 0x01, 68 | Sock_LISTEN = 0x02, 69 | Sock_CONNECT = 0x04, 70 | Sock_DISCON = 0x08, 71 | Sock_CLOSE = 0x10, 72 | Sock_SEND = 0x20, 73 | Sock_SEND_MAC = 0x21, 74 | Sock_SEND_KEEP = 0x22, 75 | Sock_RECV = 0x40 76 | }; 77 | 78 | class SnIR { 79 | public: 80 | static const uint8_t SEND_OK = 0x10; 81 | static const uint8_t TIMEOUT = 0x08; 82 | static const uint8_t RECV = 0x04; 83 | static const uint8_t DISCON = 0x02; 84 | static const uint8_t CON = 0x01; 85 | }; 86 | 87 | class SnSR { 88 | public: 89 | static const uint8_t CLOSED = 0x00; 90 | static const uint8_t INIT = 0x13; 91 | static const uint8_t LISTEN = 0x14; 92 | static const uint8_t SYNSENT = 0x15; 93 | static const uint8_t SYNRECV = 0x16; 94 | static const uint8_t ESTABLISHED = 0x17; 95 | static const uint8_t FIN_WAIT = 0x18; 96 | static const uint8_t CLOSING = 0x1A; 97 | static const uint8_t TIME_WAIT = 0x1B; 98 | static const uint8_t CLOSE_WAIT = 0x1C; 99 | static const uint8_t LAST_ACK = 0x1D; 100 | static const uint8_t UDP = 0x22; 101 | static const uint8_t IPRAW = 0x32; 102 | static const uint8_t MACRAW = 0x42; 103 | static const uint8_t PPPOE = 0x5F; 104 | }; 105 | 106 | class IPPROTO { 107 | public: 108 | static const uint8_t IP = 0; 109 | static const uint8_t ICMP = 1; 110 | static const uint8_t IGMP = 2; 111 | static const uint8_t GGP = 3; 112 | static const uint8_t TCP = 6; 113 | static const uint8_t PUP = 12; 114 | static const uint8_t UDP = 17; 115 | static const uint8_t IDP = 22; 116 | static const uint8_t ND = 77; 117 | static const uint8_t RAW = 255; 118 | }; 119 | 120 | enum W5100Linkstatus { 121 | UNKNOWN, 122 | LINK_ON, 123 | LINK_OFF 124 | }; 125 | 126 | class W5100Class { 127 | 128 | public: 129 | static uint8_t init(void); 130 | 131 | inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); } 132 | inline void getGatewayIp(uint8_t * addr) { readGAR(addr); } 133 | 134 | inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); } 135 | inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); } 136 | 137 | inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); } 138 | inline void getMACAddress(uint8_t * addr) { readSHAR(addr); } 139 | 140 | inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); } 141 | inline void getIPAddress(uint8_t * addr) { readSIPR(addr); } 142 | 143 | inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); } 144 | inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); } 145 | 146 | static void execCmdSn(SOCKET s, SockCMD _cmd); 147 | 148 | 149 | // W5100 Registers 150 | // --------------- 151 | //private: 152 | public: 153 | static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len); 154 | static uint8_t write(uint16_t addr, uint8_t data) { 155 | return write(addr, &data, 1); 156 | } 157 | static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len); 158 | static uint8_t read(uint16_t addr) { 159 | uint8_t data; 160 | read(addr, &data, 1); 161 | return data; 162 | } 163 | 164 | #define W6100_SPI_FRAME_CTL_BSB_BLK(sn) ((sn)<<5) 165 | 166 | #define W6100_SPI_FRAME_CTL_BSB_COMM (0<<3) 167 | #define W6100_SPI_FRAME_CTL_BSB_SOCK (1<<3) 168 | #define W6100_SPI_FRAME_CTL_BSB_TXBF (2<<3) 169 | #define W6100_SPI_FRAME_CTL_BSB_RXBF (3<<3) 170 | 171 | #define W6100_SPI_FRAME_CTL_RD (0<<2) 172 | #define W6100_SPI_FRAME_CTL_WD (1<<2) 173 | 174 | #define W6100_SPI_FRAME_CTL_OPM_VDM (0<<0) 175 | #define W6100_SPI_FRAME_CTL_OPM_FDM1 (1<<0) 176 | #define W6100_SPI_FRAME_CTL_OPM_FDM2 (2<<0) 177 | #define W6100_SPI_FRAME_CTL_OPM_FDM4 (3<<0) 178 | 179 | #define W6100_COMMON_BASE_ADDR (0x0000) 180 | #define W6100_SOCKET_BASE_ADDR (0x6000) 181 | #define W6100_TX_BASE_ADDR (0x8000) 182 | #define W6100_RX_BASE_ADDR (0xC000) 183 | #define W6100_SOCKET_NUM(_s) ((_s)<<10)) 184 | 185 | #define W6100_CHPLCKR_UNLOCK 0xCE 186 | #define W6100_NETLCKR_UNLOCK 0x3A 187 | #define W6100_PHYLCKR_UNLOCK 0x53 188 | 189 | #define W6100_SYSR_CHPL_LOCK (1<<7) 190 | #define W6100_SYSR_CHPL_ULOCK (0<<7) 191 | 192 | #define W6100_UDP_HEADER_IPV (1<<7) 193 | #define W6100_UDP_HEADER_IPV4 (0<<7) 194 | #define W6100_UDP_HEADER_IPV6 (1<<7) 195 | #define W6100_UDP_HEADER_ALL (1<<6) 196 | #define W6100_UDP_HEADER_MUL (1<<5) 197 | #define W6100_UDP_HEADER_GUA (0<<3) 198 | #define W6100_UDP_HEADER_LLA (1<<3) 199 | 200 | #define __GP_REGISTER8(name, address, adrss_w6100) \ 201 | static inline void write##name(uint8_t _data) { \ 202 | if(chip == 61) { \ 203 | write(adrss_w6100, _data); \ 204 | } else { \ 205 | write(address, _data); \ 206 | } \ 207 | } \ 208 | static inline uint8_t read##name() { \ 209 | if(chip == 61) { \ 210 | return read(adrss_w6100); \ 211 | } else { \ 212 | return read(address); \ 213 | } \ 214 | } \ 215 | 216 | #define __GP_REGISTER16(name, address, adrss_w6100) \ 217 | static void write##name(uint16_t _data) { \ 218 | uint8_t buf[2]; \ 219 | buf[0] = _data >> 8; \ 220 | buf[1] = _data & 0xFF; \ 221 | if(chip == 61) { \ 222 | write(adrss_w6100, buf, 2); \ 223 | } else { \ 224 | write(address, buf, 2); \ 225 | } \ 226 | } \ 227 | static uint16_t read##name() { \ 228 | uint8_t buf[2]; \ 229 | if(chip == 61) { \ 230 | read(adrss_w6100, buf, 2); \ 231 | } else { \ 232 | read(address, buf, 2); \ 233 | } \ 234 | return (buf[0] << 8) | buf[1]; \ 235 | } 236 | 237 | #define __GP_REGISTER_N(name, address, adrss_w6100, size) \ 238 | static uint16_t write##name(const uint8_t *_buff) { \ 239 | if(chip == 61) { \ 240 | return write(adrss_w6100, _buff, size); \ 241 | } else { \ 242 | return write(address, _buff, size); \ 243 | } \ 244 | } \ 245 | static uint16_t read##name(uint8_t *_buff) { \ 246 | if(chip == 61) { \ 247 | return read(adrss_w6100, _buff, size); \ 248 | } else { \ 249 | return read(address, _buff, size); \ 250 | } \ 251 | } 252 | static W5100Linkstatus getLinkStatus(); 253 | 254 | public: 255 | __GP_REGISTER8 (MR, 0x0000, 0x4000); // Mode 256 | __GP_REGISTER_N(GAR, 0x0001, 0x4130, 4); // Gateway IP address 257 | __GP_REGISTER_N(SUBR, 0x0005, 0x4134, 4); // Subnet mask address 258 | __GP_REGISTER_N(SHAR, 0x0009, 0x4120, 6); // Source MAC address 259 | __GP_REGISTER_N(SIPR, 0x000F, 0x4138, 4); // Source IP address 260 | __GP_REGISTER8 (IR, 0x0015, 0x2100); // Interrupt 261 | __GP_REGISTER8 (IMR, 0x0016, 0x2104); // Interrupt Mask 262 | __GP_REGISTER16(RTR, 0x0017, 0x2101); // Timeout address 263 | __GP_REGISTER8 (RCR, 0x0019, 0x4200); // Retry count 264 | __GP_REGISTER8 (RMSR, 0x001A, 0x0000); // Receive memory size (W5100 only) 265 | __GP_REGISTER8 (TMSR, 0x001B, 0x0000); // Transmit memory size (W5100 only) 266 | __GP_REGISTER8 (PATR, 0x001C, 0x0000); // Authentication type address in PPPoE mode 267 | __GP_REGISTER8 (PTIMER, 0x0028, 0x4100); // PPP LCP Request Timer 268 | __GP_REGISTER8 (PMAGIC, 0x0029, 0x4104); // PPP LCP Magic Number 269 | __GP_REGISTER_N(UIPR, 0x002A, 0x0000, 4); // Unreachable IP address in UDP mode (W5100 only) 270 | __GP_REGISTER16(UPORT, 0x002E, 0x0000); // Unreachable Port address in UDP mode (W5100 only) 271 | __GP_REGISTER8 (VERSIONR_W5200, 0x001F, 0x0000); // Chip Version Register (W5200 only) 272 | __GP_REGISTER8 (VERSIONR_W5500, 0x0039, 0x0000); // Chip Version Register (W5500 only) 273 | __GP_REGISTER8 (VERSIONR_W5100S, 0x0080, 0x0000); // Chip Version Register (W5100S only) 274 | __GP_REGISTER8 (PSTATUS_W5200, 0x0035, 0x0000); // PHY Status 275 | __GP_REGISTER8 (PHYCFGR_W5500, 0x002E, 0x0000); // PHY Configuration register, default: 10111xxx 276 | __GP_REGISTER8 (PHYCFGR_W5100S, 0x003C, 0x0000); // PHY Status 277 | 278 | // For W6100 279 | __GP_REGISTER8 (SYCR0, 0x0000, 0x2004); // System Command Register 280 | __GP_REGISTER8 (SYSR_W6100, 0x0000, 0x2000); // System Status Register 281 | __GP_REGISTER8 (NETLCKR_W6100, 0x0000, 0x41F5); // Network Lock Register 282 | __GP_REGISTER8 (CHPLCKR_W6100, 0x0000, 0x41F4); // Chip Lock Register 283 | __GP_REGISTER8 (PHYLCKR_W6100, 0x0000, 0x41F6); // PHY Lock Register 284 | __GP_REGISTER8 (PHYCFGR_W6100, 0x0000, 0x3000); // PHY Status 285 | __GP_REGISTER8 (VERSIONR_W6100, 0x0000, 0x0000); // Chip Version Register 286 | __GP_REGISTER8 (CVERSIONR_W6100, 0x0000, 0x0002); // Chip Version Register 287 | 288 | #undef __GP_REGISTER8 289 | #undef __GP_REGISTER16 290 | #undef __GP_REGISTER_N 291 | 292 | // W5100 Socket registers 293 | // ---------------------- 294 | private: 295 | static uint16_t CH_BASE(void) { 296 | //if (chip == 55) return 0x1000; 297 | //if (chip == 52) return 0x4000; 298 | //return 0x0400; 299 | 300 | // 5500 : 0x10 << 8 = 0x1000 301 | // 6100 : 0x60 << 8 = 0x6000 (1000 0000 0000 0000) 302 | 303 | return CH_BASE_MSB << 8; 304 | } 305 | 306 | static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR 307 | static uint16_t CH_SIZE; 308 | 309 | static inline uint8_t readSn(SOCKET s, uint16_t addr) { 310 | return read(CH_BASE() + s * CH_SIZE + addr); 311 | } 312 | static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) { 313 | return write(CH_BASE() + s * CH_SIZE + addr, data); 314 | } 315 | static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { 316 | return read(CH_BASE() + s * CH_SIZE + addr, buf, len); 317 | } 318 | static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { 319 | return write(CH_BASE() + s * CH_SIZE + addr, buf, len); 320 | } 321 | 322 | #define __SOCKET_REGISTER8(name, address, adrss_w6100) \ 323 | static inline void write##name(SOCKET _s, uint8_t _data) { \ 324 | if(chip == 61) { \ 325 | writeSn(_s, adrss_w6100, _data); \ 326 | } else { \ 327 | writeSn(_s, address, _data); \ 328 | } \ 329 | } \ 330 | static inline uint8_t read##name(SOCKET _s) { \ 331 | if(chip == 61) { \ 332 | return readSn(_s, adrss_w6100); \ 333 | } else { \ 334 | return readSn(_s, address); \ 335 | } \ 336 | } 337 | 338 | #define __SOCKET_REGISTER16(name, address, adrss_w6100) \ 339 | static void write##name(SOCKET _s, uint16_t _data) { \ 340 | uint8_t buf[2]; \ 341 | buf[0] = _data >> 8; \ 342 | buf[1] = _data & 0xFF; \ 343 | if(chip == 61) { \ 344 | writeSn(_s, adrss_w6100, buf, 2);\ 345 | } else { \ 346 | writeSn(_s, address, buf, 2); \ 347 | } \ 348 | } \ 349 | static uint16_t read##name(SOCKET _s) { \ 350 | uint8_t buf[2]; \ 351 | if(chip == 61) { \ 352 | readSn(_s, adrss_w6100, buf, 2); \ 353 | } else { \ 354 | readSn(_s, address, buf, 2); \ 355 | } \ 356 | return (buf[0] << 8) | buf[1]; \ 357 | } 358 | 359 | #define __SOCKET_REGISTER_N(name, address, adrss_w6100, size)\ 360 | static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \ 361 | if(chip == 61) { \ 362 | return writeSn(_s, adrss_w6100, _buff, size); \ 363 | } else { \ 364 | return writeSn(_s, address, _buff, size); \ 365 | } \ 366 | } \ 367 | static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \ 368 | if(chip == 61) { \ 369 | return readSn(_s, adrss_w6100, _buff, size); \ 370 | } else { \ 371 | return readSn(_s, address, _buff, size); \ 372 | } \ 373 | } 374 | 375 | public: 376 | __SOCKET_REGISTER8(SnMR, 0x0000, 0x0000) // Mode 377 | __SOCKET_REGISTER8(SnCR, 0x0001, 0x0010) // Command 378 | __SOCKET_REGISTER8(SnIR, 0x0002, 0x0020) // Interrupt 379 | __SOCKET_REGISTER8(SnSR, 0x0003, 0x0030) // Status 380 | __SOCKET_REGISTER16(SnPORT, 0x0004, 0x0114) // Source Port 381 | __SOCKET_REGISTER_N(SnDHAR, 0x0006, 0x0118, 6) // Destination Hardw Addr 382 | __SOCKET_REGISTER_N(SnDIPR, 0x000C, 0x0120, 4) // Destination IP Addr 383 | __SOCKET_REGISTER16(SnDPORT, 0x0010, 0x0140) // Destination Port 384 | __SOCKET_REGISTER16(SnMSSR, 0x0012, 0x0110) // Max Segment Size 385 | __SOCKET_REGISTER8(SnPROTO, 0x0014, 0x0000) // Protocol in IP RAW Mode 386 | __SOCKET_REGISTER8(SnTOS, 0x0015, 0x0104) // IP TOS 387 | __SOCKET_REGISTER8(SnTTL, 0x0016, 0x0108) // IP TTL 388 | __SOCKET_REGISTER8(SnRX_SIZE, 0x001E, 0x0220) // RX Memory Size (W5200 only) 389 | __SOCKET_REGISTER8(SnTX_SIZE, 0x001F, 0x0200) // TX Memory Size (W5200 only) 390 | __SOCKET_REGISTER16(SnTX_FSR, 0x0020, 0x0204) // TX Free Size 391 | __SOCKET_REGISTER16(SnTX_RD, 0x0022, 0x0208) // TX Read Pointer 392 | __SOCKET_REGISTER16(SnTX_WR, 0x0024, 0x020C) // TX Write Pointer 393 | __SOCKET_REGISTER16(SnRX_RSR, 0x0026, 0x0224) // RX Free Size 394 | __SOCKET_REGISTER16(SnRX_RD, 0x0028, 0x0228) // RX Read Pointer 395 | __SOCKET_REGISTER16(SnRX_WR, 0x002A, 0x022C) // RX Write Pointer (supported?) 396 | 397 | #undef __SOCKET_REGISTER8 398 | #undef __SOCKET_REGISTER16 399 | #undef __SOCKET_REGISTER_N 400 | 401 | 402 | private: 403 | static uint8_t chip; 404 | static uint8_t ss_pin; 405 | static uint8_t softReset(void); 406 | static uint8_t isW5100(void); 407 | static uint8_t isW5100S(void); 408 | static uint8_t isW5200(void); 409 | static uint8_t isW5500(void); 410 | static uint8_t isW6100(void); 411 | 412 | public: 413 | static uint8_t getChip(void) { return chip; } 414 | #ifdef ETHERNET_LARGE_BUFFERS 415 | static uint16_t SSIZE; 416 | static uint16_t SMASK; 417 | #else 418 | static const uint16_t SSIZE = 2048; 419 | static const uint16_t SMASK = 0x07FF; 420 | #endif 421 | static uint16_t SBASE(uint8_t socknum) { 422 | if (chip == 51 || chip == 50) { 423 | return socknum * SSIZE + 0x4000; 424 | } else if (chip == 61) { 425 | return socknum * SSIZE + W6100_TX_BASE_ADDR; 426 | } else { 427 | return socknum * SSIZE + 0x8000; 428 | } 429 | } 430 | static uint16_t RBASE(uint8_t socknum) { 431 | if (chip == 51 || chip == 50) { 432 | return socknum * SSIZE + 0x6000; 433 | } else if (chip == 61) { 434 | return socknum * SSIZE + W6100_RX_BASE_ADDR; 435 | } else { 436 | return socknum * SSIZE + 0xC000; 437 | } 438 | } 439 | 440 | static bool hasOffsetAddressMapping(void) { 441 | if (chip == 55 || chip == 61) return true; 442 | return false; 443 | } 444 | static void setSS(uint8_t pin) { ss_pin = pin; } 445 | 446 | private: 447 | #if defined(__AVR__) 448 | static volatile uint8_t *ss_pin_reg; 449 | static uint8_t ss_pin_mask; 450 | inline static void initSS() { 451 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); 452 | ss_pin_mask = digitalPinToBitMask(ss_pin); 453 | pinMode(ss_pin, OUTPUT); 454 | } 455 | inline static void setSS() { 456 | *(ss_pin_reg) &= ~ss_pin_mask; 457 | } 458 | inline static void resetSS() { 459 | *(ss_pin_reg) |= ss_pin_mask; 460 | } 461 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) 462 | static volatile uint8_t *ss_pin_reg; 463 | inline static void initSS() { 464 | ss_pin_reg = portOutputRegister(ss_pin); 465 | pinMode(ss_pin, OUTPUT); 466 | } 467 | inline static void setSS() { 468 | *(ss_pin_reg+256) = 1; 469 | } 470 | inline static void resetSS() { 471 | *(ss_pin_reg+128) = 1; 472 | } 473 | #elif defined(__MKL26Z64__) 474 | static volatile uint8_t *ss_pin_reg; 475 | static uint8_t ss_pin_mask; 476 | inline static void initSS() { 477 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); 478 | ss_pin_mask = digitalPinToBitMask(ss_pin); 479 | pinMode(ss_pin, OUTPUT); 480 | } 481 | inline static void setSS() { 482 | *(ss_pin_reg+8) = ss_pin_mask; 483 | } 484 | inline static void resetSS() { 485 | *(ss_pin_reg+4) = ss_pin_mask; 486 | } 487 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) 488 | static volatile uint32_t *ss_pin_reg; 489 | static uint32_t ss_pin_mask; 490 | inline static void initSS() { 491 | ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER); 492 | ss_pin_mask = digitalPinToBitMask(ss_pin); 493 | pinMode(ss_pin, OUTPUT); 494 | } 495 | inline static void setSS() { 496 | *(ss_pin_reg+13) = ss_pin_mask; 497 | } 498 | inline static void resetSS() { 499 | *(ss_pin_reg+12) = ss_pin_mask; 500 | } 501 | #elif defined(__PIC32MX__) 502 | static volatile uint32_t *ss_pin_reg; 503 | static uint32_t ss_pin_mask; 504 | inline static void initSS() { 505 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); 506 | ss_pin_mask = digitalPinToBitMask(ss_pin); 507 | pinMode(ss_pin, OUTPUT); 508 | } 509 | inline static void setSS() { 510 | *(ss_pin_reg+8+1) = ss_pin_mask; 511 | } 512 | inline static void resetSS() { 513 | *(ss_pin_reg+8+2) = ss_pin_mask; 514 | } 515 | 516 | #elif defined(ARDUINO_ARCH_ESP8266) 517 | static volatile uint32_t *ss_pin_reg; 518 | static uint32_t ss_pin_mask; 519 | inline static void initSS() { 520 | ss_pin_reg = (volatile uint32_t*)GPO; 521 | ss_pin_mask = 1 << ss_pin; 522 | pinMode(ss_pin, OUTPUT); 523 | } 524 | inline static void setSS() { 525 | GPOC = ss_pin_mask; 526 | } 527 | inline static void resetSS() { 528 | GPOS = ss_pin_mask; 529 | } 530 | 531 | #elif defined(__SAMD21G18A__) 532 | static volatile uint32_t *ss_pin_reg; 533 | static uint32_t ss_pin_mask; 534 | inline static void initSS() { 535 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); 536 | ss_pin_mask = digitalPinToBitMask(ss_pin); 537 | pinMode(ss_pin, OUTPUT); 538 | } 539 | inline static void setSS() { 540 | *(ss_pin_reg+5) = ss_pin_mask; 541 | } 542 | inline static void resetSS() { 543 | *(ss_pin_reg+6) = ss_pin_mask; 544 | } 545 | #else 546 | inline static void initSS() { 547 | pinMode(ss_pin, OUTPUT); 548 | } 549 | inline static void setSS() { 550 | digitalWrite(ss_pin, LOW); 551 | } 552 | inline static void resetSS() { 553 | digitalWrite(ss_pin, HIGH); 554 | } 555 | #endif 556 | }; 557 | 558 | extern W5100Class W5100; 559 | 560 | 561 | 562 | #endif 563 | 564 | #ifndef UTIL_H 565 | #define UTIL_H 566 | 567 | #define htons(x) ( (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) ) 568 | #define ntohs(x) htons(x) 569 | 570 | #define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ 571 | ((x)<< 8 & 0x00FF0000UL) | \ 572 | ((x)>> 8 & 0x0000FF00UL) | \ 573 | ((x)>>24 & 0x000000FFUL) ) 574 | #define ntohl(x) htonl(x) 575 | 576 | #endif 577 | --------------------------------------------------------------------------------