├── src
├── EthernetClient.h
├── EthernetServer.h
├── Dns.h
├── EthernetUdp.h
├── Dhcp.h
├── EthernetServer.cpp
├── EthernetUdp.cpp
├── EthernetClient.cpp
├── M5_Ethernet.cpp
├── Dns.cpp
├── Dhcp.cpp
├── M5_Ethernet.h
├── utility
│ ├── w5100.cpp
│ └── w5100.h
└── socket.cpp
├── library.json
├── library.properties
├── README_cn.md
├── LICENSE
├── examples
├── LinkStatus
│ └── LinkStatus.ino
├── DhcpAddressPrinter
│ └── DhcpAddressPrinter.ino
├── ChatServer
│ └── ChatServer.ino
├── DhcpChatServer
│ └── DhcpChatServer.ino
├── TelnetClient
│ └── TelnetClient.ino
├── AdvancedChatServer
│ └── AdvancedChatServer.ino
├── WebServer
│ └── WebServer.ino
├── UDPSendReceiveString
│ └── UDPSendReceiveString.ino
├── WebClientRepeating
│ └── WebClientRepeating.ino
├── WebClient
│ └── WebClient.ino
├── UdpNtpClient
│ └── UdpNtpClient.ino
└── BarometricPressureWebServer
│ └── BarometricPressureWebServer.ino
├── README.md
└── keywords.txt
/src/EthernetClient.h:
--------------------------------------------------------------------------------
1 | // This file is in the public domain. No copyright is claimed.
2 |
3 | #include "M5_Ethernet.h"
4 |
--------------------------------------------------------------------------------
/src/EthernetServer.h:
--------------------------------------------------------------------------------
1 | // This file is in the public domain. No copyright is claimed.
2 |
3 | #include "M5_Ethernet.h"
4 |
--------------------------------------------------------------------------------
/library.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "M5-Ethernet",
3 | "description": "Library for M5Stack Ethernet development kit",
4 | "keywords": "W5500",
5 | "authors": {
6 | "name": "M5Stack",
7 | "url": "http://www.m5stack.com"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "https://github.com/m5stack/M5-Ethernet.git"
12 | },
13 | "version": "4.0.0",
14 | "frameworks": "arduino",
15 | "platforms": "espressif32"
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/library.properties:
--------------------------------------------------------------------------------
1 | name=M5-Ethernet
2 | version=4.0.0
3 | author=Icing Tomato (https://github.com/IcingTomato)
4 | maintainer=Icing Tomato (icing@m5stack.com)
5 | sentence=Enables network connection (local and Internet) using the M5 PoE Camera.
6 | paragraph=With this library you can use the M5 PoE Camera 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=https://github.com/m5stack/M5-Ethernet
9 | architectures=esp32
10 | includes=M5_Ethernet.h
11 |
--------------------------------------------------------------------------------
/README_cn.md:
--------------------------------------------------------------------------------
1 | # M5 PoE_CAM Ethernet Arduino 依赖库
2 |
3 | 中文 | [English](README_cn.md)
4 |
5 |
6 | 
7 |
8 | * **如果查看 PoECAM 的详细介绍文档,[点击这里](https://docs.m5stack.com/zh_CN/unit/poe_cam)**
9 |
10 | ## 描述
11 |
12 | **PoECAM**是一款集成`PoE`(Power Over Ethernet)功能的一款开源`可编程网络摄像头`。硬件使用`ESP32`控制核心+`W5500嵌入式以太网控制器`+200w像素图像传感器`OV2640`方案。 搭配`8MB PSRAM` + `16MB Flash` 大内存组合。整机体积紧凑, 供电方式灵活, 仅需两步, `连接网线, 即可实现稳定的图像传输`。非常适用于仓储监控, 定时图像采集等应用。
13 |
14 | ## 注意事项:
15 |
16 | 1. PoECAM下载程序需外接ESP32烧录器,你可以[点击此处购买M5官方的ESP32-Downloader套件,内含转接小板,连接会更加的方便](https://shop.m5stack.com/products/esp32-downloader-kit)
17 | 2. PoECAM的出厂固件,在连接交换机后将会自动获取IP,并启动web服务器。通过查看PoECAM的串口输出,可以获取到IP地址与图像流URL,同一局域网下用浏览器的访问该URL,既可以实时预览图像。
18 |
19 | ## 更多信息
20 |
21 | **Arduino IDE 环境搭建**: [点击这里](https://docs.m5stack.com/zh_CN/quick_start/poe_cam/arduino)
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 icing@tomato:~#
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/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 |
25 | Serial.begin(9600);
26 | }
27 |
28 | void loop() {
29 | auto link = Ethernet.linkStatus();
30 | Serial.print("Link status: ");
31 | switch (link) {
32 | case Unknown:
33 | Serial.println("Unknown");
34 | break;
35 | case LinkON:
36 | Serial.println("ON");
37 | break;
38 | case LinkOFF:
39 | Serial.println("OFF");
40 | break;
41 | }
42 | delay(1000);
43 | }
44 |
--------------------------------------------------------------------------------
/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 "M5_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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # M5 PoE_CAM Ethernet Arduino Library
2 |
3 | English | [中文](README_cn.md)
4 |
5 | 
6 |
7 | * **For the Detailed documentation of PoECAM, Please [Click here](https://docs.m5stack.com/en/unit/poe_cam)**
8 |
9 | ## Description:
10 |
11 | **PoECAM** is an `open source` Fully `programmable camera` integrating `PoE` (Power Over Ethernet) . This item is `ESP32` based webcam with `W5500` embedded Ethernet controller plus `200w pixel` image sensor `OV2640`.
12 | PoECAM equipped with a combination of `8MB PSRAM` + `16MB Flash` large memory. This teeny tiny with flexible power supply, you can get stable image by connecting the network cable in just 2 steps. It's wonderful for you to monitor warehouse, get auto image acquisition, etc.
13 |
14 | ## Notes:
15 |
16 | 1. The PoECAM download program requires an external ESP32 burner, you can [click here to buy the official M5 ESP32-Downloader kit, which includes a small adapter board, and the connection will be even better Convenient](https://shop.m5stack.com/products/esp32-downloader-kit)
17 | 2. The factory firmware of PoECAM will automatically obtain the IP after connecting to the switch and start the web server. By viewing the serial port output of PoECAM, you can get the IP address and the image stream URL, and you can preview the image in real time by visiting the URL with a browser under the same local area network.
18 |
19 | ## More Information
20 |
21 | **Arduino IDE Development**: [Click Here](https://docs.m5stack.com/en/quick_start/poe_cam/arduino)
22 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 "M5_Ethernet.h"
38 |
39 |
--------------------------------------------------------------------------------
/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 |
37 | // Open serial communications and wait for port to open:
38 | Serial.begin(9600);
39 | while (!Serial) {
40 | ; // wait for serial port to connect. Needed for native USB port only
41 | }
42 |
43 | // start the Ethernet connection:
44 | Serial.println("Initialize Ethernet with DHCP:");
45 | if (Ethernet.begin(mac) == 0) {
46 | Serial.println("Failed to configure Ethernet using DHCP");
47 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
48 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
49 | } else if (Ethernet.linkStatus() == LinkOFF) {
50 | Serial.println("Ethernet cable is not connected.");
51 | }
52 | // no point in carrying on, so do nothing forevermore:
53 | while (true) {
54 | delay(1);
55 | }
56 | }
57 | // print your local IP address:
58 | Serial.print("My IP address: ");
59 | Serial.println(Ethernet.localIP());
60 | }
61 |
62 | void loop() {
63 | switch (Ethernet.maintain()) {
64 | case 1:
65 | //renewed fail
66 | Serial.println("Error: renewed fail");
67 | break;
68 |
69 | case 2:
70 | //renewed success
71 | Serial.println("Renewed success");
72 | //print your local IP address:
73 | Serial.print("My IP address: ");
74 | Serial.println(Ethernet.localIP());
75 | break;
76 |
77 | case 3:
78 | //rebind fail
79 | Serial.println("Error: rebind fail");
80 | break;
81 |
82 | case 4:
83 | //rebind success
84 | Serial.println("Rebind success");
85 | //print your local IP address:
86 | Serial.print("My IP address: ");
87 | Serial.println(Ethernet.localIP());
88 | break;
89 |
90 | default:
91 | //nothing happened
92 | break;
93 | }
94 | }
95 |
96 |
--------------------------------------------------------------------------------
/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 | boolean 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 |
46 | // initialize the ethernet device
47 | Ethernet.begin(mac, ip, myDns, gateway, subnet);
48 |
49 | // Open serial communications and wait for port to open:
50 | Serial.begin(9600);
51 | while (!Serial) {
52 | ; // wait for serial port to connect. Needed for native USB port only
53 | }
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 listening for clients
67 | server.begin();
68 |
69 | Serial.print("Chat server address:");
70 | Serial.println(Ethernet.localIP());
71 | }
72 |
73 | void loop() {
74 | // wait for a new client:
75 | EthernetClient client = server.available();
76 |
77 | // when the client sends the first byte, say hello:
78 | if (client) {
79 | if (!alreadyConnected) {
80 | // clear out the input buffer:
81 | client.flush();
82 | Serial.println("We have a new client");
83 | client.println("Hello, client!");
84 | alreadyConnected = true;
85 | }
86 |
87 | if (client.available() > 0) {
88 | // read the bytes incoming from the client:
89 | char thisChar = client.read();
90 | // echo the bytes back to the client:
91 | server.write(thisChar);
92 | // echo the bytes to the server as well:
93 | Serial.write(thisChar);
94 | }
95 | }
96 | }
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/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 | boolean 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 |
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 | // start the Ethernet connection:
57 | Serial.println("Trying to get an IP address using DHCP");
58 | if (Ethernet.begin(mac) == 0) {
59 | Serial.println("Failed to configure Ethernet using DHCP");
60 | // Check for Ethernet hardware present
61 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
62 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
63 | while (true) {
64 | delay(1); // do nothing, no point running without Ethernet hardware
65 | }
66 | }
67 | if (Ethernet.linkStatus() == LinkOFF) {
68 | Serial.println("Ethernet cable is not connected.");
69 | }
70 | // initialize the Ethernet device not using DHCP:
71 | Ethernet.begin(mac, ip, myDns, gateway, subnet);
72 | }
73 | // print your local IP address:
74 | Serial.print("My IP address: ");
75 | Serial.println(Ethernet.localIP());
76 |
77 | // start listening for clients
78 | server.begin();
79 | }
80 |
81 | void loop() {
82 | // wait for a new client:
83 | EthernetClient client = server.available();
84 |
85 | // when the client sends the first byte, say hello:
86 | if (client) {
87 | if (!gotAMessage) {
88 | Serial.println("We have a new client");
89 | client.println("Hello, client!");
90 | gotAMessage = true;
91 | }
92 |
93 | // read the bytes incoming from the client:
94 | char thisChar = client.read();
95 | // echo the bytes back to the client:
96 | server.write(thisChar);
97 | // echo the bytes to the server as well:
98 | Serial.print(thisChar);
99 | Ethernet.maintain();
100 | }
101 | }
102 |
103 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
48 | // start the Ethernet connection:
49 | Ethernet.begin(mac, ip);
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 | // Check for Ethernet hardware present
58 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
59 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
60 | while (true) {
61 | delay(1); // do nothing, no point running without Ethernet hardware
62 | }
63 | }
64 | while (Ethernet.linkStatus() == LinkOFF) {
65 | Serial.println("Ethernet cable is not connected.");
66 | delay(500);
67 | }
68 |
69 | // give the Ethernet shield a second to initialize:
70 | delay(1000);
71 | Serial.println("connecting...");
72 |
73 | // if you get a connection, report back via serial:
74 | if (client.connect(server, 10002)) {
75 | Serial.println("connected");
76 | } else {
77 | // if you didn't get a connection to the server:
78 | Serial.println("connection failed");
79 | }
80 | }
81 |
82 | void loop() {
83 | // if there are incoming bytes available
84 | // from the server, read them and print them:
85 | if (client.available()) {
86 | char c = client.read();
87 | Serial.print(c);
88 | }
89 |
90 | // as long as there are bytes in the serial queue,
91 | // read them and send them out the socket if it's open:
92 | while (Serial.available() > 0) {
93 | char inChar = Serial.read();
94 | if (client.connected()) {
95 | client.print(inChar);
96 | }
97 | }
98 |
99 | // if the server's disconnected, stop the client:
100 | if (!client.connected()) {
101 | Serial.println();
102 | Serial.println("disconnecting.");
103 | client.stop();
104 | // do nothing:
105 | while (true) {
106 | delay(1);
107 | }
108 | }
109 | }
110 |
111 |
112 |
113 |
114 |
--------------------------------------------------------------------------------
/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 |
51 | // initialize the Ethernet device
52 | Ethernet.begin(mac, ip, myDns, gateway, subnet);
53 |
54 | // Open serial communications and wait for port to open:
55 | Serial.begin(9600);
56 | while (!Serial) {
57 | ; // wait for serial port to connect. Needed for native USB port only
58 | }
59 |
60 | // Check for Ethernet hardware present
61 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
62 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
63 | while (true) {
64 | delay(1); // do nothing, no point running without Ethernet hardware
65 | }
66 | }
67 | if (Ethernet.linkStatus() == LinkOFF) {
68 | Serial.println("Ethernet cable is not connected.");
69 | }
70 |
71 | // start listening for clients
72 | server.begin();
73 |
74 | Serial.print("Chat server address:");
75 | Serial.println(Ethernet.localIP());
76 | }
77 |
78 | void loop() {
79 | // check for any new client connecting, and say hello (before any incoming data)
80 | EthernetClient newClient = server.accept();
81 | if (newClient) {
82 | for (byte i=0; i < 8; i++) {
83 | if (!clients[i]) {
84 | Serial.print("We have a new client #");
85 | Serial.println(i);
86 | newClient.print("Hello, client number: ");
87 | newClient.println(i);
88 | // Once we "accept", the client is no longer tracked by EthernetServer
89 | // so we must store it into our list of clients
90 | clients[i] = newClient;
91 | break;
92 | }
93 | }
94 | }
95 |
96 | // check for incoming data from all clients
97 | for (byte i=0; i < 8; i++) {
98 | if (clients[i] && clients[i].available() > 0) {
99 | // read bytes from a client
100 | byte buffer[80];
101 | int count = clients[i].read(buffer, 80);
102 | // write the bytes to all other connected clients
103 | for (byte j=0; j < 8; j++) {
104 | if (j != i && clients[j].connected()) {
105 | clients[j].write(buffer, count);
106 | }
107 | }
108 | }
109 | }
110 |
111 | // stop any clients which disconnect
112 | for (byte i=0; i < 8; i++) {
113 | if (clients[i] && !clients[i].connected()) {
114 | Serial.print("disconnect client #");
115 | Serial.println(i);
116 | clients[i].stop();
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/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 |
44 | // Open serial communications and wait for port to open:
45 | Serial.begin(9600);
46 | while (!Serial) {
47 | ; // wait for serial port to connect. Needed for native USB port only
48 | }
49 | Serial.println("Ethernet WebServer Example");
50 |
51 | // start the Ethernet connection and the server:
52 | Ethernet.begin(mac, ip);
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 the server
66 | server.begin();
67 | Serial.print("server is at ");
68 | Serial.println(Ethernet.localIP());
69 | }
70 |
71 |
72 | void loop() {
73 | // listen for incoming clients
74 | EthernetClient client = server.available();
75 | if (client) {
76 | Serial.println("new client");
77 | // an http request ends with a blank line
78 | boolean currentLineIsBlank = true;
79 | while (client.connected()) {
80 | if (client.available()) {
81 | char c = client.read();
82 | Serial.write(c);
83 | // if you've gotten to the end of the line (received a newline
84 | // character) and the line is blank, the http request has ended,
85 | // so you can send a reply
86 | if (c == '\n' && currentLineIsBlank) {
87 | // send a standard http response header
88 | client.println("HTTP/1.1 200 OK");
89 | client.println("Content-Type: text/html");
90 | client.println("Connection: close"); // the connection will be closed after completion of the response
91 | client.println("Refresh: 5"); // refresh the page automatically every 5 sec
92 | client.println();
93 | client.println("");
94 | client.println("");
95 | // output the value of each analog input pin
96 | for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
97 | int sensorReading = analogRead(analogChannel);
98 | client.print("analog input ");
99 | client.print(analogChannel);
100 | client.print(" is ");
101 | client.print(sensorReading);
102 | client.println("
");
103 | }
104 | client.println("");
105 | break;
106 | }
107 | if (c == '\n') {
108 | // you're starting a new line
109 | currentLineIsBlank = true;
110 | } else if (c != '\r') {
111 | // you've gotten a character on the current line
112 | currentLineIsBlank = false;
113 | }
114 | }
115 | }
116 | // give the web browser time to receive the data
117 | delay(1);
118 | // close the connection:
119 | client.stop();
120 | Serial.println("client disconnected");
121 | }
122 | }
123 |
124 |
--------------------------------------------------------------------------------
/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 |
44 | // start the Ethernet
45 | Ethernet.begin(mac, ip);
46 |
47 | // Open serial communications and wait for port to open:
48 | Serial.begin(9600);
49 | while (!Serial) {
50 | ; // wait for serial port to connect. Needed for native USB port only
51 | }
52 |
53 | // Check for Ethernet hardware present
54 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
55 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
56 | while (true) {
57 | delay(1); // do nothing, no point running without Ethernet hardware
58 | }
59 | }
60 | if (Ethernet.linkStatus() == LinkOFF) {
61 | Serial.println("Ethernet cable is not connected.");
62 | }
63 |
64 | // start UDP
65 | Udp.begin(localPort);
66 | }
67 |
68 | void loop() {
69 | // if there's data available, read a packet
70 | int packetSize = Udp.parsePacket();
71 | if (packetSize) {
72 | Serial.print("Received packet of size ");
73 | Serial.println(packetSize);
74 | Serial.print("From ");
75 | IPAddress remote = Udp.remoteIP();
76 | for (int i=0; i < 4; i++) {
77 | Serial.print(remote[i], DEC);
78 | if (i < 3) {
79 | Serial.print(".");
80 | }
81 | }
82 | Serial.print(", port ");
83 | Serial.println(Udp.remotePort());
84 |
85 | // read the packet into packetBufffer
86 | Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
87 | Serial.println("Contents:");
88 | Serial.println(packetBuffer);
89 |
90 | // send a reply to the IP address and port that sent us the packet we received
91 | Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
92 | Udp.write(ReplyBuffer);
93 | Udp.endPacket();
94 | }
95 | delay(10);
96 | }
97 |
98 |
99 | /*
100 | Processing sketch to run with this example
101 | =====================================================
102 |
103 | // Processing UDP example to send and receive string data from Arduino
104 | // press any key to send the "Hello Arduino" message
105 |
106 |
107 | import hypermedia.net.*;
108 |
109 | UDP udp; // define the UDP object
110 |
111 |
112 | void setup() {
113 | udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000
114 | //udp.log( true ); // <-- printout the connection activity
115 | udp.listen( true ); // and wait for incoming message
116 | }
117 |
118 | void draw()
119 | {
120 | }
121 |
122 | void keyPressed() {
123 | String ip = "192.168.1.177"; // the remote IP address
124 | int port = 8888; // the destination port
125 |
126 | udp.send("Hello World", ip, port ); // the message to send
127 |
128 | }
129 |
130 | void receive( byte[] data ) { // <-- default handler
131 | //void receive( byte[] data, String ip, int port ) { // <-- extended handler
132 |
133 | for(int i=0; i < data.length; i++)
134 | print(char(data[i]));
135 | println();
136 | }
137 | */
138 |
139 |
140 |
--------------------------------------------------------------------------------
/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 |
55 | // start serial port:
56 | Serial.begin(9600);
57 | while (!Serial) {
58 | ; // wait for serial port to connect. Needed for native USB port only
59 | }
60 |
61 | // start the Ethernet connection:
62 | Serial.println("Initialize Ethernet with DHCP:");
63 | if (Ethernet.begin(mac) == 0) {
64 | Serial.println("Failed to configure Ethernet using DHCP");
65 | // Check for Ethernet hardware present
66 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
67 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
68 | while (true) {
69 | delay(1); // do nothing, no point running without Ethernet hardware
70 | }
71 | }
72 | if (Ethernet.linkStatus() == LinkOFF) {
73 | Serial.println("Ethernet cable is not connected.");
74 | }
75 | // try to congifure using IP address instead of DHCP:
76 | Ethernet.begin(mac, ip, myDns);
77 | Serial.print("My IP address: ");
78 | Serial.println(Ethernet.localIP());
79 | } else {
80 | Serial.print(" DHCP assigned IP ");
81 | Serial.println(Ethernet.localIP());
82 | }
83 | // give the Ethernet shield a second to initialize:
84 | delay(1000);
85 | }
86 |
87 | void loop() {
88 | // if there's incoming data from the net connection.
89 | // send it out the serial port. This is for debugging
90 | // purposes only:
91 | if (client.available()) {
92 | char c = client.read();
93 | Serial.write(c);
94 | }
95 |
96 | // if ten seconds have passed since your last connection,
97 | // then connect again and send data:
98 | if (millis() - lastConnectionTime > postingInterval) {
99 | httpRequest();
100 | }
101 |
102 | }
103 |
104 | // this method makes a HTTP connection to the server:
105 | void httpRequest() {
106 | // close any connection before send a new request.
107 | // This will free the socket on the WiFi shield
108 | client.stop();
109 |
110 | // if there's a successful connection:
111 | if (client.connect(server, 80)) {
112 | Serial.println("connecting...");
113 | // send the HTTP GET request:
114 | client.println("GET /latest.txt HTTP/1.1");
115 | client.println("Host: www.arduino.cc");
116 | client.println("User-Agent: arduino-ethernet");
117 | client.println("Connection: close");
118 | client.println();
119 |
120 | // note the time that the connection was made:
121 | lastConnectionTime = millis();
122 | } else {
123 | // if you couldn't make a connection:
124 | Serial.println("connection failed");
125 | }
126 | }
127 |
128 |
129 |
130 |
131 |
--------------------------------------------------------------------------------
/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 |
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 the Ethernet connection:
59 | Serial.println("Initialize Ethernet with DHCP:");
60 | if (Ethernet.begin(mac) == 0) {
61 | Serial.println("Failed to configure Ethernet using DHCP");
62 | // Check for Ethernet hardware present
63 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
64 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
65 | while (true) {
66 | delay(1); // do nothing, no point running without Ethernet hardware
67 | }
68 | }
69 | if (Ethernet.linkStatus() == LinkOFF) {
70 | Serial.println("Ethernet cable is not connected.");
71 | }
72 | // try to congifure using IP address instead of DHCP:
73 | Ethernet.begin(mac, ip, myDns);
74 | } else {
75 | Serial.print(" DHCP assigned IP ");
76 | Serial.println(Ethernet.localIP());
77 | }
78 | // give the Ethernet shield a second to initialize:
79 | delay(1000);
80 | Serial.print("connecting to ");
81 | Serial.print(server);
82 | Serial.println("...");
83 |
84 | // if you get a connection, report back via serial:
85 | if (client.connect(server, 80)) {
86 | Serial.print("connected to ");
87 | Serial.println(client.remoteIP());
88 | // Make a HTTP request:
89 | client.println("GET /search?q=arduino HTTP/1.1");
90 | client.println("Host: www.google.com");
91 | client.println("Connection: close");
92 | client.println();
93 | } else {
94 | // if you didn't get a connection to the server:
95 | Serial.println("connection failed");
96 | }
97 | beginMicros = micros();
98 | }
99 |
100 | void loop() {
101 | // if there are incoming bytes available
102 | // from the server, read them and print them:
103 | int len = client.available();
104 | if (len > 0) {
105 | byte buffer[80];
106 | if (len > 80) len = 80;
107 | client.read(buffer, len);
108 | if (printWebData) {
109 | Serial.write(buffer, len); // show in the serial monitor (slows some boards)
110 | }
111 | byteCount = byteCount + len;
112 | }
113 |
114 | // if the server's disconnected, stop the client:
115 | if (!client.connected()) {
116 | endMicros = micros();
117 | Serial.println();
118 | Serial.println("disconnecting.");
119 | client.stop();
120 | Serial.print("Received ");
121 | Serial.print(byteCount);
122 | Serial.print(" bytes in ");
123 | float seconds = (float)(endMicros - beginMicros) / 1000000.0;
124 | Serial.print(seconds, 4);
125 | float rate = (float)byteCount / seconds / 1000.0;
126 | Serial.print(", rate = ");
127 | Serial.print(rate);
128 | Serial.print(" kbytes/second");
129 | Serial.println();
130 |
131 | // do nothing forevermore:
132 | while (true) {
133 | delay(1);
134 | }
135 | }
136 | }
137 |
138 |
--------------------------------------------------------------------------------
/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 | 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 |
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 | // start Ethernet and UDP
57 | if (Ethernet.begin(mac) == 0) {
58 | Serial.println("Failed to configure Ethernet using DHCP");
59 | // Check for Ethernet hardware present
60 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
61 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
62 | } else if (Ethernet.linkStatus() == LinkOFF) {
63 | Serial.println("Ethernet cable is not connected.");
64 | }
65 | // no point in carrying on, so do nothing forevermore:
66 | while (true) {
67 | delay(1);
68 | }
69 | }
70 | Udp.begin(localPort);
71 | }
72 |
73 | void loop() {
74 | sendNTPpacket(timeServer); // send an NTP packet to a time server
75 |
76 | // wait to see if a reply is available
77 | delay(1000);
78 | if (Udp.parsePacket()) {
79 | // We've received a packet, read the data from it
80 | Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
81 |
82 | // the timestamp starts at byte 40 of the received packet and is four bytes,
83 | // or two words, long. First, extract the two words:
84 |
85 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
86 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
87 | // combine the four bytes (two words) into a long integer
88 | // this is NTP time (seconds since Jan 1 1900):
89 | unsigned long secsSince1900 = highWord << 16 | lowWord;
90 | Serial.print("Seconds since Jan 1 1900 = ");
91 | Serial.println(secsSince1900);
92 |
93 | // now convert NTP time into everyday time:
94 | Serial.print("Unix time = ");
95 | // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
96 | const unsigned long seventyYears = 2208988800UL;
97 | // subtract seventy years:
98 | unsigned long epoch = secsSince1900 - seventyYears;
99 | // print Unix time:
100 | Serial.println(epoch);
101 |
102 |
103 | // print the hour, minute and second:
104 | Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
105 | Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
106 | Serial.print(':');
107 | if (((epoch % 3600) / 60) < 10) {
108 | // In the first 10 minutes of each hour, we'll want a leading '0'
109 | Serial.print('0');
110 | }
111 | Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
112 | Serial.print(':');
113 | if ((epoch % 60) < 10) {
114 | // In the first 10 seconds of each minute, we'll want a leading '0'
115 | Serial.print('0');
116 | }
117 | Serial.println(epoch % 60); // print the second
118 | }
119 | // wait ten seconds before asking for the time again
120 | delay(10000);
121 | Ethernet.maintain();
122 | }
123 |
124 | // send an NTP request to the time server at the given address
125 | void sendNTPpacket(const char * address) {
126 | // set all bytes in the buffer to 0
127 | memset(packetBuffer, 0, NTP_PACKET_SIZE);
128 | // Initialize values needed to form NTP request
129 | // (see URL above for details on the packets)
130 | packetBuffer[0] = 0b11100011; // LI, Version, Mode
131 | packetBuffer[1] = 0; // Stratum, or type of clock
132 | packetBuffer[2] = 6; // Polling Interval
133 | packetBuffer[3] = 0xEC; // Peer Clock Precision
134 | // 8 bytes of zero for Root Delay & Root Dispersion
135 | packetBuffer[12] = 49;
136 | packetBuffer[13] = 0x4E;
137 | packetBuffer[14] = 49;
138 | packetBuffer[15] = 52;
139 |
140 | // all NTP fields have been given values, now
141 | // you can send a packet requesting a timestamp:
142 | Udp.beginPacket(address, 123); // NTP requests are to port 123
143 | Udp.write(packetBuffer, NTP_PACKET_SIZE);
144 | Udp.endPacket();
145 | }
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
--------------------------------------------------------------------------------
/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 "M5_Ethernet.h"
23 | #include "utility/w5100.h"
24 |
25 | uint16_t EthernetServer::server_port[MAX_SOCK_NUM];
26 |
27 |
28 | void EthernetServer::begin(uint16_t port)
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) 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 || stat == SnSR::ESTABLISHED) {
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) 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) 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) 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/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 "M5_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[8];
112 | int ret=0;
113 | //read 8 header bytes and get IP and port from it
114 | ret = Ethernet.socketRecv(sockindex, tmpBuf, 8);
115 | if (ret > 0) {
116 | _remoteIP = tmpBuf;
117 | _remotePort = tmpBuf[4];
118 | _remotePort = (_remotePort << 8) + tmpBuf[5];
119 | _remaining = tmpBuf[6];
120 | _remaining = (_remaining << 8) + tmpBuf[7];
121 |
122 | // When we get here, any remaining bytes are the data
123 | ret = _remaining;
124 | }
125 | return ret;
126 | }
127 | // There aren't any packets available
128 | return 0;
129 | }
130 |
131 | int EthernetUDP::read()
132 | {
133 | uint8_t byte;
134 |
135 | if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) {
136 | // We read things without any problems
137 | _remaining--;
138 | return byte;
139 | }
140 |
141 | // If we get here, there's no data available
142 | return -1;
143 | }
144 |
145 | int EthernetUDP::read(unsigned char *buffer, size_t len)
146 | {
147 | if (_remaining > 0) {
148 | int got;
149 | if (_remaining <= len) {
150 | // data should fit in the buffer
151 | got = Ethernet.socketRecv(sockindex, buffer, _remaining);
152 | } else {
153 | // too much data for the buffer,
154 | // grab as much as will fit
155 | got = Ethernet.socketRecv(sockindex, buffer, len);
156 | }
157 | if (got > 0) {
158 | _remaining -= got;
159 | //Serial.printf("UDP read %d\n", got);
160 | return got;
161 | }
162 | }
163 | // If we get here, there's no data available or recv failed
164 | return -1;
165 | }
166 |
167 | int EthernetUDP::peek()
168 | {
169 | // Unlike recv, peek doesn't check to see if there's any data available, so we must.
170 | // If the user hasn't called parsePacket yet then return nothing otherwise they
171 | // may get the UDP header
172 | if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1;
173 | return Ethernet.socketPeek(sockindex);
174 | }
175 |
176 | void EthernetUDP::flush()
177 | {
178 | // TODO: we should wait for TX buffer to be emptied
179 | }
180 |
181 | /* Start EthernetUDP socket, listening at local port PORT */
182 | uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port)
183 | {
184 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex);
185 | sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port);
186 | if (sockindex >= MAX_SOCK_NUM) return 0;
187 | _port = port;
188 | _remaining = 0;
189 | return 1;
190 | }
191 |
192 |
--------------------------------------------------------------------------------
/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 "M5_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 | // wait up to a second for the connection to close
140 | do {
141 | if (Ethernet.socketStatus(sockindex) == SnSR::CLOSED) {
142 | sockindex = MAX_SOCK_NUM;
143 | return; // exit the loop
144 | }
145 | delay(1);
146 | } while (millis() - start < _timeout);
147 |
148 | // if it hasn't closed, close it forcefully
149 | Ethernet.socketClose(sockindex);
150 | sockindex = MAX_SOCK_NUM;
151 | }
152 |
153 | uint8_t EthernetClient::connected()
154 | {
155 | if (sockindex >= MAX_SOCK_NUM) return 0;
156 |
157 | uint8_t s = Ethernet.socketStatus(sockindex);
158 | return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
159 | (s == SnSR::CLOSE_WAIT && !available()));
160 | }
161 |
162 | uint8_t EthernetClient::status()
163 | {
164 | if (sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED;
165 | return Ethernet.socketStatus(sockindex);
166 | }
167 |
168 | // the next function allows us to use the client returned by
169 | // EthernetServer::available() as the condition in an if-statement.
170 | bool EthernetClient::operator==(const EthernetClient& rhs)
171 | {
172 | if (sockindex != rhs.sockindex) return false;
173 | if (sockindex >= MAX_SOCK_NUM) return false;
174 | if (rhs.sockindex >= MAX_SOCK_NUM) return false;
175 | return true;
176 | }
177 |
178 | // https://github.com/per1234/EthernetMod
179 | // from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd
180 | uint16_t EthernetClient::localPort()
181 | {
182 | if (sockindex >= MAX_SOCK_NUM) return 0;
183 | uint16_t port;
184 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
185 | port = W5100.readSnPORT(sockindex);
186 | SPI.endTransaction();
187 | return port;
188 | }
189 |
190 | // https://github.com/per1234/EthernetMod
191 | // returns the remote IP address: http://forum.arduino.cc/index.php?topic=82416.0
192 | IPAddress EthernetClient::remoteIP()
193 | {
194 | if (sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0);
195 | uint8_t remoteIParray[4];
196 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
197 | W5100.readSnDIPR(sockindex, remoteIParray);
198 | SPI.endTransaction();
199 | return IPAddress(remoteIParray);
200 | }
201 |
202 | // https://github.com/per1234/EthernetMod
203 | // from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75
204 | uint16_t EthernetClient::remotePort()
205 | {
206 | if (sockindex >= MAX_SOCK_NUM) return 0;
207 | uint16_t port;
208 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
209 | port = W5100.readSnDPORT(sockindex);
210 | SPI.endTransaction();
211 | return port;
212 | }
213 |
214 |
215 |
--------------------------------------------------------------------------------
/src/M5_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 "M5_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 51: return EthernetW5100;
118 | case 52: return EthernetW5200;
119 | case 55: return EthernetW5500;
120 | default: return EthernetNoHardware;
121 | }
122 | }
123 |
124 | int EthernetClass::maintain()
125 | {
126 | int rc = DHCP_CHECK_NONE;
127 | if (_dhcp != NULL) {
128 | // we have a pointer to dhcp, use it
129 | rc = _dhcp->checkLease();
130 | switch (rc) {
131 | case DHCP_CHECK_NONE:
132 | //nothing done
133 | break;
134 | case DHCP_CHECK_RENEW_OK:
135 | case DHCP_CHECK_REBIND_OK:
136 | //we might have got a new IP.
137 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
138 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address());
139 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address());
140 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address());
141 | SPI.endTransaction();
142 | _dnsServerAddress = _dhcp->getDnsServerIp();
143 | break;
144 | default:
145 | //this is actually an error, it will retry though
146 | break;
147 | }
148 | }
149 | return rc;
150 | }
151 |
152 |
153 | void EthernetClass::MACAddress(uint8_t *mac_address)
154 | {
155 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
156 | W5100.getMACAddress(mac_address);
157 | SPI.endTransaction();
158 | }
159 |
160 | IPAddress EthernetClass::localIP()
161 | {
162 | IPAddress ret;
163 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
164 | W5100.getIPAddress(ret.raw_address());
165 | SPI.endTransaction();
166 | return ret;
167 | }
168 |
169 | IPAddress EthernetClass::subnetMask()
170 | {
171 | IPAddress ret;
172 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
173 | W5100.getSubnetMask(ret.raw_address());
174 | SPI.endTransaction();
175 | return ret;
176 | }
177 |
178 | IPAddress EthernetClass::gatewayIP()
179 | {
180 | IPAddress ret;
181 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
182 | W5100.getGatewayIp(ret.raw_address());
183 | SPI.endTransaction();
184 | return ret;
185 | }
186 |
187 | void EthernetClass::setMACAddress(const uint8_t *mac_address)
188 | {
189 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
190 | W5100.setMACAddress(mac_address);
191 | SPI.endTransaction();
192 | }
193 |
194 | void EthernetClass::setLocalIP(const IPAddress local_ip)
195 | {
196 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
197 | IPAddress ip = local_ip;
198 | W5100.setIPAddress(ip.raw_address());
199 | SPI.endTransaction();
200 | }
201 |
202 | void EthernetClass::setSubnetMask(const IPAddress subnet)
203 | {
204 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
205 | IPAddress ip = subnet;
206 | W5100.setSubnetMask(ip.raw_address());
207 | SPI.endTransaction();
208 | }
209 |
210 | void EthernetClass::setGatewayIP(const IPAddress gateway)
211 | {
212 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
213 | IPAddress ip = gateway;
214 | W5100.setGatewayIp(ip.raw_address());
215 | SPI.endTransaction();
216 | }
217 |
218 | void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds)
219 | {
220 | if (milliseconds > 6553) milliseconds = 6553;
221 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
222 | W5100.setRetransmissionTime(milliseconds * 10);
223 | SPI.endTransaction();
224 | }
225 |
226 | void EthernetClass::setRetransmissionCount(uint8_t num)
227 | {
228 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
229 | W5100.setRetransmissionCount(num);
230 | SPI.endTransaction();
231 | }
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 | EthernetClass Ethernet;
243 |
--------------------------------------------------------------------------------
/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 |
69 | // start the SPI library:
70 | SPI.begin();
71 |
72 | // start the Ethernet connection
73 | Ethernet.begin(mac, ip);
74 |
75 | // Open serial communications and wait for port to open:
76 | Serial.begin(9600);
77 | while (!Serial) {
78 | ; // wait for serial port to connect. Needed for native USB port only
79 | }
80 |
81 | // Check for Ethernet hardware present
82 | if (Ethernet.hardwareStatus() == EthernetNoHardware) {
83 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
84 | while (true) {
85 | delay(1); // do nothing, no point running without Ethernet hardware
86 | }
87 | }
88 | if (Ethernet.linkStatus() == LinkOFF) {
89 | Serial.println("Ethernet cable is not connected.");
90 | }
91 |
92 | // start listening for clients
93 | server.begin();
94 |
95 | // initalize the data ready and chip select pins:
96 | pinMode(dataReadyPin, INPUT);
97 | pinMode(chipSelectPin, OUTPUT);
98 |
99 | //Configure SCP1000 for low noise configuration:
100 | writeRegister(0x02, 0x2D);
101 | writeRegister(0x01, 0x03);
102 | writeRegister(0x03, 0x02);
103 |
104 | // give the sensor and Ethernet shield time to set up:
105 | delay(1000);
106 |
107 | //Set the sensor to high resolution mode tp start readings:
108 | writeRegister(0x03, 0x0A);
109 |
110 | }
111 |
112 | void loop() {
113 | // check for a reading no more than once a second.
114 | if (millis() - lastReadingTime > 1000) {
115 | // if there's a reading ready, read it:
116 | // don't do anything until the data ready pin is high:
117 | if (digitalRead(dataReadyPin) == HIGH) {
118 | getData();
119 | // timestamp the last time you got a reading:
120 | lastReadingTime = millis();
121 | }
122 | }
123 |
124 | // listen for incoming Ethernet connections:
125 | listenForEthernetClients();
126 | }
127 |
128 |
129 | void getData() {
130 | Serial.println("Getting reading");
131 | //Read the temperature data
132 | int tempData = readRegister(0x21, 2);
133 |
134 | // convert the temperature to celsius and display it:
135 | temperature = (float)tempData / 20.0;
136 |
137 | //Read the pressure data highest 3 bits:
138 | byte pressureDataHigh = readRegister(0x1F, 1);
139 | pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0
140 |
141 | //Read the pressure data lower 16 bits:
142 | unsigned int pressureDataLow = readRegister(0x20, 2);
143 | //combine the two parts into one 19-bit number:
144 | pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4;
145 |
146 | Serial.print("Temperature: ");
147 | Serial.print(temperature);
148 | Serial.println(" degrees C");
149 | Serial.print("Pressure: " + String(pressure));
150 | Serial.println(" Pa");
151 | }
152 |
153 | void listenForEthernetClients() {
154 | // listen for incoming clients
155 | EthernetClient client = server.available();
156 | if (client) {
157 | Serial.println("Got a client");
158 | // an http request ends with a blank line
159 | boolean currentLineIsBlank = true;
160 | while (client.connected()) {
161 | if (client.available()) {
162 | char c = client.read();
163 | // if you've gotten to the end of the line (received a newline
164 | // character) and the line is blank, the http request has ended,
165 | // so you can send a reply
166 | if (c == '\n' && currentLineIsBlank) {
167 | // send a standard http response header
168 | client.println("HTTP/1.1 200 OK");
169 | client.println("Content-Type: text/html");
170 | client.println();
171 | // print the current readings, in HTML format:
172 | client.print("Temperature: ");
173 | client.print(temperature);
174 | client.print(" degrees C");
175 | client.println("
");
176 | client.print("Pressure: " + String(pressure));
177 | client.print(" Pa");
178 | client.println("
");
179 | break;
180 | }
181 | if (c == '\n') {
182 | // you're starting a new line
183 | currentLineIsBlank = true;
184 | } else if (c != '\r') {
185 | // you've gotten a character on the current line
186 | currentLineIsBlank = false;
187 | }
188 | }
189 | }
190 | // give the web browser time to receive the data
191 | delay(1);
192 | // close the connection:
193 | client.stop();
194 | }
195 | }
196 |
197 |
198 | //Send a write command to SCP1000
199 | void writeRegister(byte registerName, byte registerValue) {
200 | // SCP1000 expects the register name in the upper 6 bits
201 | // of the byte:
202 | registerName <<= 2;
203 | // command (read or write) goes in the lower two bits:
204 | registerName |= 0b00000010; //Write command
205 |
206 | // take the chip select low to select the device:
207 | digitalWrite(chipSelectPin, LOW);
208 |
209 | SPI.transfer(registerName); //Send register location
210 | SPI.transfer(registerValue); //Send value to record into register
211 |
212 | // take the chip select high to de-select:
213 | digitalWrite(chipSelectPin, HIGH);
214 | }
215 |
216 |
217 | //Read register from the SCP1000:
218 | unsigned int readRegister(byte registerName, int numBytes) {
219 | byte inByte = 0; // incoming from the SPI read
220 | unsigned int result = 0; // result to return
221 |
222 | // SCP1000 expects the register name in the upper 6 bits
223 | // of the byte:
224 | registerName <<= 2;
225 | // command (read or write) goes in the lower two bits:
226 | registerName &= 0b11111100; //Read command
227 |
228 | // take the chip select low to select the device:
229 | digitalWrite(chipSelectPin, LOW);
230 | // send the device the register you want to read:
231 | int command = SPI.transfer(registerName);
232 | // send a value of 0 to read the first byte returned:
233 | inByte = SPI.transfer(0x00);
234 |
235 | result = inByte;
236 | // if there's more than one byte returned,
237 | // shift the first byte then get the second byte:
238 | if (numBytes > 1) {
239 | result = inByte << 8;
240 | inByte = SPI.transfer(0x00);
241 | result = result | inByte;
242 | }
243 | // take the chip select high to de-select:
244 | digitalWrite(chipSelectPin, HIGH);
245 | // return the result:
246 | return (result);
247 | }
248 |
--------------------------------------------------------------------------------
/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 "M5_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/Dhcp.cpp:
--------------------------------------------------------------------------------
1 | // DHCP Library v0.3 - April 25, 2009
2 | // Author: Jordan Terrell - blog.jordanterrell.com
3 |
4 | #include
5 | #include "M5_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/M5_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 | #define MAX_SOCK_NUM 2
42 |
43 | // By default, each socket uses 2K buffers inside the Wiznet chip. If
44 | // MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting
45 | // this will use larger buffers within the Wiznet chip. Large buffers
46 | // can really help with UDP protocols like Artnet. In theory larger
47 | // buffers should allow faster TCP over high-latency links, but this
48 | // does not always seem to work in practice (maybe Wiznet bugs?)
49 | #define ETHERNET_LARGE_BUFFERS
50 |
51 |
52 | #include
53 | #include "Client.h"
54 | #include "Server.h"
55 | #include "Udp.h"
56 |
57 | enum EthernetLinkStatus {
58 | Unknown,
59 | LinkON,
60 | LinkOFF
61 | };
62 |
63 | enum EthernetHardwareStatus {
64 | EthernetNoHardware,
65 | EthernetW5100,
66 | EthernetW5200,
67 | EthernetW5500
68 | };
69 |
70 | class EthernetUDP;
71 | class EthernetClient;
72 | class EthernetServer;
73 | class DhcpClass;
74 |
75 | class EthernetClass {
76 | private:
77 | static IPAddress _dnsServerAddress;
78 | static DhcpClass* _dhcp;
79 | public:
80 | // Initialise the Ethernet shield to use the provided MAC address and
81 | // gain the rest of the configuration through DHCP.
82 | // Returns 0 if the DHCP configuration failed, and 1 if it succeeded
83 | static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
84 | static int maintain();
85 | static EthernetLinkStatus linkStatus();
86 | static EthernetHardwareStatus hardwareStatus();
87 |
88 | // Manaul configuration
89 | static void begin(uint8_t *mac, IPAddress ip);
90 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns);
91 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway);
92 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet);
93 | static void init(uint8_t sspin = 10);
94 |
95 | static void MACAddress(uint8_t *mac_address);
96 | static IPAddress localIP();
97 | static IPAddress subnetMask();
98 | static IPAddress gatewayIP();
99 | static IPAddress dnsServerIP() { return _dnsServerAddress; }
100 |
101 | void setMACAddress(const uint8_t *mac_address);
102 | void setLocalIP(const IPAddress local_ip);
103 | void setSubnetMask(const IPAddress subnet);
104 | void setGatewayIP(const IPAddress gateway);
105 | void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; }
106 | void setRetransmissionTimeout(uint16_t milliseconds);
107 | void setRetransmissionCount(uint8_t num);
108 |
109 | static uint16_t socketSendAvailable(uint8_t s);
110 | static uint16_t socketRecvAvailable(uint8_t s);
111 | static void socketDisconnect(uint8_t s);
112 |
113 | friend class EthernetClient;
114 | friend class EthernetServer;
115 | friend class EthernetUDP;
116 | private:
117 | // Opens a socket(TCP or UDP or IP_RAW mode)
118 | static uint8_t socketBegin(uint8_t protocol, uint16_t port);
119 | static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port);
120 | static uint8_t socketStatus(uint8_t s);
121 | // Close socket
122 | static void socketClose(uint8_t s);
123 | // Establish TCP connection (Active connection)
124 | static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port);
125 | // disconnect the connection
126 | // Establish TCP connection (Passive connection)
127 | static uint8_t socketListen(uint8_t s);
128 | // Send data (TCP)
129 | static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len);
130 | // Receive data (TCP)
131 | static int socketRecv(uint8_t s, uint8_t * buf, int16_t len);
132 | static uint8_t socketPeek(uint8_t s);
133 | // sets up a UDP datagram, the data for which will be provided by one
134 | // or more calls to bufferData and then finally sent with sendUDP.
135 | // return true if the datagram was successfully set up, or false if there was an error
136 | static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port);
137 | // copy up to len bytes of data from buf into a UDP datagram to be
138 | // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls.
139 | // return Number of bytes successfully buffered
140 | static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len);
141 | // Send a UDP datagram built up from a sequence of startUDP followed by one or more
142 | // calls to bufferData.
143 | // return true if the datagram was successfully sent, or false if there was an error
144 | static bool socketSendUDP(uint8_t s);
145 | // Initialize the "random" source port number
146 | static void socketPortRand(uint16_t n);
147 | };
148 |
149 | extern EthernetClass Ethernet;
150 |
151 |
152 | #define UDP_TX_PACKET_MAX_SIZE 24
153 |
154 | class EthernetUDP : public UDP {
155 | private:
156 | uint16_t _port; // local port to listen on
157 | IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed
158 | uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed
159 | uint16_t _offset; // offset into the packet being sent
160 |
161 | protected:
162 | uint8_t sockindex;
163 | uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
164 |
165 | public:
166 | EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor
167 | 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
168 | 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
169 | virtual void stop(); // Finish with the UDP socket
170 |
171 | // Sending UDP packets
172 |
173 | // Start building up a packet to send to the remote host specific in ip and port
174 | // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
175 | virtual int beginPacket(IPAddress ip, uint16_t port);
176 | // Start building up a packet to send to the remote host specific in host and port
177 | // Returns 1 if successful, 0 if there was a problem resolving the hostname or port
178 | virtual int beginPacket(const char *host, uint16_t port);
179 | // Finish off this packet and send it
180 | // Returns 1 if the packet was sent successfully, 0 if there was an error
181 | virtual int endPacket();
182 | // Write a single byte into the packet
183 | virtual size_t write(uint8_t);
184 | // Write size bytes from buffer into the packet
185 | virtual size_t write(const uint8_t *buffer, size_t size);
186 |
187 | using Print::write;
188 |
189 | // Start processing the next available incoming packet
190 | // Returns the size of the packet in bytes, or 0 if no packets are available
191 | virtual int parsePacket();
192 | // Number of bytes remaining in the current packet
193 | virtual int available();
194 | // Read a single byte from the current packet
195 | virtual int read();
196 | // Read up to len bytes from the current packet and place them into buffer
197 | // Returns the number of bytes read, or 0 if none are available
198 | virtual int read(unsigned char* buffer, size_t len);
199 | // Read up to len characters from the current packet and place them into buffer
200 | // Returns the number of characters read, or 0 if none are available
201 | virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); };
202 | // Return the next byte from the current packet without moving on to the next byte
203 | virtual int peek();
204 | virtual void flush(); // Finish reading the current packet
205 |
206 | // Return the IP address of the host who sent the current incoming packet
207 | virtual IPAddress remoteIP() { return _remoteIP; };
208 | // Return the port of the host who sent the current incoming packet
209 | virtual uint16_t remotePort() { return _remotePort; };
210 | virtual uint16_t localPort() { return _port; }
211 | };
212 |
213 |
214 |
215 |
216 | class EthernetClient : public Client {
217 | public:
218 | EthernetClient() : sockindex(MAX_SOCK_NUM), _timeout(1000) { }
219 | EthernetClient(uint8_t s) : sockindex(s), _timeout(1000) { }
220 |
221 | uint8_t status();
222 | virtual int connect(IPAddress ip, uint16_t port);
223 | virtual int connect(const char *host, uint16_t port);
224 | virtual int availableForWrite(void);
225 | virtual size_t write(uint8_t);
226 | virtual size_t write(const uint8_t *buf, size_t size);
227 | virtual int available();
228 | virtual int read();
229 | virtual int read(uint8_t *buf, size_t size);
230 | virtual int peek();
231 | virtual void flush();
232 | virtual void stop();
233 | virtual uint8_t connected();
234 | virtual operator bool() { return sockindex < MAX_SOCK_NUM; }
235 | virtual bool operator==(const bool value) { return bool() == value; }
236 | virtual bool operator!=(const bool value) { return bool() != value; }
237 | virtual bool operator==(const EthernetClient&);
238 | virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); }
239 | uint8_t getSocketNumber() const { return sockindex; }
240 | virtual uint16_t localPort();
241 | virtual IPAddress remoteIP();
242 | virtual uint16_t remotePort();
243 | virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; }
244 |
245 | friend class EthernetServer;
246 |
247 | using Print::write;
248 |
249 | private:
250 | uint8_t sockindex; // MAX_SOCK_NUM means client not in use
251 | uint16_t _timeout;
252 | };
253 |
254 |
255 | class EthernetServer : public Server {
256 | private:
257 | uint16_t _port;
258 | public:
259 | EthernetServer(uint16_t port) : _port(port) { }
260 | EthernetClient available();
261 | EthernetClient accept();
262 | virtual void begin(uint16_t port = 80);
263 | virtual size_t write(uint8_t);
264 | virtual size_t write(const uint8_t *buf, size_t size);
265 | virtual operator bool();
266 | using Print::write;
267 | //void statusreport();
268 |
269 | // TODO: make private when socket allocation moves to EthernetClass
270 | static uint16_t server_port[MAX_SOCK_NUM];
271 | };
272 |
273 |
274 | class DhcpClass {
275 | private:
276 | uint32_t _dhcpInitialTransactionId;
277 | uint32_t _dhcpTransactionId;
278 | uint8_t _dhcpMacAddr[6];
279 | #ifdef __arm__
280 | uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
281 | uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
282 | uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4)));
283 | uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4)));
284 | uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4)));
285 | #else
286 | uint8_t _dhcpLocalIp[4];
287 | uint8_t _dhcpSubnetMask[4];
288 | uint8_t _dhcpGatewayIp[4];
289 | uint8_t _dhcpDhcpServerIp[4];
290 | uint8_t _dhcpDnsServerIp[4];
291 | #endif
292 | uint32_t _dhcpLeaseTime;
293 | uint32_t _dhcpT1, _dhcpT2;
294 | uint32_t _renewInSec;
295 | uint32_t _rebindInSec;
296 | unsigned long _timeout;
297 | unsigned long _responseTimeout;
298 | unsigned long _lastCheckLeaseMillis;
299 | uint8_t _dhcp_state;
300 | EthernetUDP _dhcpUdpSocket;
301 |
302 | int request_DHCP_lease();
303 | void reset_DHCP_lease();
304 | void presend_DHCP();
305 | void send_DHCP_MESSAGE(uint8_t, uint16_t);
306 | void printByte(char *, uint8_t);
307 |
308 | uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId);
309 | public:
310 | IPAddress getLocalIp();
311 | IPAddress getSubnetMask();
312 | IPAddress getGatewayIp();
313 | IPAddress getDhcpServerIp();
314 | IPAddress getDnsServerIp();
315 |
316 | int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
317 | int checkLease();
318 | };
319 |
320 |
321 |
322 |
323 |
324 | #endif
325 |
--------------------------------------------------------------------------------
/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 "M5_Ethernet.h"
13 | #include "w5100.h"
14 |
15 |
16 | /***************************************************/
17 | /** Default SS pin setting **/
18 | /***************************************************/
19 | #define SPI_HAS_TRANSFER_BUF
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)
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 | uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT;
56 | #ifdef ETHERNET_LARGE_BUFFERS
57 | uint16_t W5100Class::SSIZE = 2048;
58 | uint16_t W5100Class::SMASK = 0x07FF;
59 | #endif
60 | W5100Class W5100;
61 |
62 | // pointers and bitmasks for optimized SS pin
63 | #if defined(__AVR__)
64 | volatile uint8_t * W5100Class::ss_pin_reg;
65 | uint8_t W5100Class::ss_pin_mask;
66 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
67 | volatile uint8_t * W5100Class::ss_pin_reg;
68 | #elif defined(__MKL26Z64__)
69 | volatile uint8_t * W5100Class::ss_pin_reg;
70 | uint8_t W5100Class::ss_pin_mask;
71 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
72 | volatile uint32_t * W5100Class::ss_pin_reg;
73 | uint32_t W5100Class::ss_pin_mask;
74 | #elif defined(__PIC32MX__)
75 | volatile uint32_t * W5100Class::ss_pin_reg;
76 | uint32_t W5100Class::ss_pin_mask;
77 | #elif defined(ARDUINO_ARCH_ESP8266)
78 | volatile uint32_t * W5100Class::ss_pin_reg;
79 | uint32_t W5100Class::ss_pin_mask;
80 | #elif defined(__SAMD21G18A__)
81 | volatile uint32_t * W5100Class::ss_pin_reg;
82 | uint32_t W5100Class::ss_pin_mask;
83 | #endif
84 |
85 |
86 | uint8_t W5100Class::init(uint8_t force)
87 | {
88 | static bool initialized = false;
89 | uint8_t i;
90 |
91 | if (force == 0 && initialized) return 1;
92 |
93 | // Many Ethernet shields have a CAT811 or similar reset chip
94 | // connected to W5100 or W5200 chips. The W5200 will not work at
95 | // all, and may even drive its MISO pin, until given an active low
96 | // reset pulse! The CAT811 has a 240 ms typical pulse length, and
97 | // a 400 ms worst case maximum pulse length. MAX811 has a worst
98 | // case maximum 560 ms pulse length. This delay is meant to wait
99 | // until the reset pulse is ended. If your hardware has a shorter
100 | // reset time, this can be edited or removed.
101 | delay(20);
102 | //Serial.println("w5100 init");
103 |
104 | // SPI.begin();
105 | initSS();
106 | resetSS();
107 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
108 |
109 | // Attempt W5200 detection first, because W5200 does not properly
110 | // reset its SPI state when CS goes high (inactive). Communication
111 | // from detecting the other chips can leave the W5200 in a state
112 | // where it won't recover, unless given a reset pulse.
113 | if (isW5200()) {
114 | CH_BASE_MSB = 0x40;
115 | #ifdef ETHERNET_LARGE_BUFFERS
116 | #if MAX_SOCK_NUM <= 1
117 | SSIZE = 16384;
118 | #elif MAX_SOCK_NUM <= 2
119 | SSIZE = 8192;
120 | #elif MAX_SOCK_NUM <= 4
121 | SSIZE = 4096;
122 | #else
123 | SSIZE = 2048;
124 | #endif
125 | SMASK = SSIZE - 1;
126 | #endif
127 | for (i=0; i> 10);
129 | writeSnTX_SIZE(i, SSIZE >> 10);
130 | }
131 | for (; i<8; i++) {
132 | writeSnRX_SIZE(i, 0);
133 | writeSnTX_SIZE(i, 0);
134 | }
135 | // Try W5500 next. Wiznet finally seems to have implemented
136 | // SPI well with this chip. It appears to be very resilient,
137 | // so try it after the fragile W5200
138 | } else if (isW5500()) {
139 | CH_BASE_MSB = 0x10;
140 | #ifdef ETHERNET_LARGE_BUFFERS
141 | #if MAX_SOCK_NUM <= 1
142 | SSIZE = 16384;
143 | #elif MAX_SOCK_NUM <= 2
144 | SSIZE = 8192;
145 | #elif MAX_SOCK_NUM <= 4
146 | SSIZE = 4096;
147 | #else
148 | SSIZE = 2048;
149 | #endif
150 | SMASK = SSIZE - 1;
151 | for (i=0; i> 10);
153 | writeSnTX_SIZE(i, SSIZE >> 10);
154 | }
155 | for (; i<8; i++) {
156 | writeSnRX_SIZE(i, 0);
157 | writeSnTX_SIZE(i, 0);
158 | }
159 | #endif
160 | // Try W5100 last. This simple chip uses fixed 4 byte frames
161 | // for every 8 bit access. Terribly inefficient, but so simple
162 | // it recovers from "hearing" unsuccessful W5100 or W5200
163 | // communication. W5100 is also the only chip without a VERSIONR
164 | // register for identification, so we check this last.
165 | } else if (isW5100()) {
166 | CH_BASE_MSB = 0x04;
167 | #ifdef ETHERNET_LARGE_BUFFERS
168 | #if MAX_SOCK_NUM <= 1
169 | SSIZE = 8192;
170 | writeTMSR(0x03);
171 | writeRMSR(0x03);
172 | #elif MAX_SOCK_NUM <= 2
173 | SSIZE = 4096;
174 | writeTMSR(0x0A);
175 | writeRMSR(0x0A);
176 | #else
177 | SSIZE = 2048;
178 | writeTMSR(0x55);
179 | writeRMSR(0x55);
180 | #endif
181 | SMASK = SSIZE - 1;
182 | #else
183 | writeTMSR(0x55);
184 | writeRMSR(0x55);
185 | #endif
186 | // No hardware seems to be present. Or it could be a W5200
187 | // that's heard other SPI communication if its chip select
188 | // pin wasn't high when a SD card or other SPI chip was used.
189 | } else {
190 | //Serial.println("no chip :-(");
191 | chip = 0;
192 | SPI.endTransaction();
193 | return 0; // no known chip is responding :-(
194 | }
195 | SPI.endTransaction();
196 | initialized = true;
197 | return 1; // successful init
198 | }
199 |
200 | // Soft reset the Wiznet chip, by writing to its MR register reset bit
201 | uint8_t W5100Class::softReset(void)
202 | {
203 | uint16_t count=0;
204 |
205 | //Serial.println("Wiznet soft reset");
206 | // write to reset bit
207 | writeMR(0x80);
208 | // then wait for soft reset to complete
209 | do {
210 | uint8_t mr = readMR();
211 | //Serial.print("mr=");
212 | //Serial.println(mr, HEX);
213 | if (mr == 0) return 1;
214 | delay(1);
215 | } while (++count < 20);
216 | return 0;
217 | }
218 |
219 | uint8_t W5100Class::isW5100(void)
220 | {
221 | chip = 51;
222 | //Serial.println("w5100.cpp: detect W5100 chip");
223 | if (!softReset()) return 0;
224 | writeMR(0x10);
225 | if (readMR() != 0x10) return 0;
226 | writeMR(0x12);
227 | if (readMR() != 0x12) return 0;
228 | writeMR(0x00);
229 | if (readMR() != 0x00) return 0;
230 | //Serial.println("chip is W5100");
231 | return 1;
232 | }
233 |
234 | uint8_t W5100Class::isW5200(void)
235 | {
236 | chip = 52;
237 | //Serial.println("w5100.cpp: detect W5200 chip");
238 | if (!softReset()) return 0;
239 | writeMR(0x08);
240 | if (readMR() != 0x08) return 0;
241 | writeMR(0x10);
242 | if (readMR() != 0x10) return 0;
243 | writeMR(0x00);
244 | if (readMR() != 0x00) return 0;
245 | int ver = readVERSIONR_W5200();
246 | //Serial.print("version=");
247 | //Serial.println(ver);
248 | if (ver != 3) return 0;
249 | //Serial.println("chip is W5200");
250 | return 1;
251 | }
252 |
253 | uint8_t W5100Class::isW5500(void)
254 | {
255 | chip = 55;
256 | //Serial.println("w5100.cpp: detect W5500 chip");
257 | if (!softReset()) return 0;
258 | writeMR(0x08);
259 | if (readMR() != 0x08) return 0;
260 | writeMR(0x10);
261 | if (readMR() != 0x10) return 0;
262 | writeMR(0x00);
263 | if (readMR() != 0x00) return 0;
264 | int ver = readVERSIONR_W5500();
265 | //Serial.print("version=");
266 | //Serial.println(ver);
267 | if (ver != 4) return 0;
268 | //Serial.println("chip is W5500");
269 | return 1;
270 | }
271 |
272 | W5100Linkstatus W5100Class::getLinkStatus()
273 | {
274 | uint8_t phystatus;
275 |
276 | if (!init()) return UNKNOWN;
277 | switch (chip) {
278 | case 52:
279 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
280 | phystatus = readPSTATUS_W5200();
281 | SPI.endTransaction();
282 | if (phystatus & 0x20) return LINK_ON;
283 | return LINK_OFF;
284 | case 55:
285 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
286 | phystatus = readPHYCFGR_W5500();
287 | SPI.endTransaction();
288 | if (phystatus & 0x01) return LINK_ON;
289 | return LINK_OFF;
290 | default:
291 | return UNKNOWN;
292 | }
293 | }
294 |
295 | uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len)
296 | {
297 | uint8_t cmd[8];
298 |
299 | if (chip == 51) {
300 | for (uint16_t i=0; i> 8);
304 | SPI.transfer(addr & 0xFF);
305 | addr++;
306 | SPI.transfer(buf[i]);
307 | resetSS();
308 | }
309 | } else if (chip == 52) {
310 | setSS();
311 | cmd[0] = addr >> 8;
312 | cmd[1] = addr & 0xFF;
313 | cmd[2] = ((len >> 8) & 0x7F) | 0x80;
314 | cmd[3] = len & 0xFF;
315 | SPI.transfer(cmd, 4);
316 | #ifdef SPI_HAS_TRANSFER_BUF
317 | SPI.transferBytes(buf, NULL, len);
318 | #else
319 | // TODO: copy 8 bytes at a time to cmd[] and block transfer
320 | for (uint16_t i=0; i < len; i++) {
321 | SPI.transfer(buf[i]);
322 | }
323 | #endif
324 | resetSS();
325 | } else { // chip == 55
326 | setSS();
327 | if (addr < 0x100) {
328 | // common registers 00nn
329 | cmd[0] = 0;
330 | cmd[1] = addr & 0xFF;
331 | cmd[2] = 0x04;
332 | } else if (addr < 0x8000) {
333 | // socket registers 10nn, 11nn, 12nn, 13nn, etc
334 | cmd[0] = 0;
335 | cmd[1] = addr & 0xFF;
336 | cmd[2] = ((addr >> 3) & 0xE0) | 0x0C;
337 | } else if (addr < 0xC000) {
338 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
339 | // 10## #nnn nnnn nnnn
340 | cmd[0] = addr >> 8;
341 | cmd[1] = addr & 0xFF;
342 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
343 | cmd[2] = 0x14; // 16K buffers
344 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
345 | cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers
346 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
347 | cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers
348 | #else
349 | cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers
350 | #endif
351 | } else {
352 | // receive buffers
353 | cmd[0] = addr >> 8;
354 | cmd[1] = addr & 0xFF;
355 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
356 | cmd[2] = 0x1C; // 16K buffers
357 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
358 | cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers
359 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
360 | cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers
361 | #else
362 | cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers
363 | #endif
364 | }
365 | if (len <= 5) {
366 | for (uint8_t i=0; i < len; i++) {
367 | cmd[i + 3] = buf[i];
368 | }
369 | SPI.transfer(cmd, len + 3);
370 | } else {
371 | SPI.transfer(cmd, 3);
372 | #ifdef SPI_HAS_TRANSFER_BUF
373 | SPI.transferBytes(buf, NULL, len);
374 | #else
375 | // TODO: copy 8 bytes at a time to cmd[] and block transfer
376 | for (uint16_t i=0; i < len; i++) {
377 | SPI.transfer(buf[i]);
378 | }
379 | #endif
380 | }
381 | resetSS();
382 | }
383 | return len;
384 | }
385 |
386 | uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len)
387 | {
388 | uint8_t cmd[4];
389 |
390 | if (chip == 51) {
391 | for (uint16_t i=0; i < len; i++) {
392 | setSS();
393 | #if 1
394 | SPI.transfer(0x0F);
395 | SPI.transfer(addr >> 8);
396 | SPI.transfer(addr & 0xFF);
397 | addr++;
398 | buf[i] = SPI.transfer(0);
399 | #else
400 | cmd[0] = 0x0F;
401 | cmd[1] = addr >> 8;
402 | cmd[2] = addr & 0xFF;
403 | cmd[3] = 0;
404 | SPI.transfer(cmd, 4); // TODO: why doesn't this work?
405 | buf[i] = cmd[3];
406 | addr++;
407 | #endif
408 | resetSS();
409 | }
410 | } else if (chip == 52) {
411 | setSS();
412 | cmd[0] = addr >> 8;
413 | cmd[1] = addr & 0xFF;
414 | cmd[2] = (len >> 8) & 0x7F;
415 | cmd[3] = len & 0xFF;
416 | SPI.transfer(cmd, 4);
417 | memset(buf, 0, len);
418 | SPI.transfer(buf, len);
419 | resetSS();
420 | } else { // chip == 55
421 | setSS();
422 | if (addr < 0x100) {
423 | // common registers 00nn
424 | cmd[0] = 0;
425 | cmd[1] = addr & 0xFF;
426 | cmd[2] = 0x00;
427 | } else if (addr < 0x8000) {
428 | // socket registers 10nn, 11nn, 12nn, 13nn, etc
429 | cmd[0] = 0;
430 | cmd[1] = addr & 0xFF;
431 | cmd[2] = ((addr >> 3) & 0xE0) | 0x08;
432 | } else if (addr < 0xC000) {
433 | // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc
434 | // 10## #nnn nnnn nnnn
435 | cmd[0] = addr >> 8;
436 | cmd[1] = addr & 0xFF;
437 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
438 | cmd[2] = 0x10; // 16K buffers
439 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
440 | cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers
441 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
442 | cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers
443 | #else
444 | cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers
445 | #endif
446 | } else {
447 | // receive buffers
448 | cmd[0] = addr >> 8;
449 | cmd[1] = addr & 0xFF;
450 | #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1
451 | cmd[2] = 0x18; // 16K buffers
452 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2
453 | cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers
454 | #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4
455 | cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers
456 | #else
457 | cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers
458 | #endif
459 | }
460 | SPI.transfer(cmd, 3);
461 | for (uint16_t i=0; i
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(26000000, MSBFIRST, SPI_MODE0)
22 | #define SPI_ETHERNET_40_SETTINGS SPISettings(40000000, MSBFIRST, SPI_MODE0)
23 |
24 | // Safe for W5200 and W5500, but too fast for W5100
25 | // Uncomment this if you know you'll never need W5100 support.
26 | // Higher SPI clock only results in faster transfer to hosts on a LAN
27 | // or with very low packet latency. With ordinary internet latency,
28 | // the TCP window size & packet loss determine your overall speed.
29 | //#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0)
30 |
31 |
32 | // Require M5_Ethernet.h, because we need MAX_SOCK_NUM
33 | #ifndef ethernet_h_
34 | #error "M5_Ethernet.h must be included before w5100.h"
35 | #endif
36 |
37 |
38 | // Arduino 101's SPI can not run faster than 8 MHz.
39 | #if defined(ARDUINO_ARCH_ARC32)
40 | #undef SPI_ETHERNET_SETTINGS
41 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
42 | #endif
43 |
44 | // Arduino Zero can't use W5100-based shields faster than 8 MHz
45 | // https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848
46 | // W5500 does seem to work at 12 MHz. Delete this if only using W5500
47 | #if defined(__SAMD21G18A__)
48 | #undef SPI_ETHERNET_SETTINGS
49 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0)
50 | #endif
51 |
52 |
53 | typedef uint8_t SOCKET;
54 |
55 | class SnMR {
56 | public:
57 | static const uint8_t CLOSE = 0x00;
58 | static const uint8_t TCP = 0x21;
59 | static const uint8_t UDP = 0x02;
60 | static const uint8_t IPRAW = 0x03;
61 | static const uint8_t MACRAW = 0x04;
62 | static const uint8_t PPPOE = 0x05;
63 | static const uint8_t ND = 0x20;
64 | static const uint8_t MULTI = 0x80;
65 | };
66 |
67 | enum SockCMD {
68 | Sock_OPEN = 0x01,
69 | Sock_LISTEN = 0x02,
70 | Sock_CONNECT = 0x04,
71 | Sock_DISCON = 0x08,
72 | Sock_CLOSE = 0x10,
73 | Sock_SEND = 0x20,
74 | Sock_SEND_MAC = 0x21,
75 | Sock_SEND_KEEP = 0x22,
76 | Sock_RECV = 0x40
77 | };
78 |
79 | class SnIR {
80 | public:
81 | static const uint8_t SEND_OK = 0x10;
82 | static const uint8_t TIMEOUT = 0x08;
83 | static const uint8_t RECV = 0x04;
84 | static const uint8_t DISCON = 0x02;
85 | static const uint8_t CON = 0x01;
86 | };
87 |
88 | class SnSR {
89 | public:
90 | static const uint8_t CLOSED = 0x00;
91 | static const uint8_t INIT = 0x13;
92 | static const uint8_t LISTEN = 0x14;
93 | static const uint8_t SYNSENT = 0x15;
94 | static const uint8_t SYNRECV = 0x16;
95 | static const uint8_t ESTABLISHED = 0x17;
96 | static const uint8_t FIN_WAIT = 0x18;
97 | static const uint8_t CLOSING = 0x1A;
98 | static const uint8_t TIME_WAIT = 0x1B;
99 | static const uint8_t CLOSE_WAIT = 0x1C;
100 | static const uint8_t LAST_ACK = 0x1D;
101 | static const uint8_t UDP = 0x22;
102 | static const uint8_t IPRAW = 0x32;
103 | static const uint8_t MACRAW = 0x42;
104 | static const uint8_t PPPOE = 0x5F;
105 | };
106 |
107 | class IPPROTO {
108 | public:
109 | static const uint8_t IP = 0;
110 | static const uint8_t ICMP = 1;
111 | static const uint8_t IGMP = 2;
112 | static const uint8_t GGP = 3;
113 | static const uint8_t TCP = 6;
114 | static const uint8_t PUP = 12;
115 | static const uint8_t UDP = 17;
116 | static const uint8_t IDP = 22;
117 | static const uint8_t ND = 77;
118 | static const uint8_t RAW = 255;
119 | };
120 |
121 | enum W5100Linkstatus {
122 | UNKNOWN,
123 | LINK_ON,
124 | LINK_OFF
125 | };
126 |
127 | class W5100Class {
128 |
129 | public:
130 | static uint8_t init(uint8_t force=0);
131 |
132 | inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); }
133 | inline void getGatewayIp(uint8_t * addr) { readGAR(addr); }
134 |
135 | inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); }
136 | inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); }
137 |
138 | inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); }
139 | inline void getMACAddress(uint8_t * addr) { readSHAR(addr); }
140 |
141 | inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); }
142 | inline void getIPAddress(uint8_t * addr) { readSIPR(addr); }
143 |
144 | inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); }
145 | inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); }
146 |
147 | static void execCmdSn(SOCKET s, SockCMD _cmd);
148 |
149 |
150 | // W5100 Registers
151 | // ---------------
152 | //private:
153 | public:
154 | static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len);
155 | static uint8_t write(uint16_t addr, uint8_t data) {
156 | return write(addr, &data, 1);
157 | }
158 | static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len);
159 | static uint8_t read(uint16_t addr) {
160 | uint8_t data;
161 | read(addr, &data, 1);
162 | return data;
163 | }
164 |
165 | #define __GP_REGISTER8(name, address) \
166 | static inline void write##name(uint8_t _data) { \
167 | write(address, _data); \
168 | } \
169 | static inline uint8_t read##name() { \
170 | return read(address); \
171 | }
172 | #define __GP_REGISTER16(name, address) \
173 | static void write##name(uint16_t _data) { \
174 | uint8_t buf[2]; \
175 | buf[0] = _data >> 8; \
176 | buf[1] = _data & 0xFF; \
177 | write(address, buf, 2); \
178 | } \
179 | static uint16_t read##name() { \
180 | uint8_t buf[2]; \
181 | read(address, buf, 2); \
182 | return (buf[0] << 8) | buf[1]; \
183 | }
184 | #define __GP_REGISTER_N(name, address, size) \
185 | static uint16_t write##name(const uint8_t *_buff) { \
186 | return write(address, _buff, size); \
187 | } \
188 | static uint16_t read##name(uint8_t *_buff) { \
189 | return read(address, _buff, size); \
190 | }
191 | static W5100Linkstatus getLinkStatus();
192 |
193 | public:
194 | __GP_REGISTER8 (MR, 0x0000); // Mode
195 | __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address
196 | __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address
197 | __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address
198 | __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address
199 | __GP_REGISTER8 (IR, 0x0015); // Interrupt
200 | __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask
201 | __GP_REGISTER16(RTR, 0x0017); // Timeout address
202 | __GP_REGISTER8 (RCR, 0x0019); // Retry count
203 | __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only)
204 | __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only)
205 | __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode
206 | __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer
207 | __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number
208 | __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only)
209 | __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only)
210 | __GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only)
211 | __GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only)
212 | __GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status
213 | __GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx
214 |
215 |
216 | #undef __GP_REGISTER8
217 | #undef __GP_REGISTER16
218 | #undef __GP_REGISTER_N
219 |
220 | // W5100 Socket registers
221 | // ----------------------
222 | private:
223 | static uint16_t CH_BASE(void) {
224 | //if (chip == 55) return 0x1000;
225 | //if (chip == 52) return 0x4000;
226 | //return 0x0400;
227 | return CH_BASE_MSB << 8;
228 | }
229 | static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR
230 | static const uint16_t CH_SIZE = 0x0100;
231 |
232 | static inline uint8_t readSn(SOCKET s, uint16_t addr) {
233 | return read(CH_BASE() + s * CH_SIZE + addr);
234 | }
235 | static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) {
236 | return write(CH_BASE() + s * CH_SIZE + addr, data);
237 | }
238 | static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
239 | return read(CH_BASE() + s * CH_SIZE + addr, buf, len);
240 | }
241 | static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) {
242 | return write(CH_BASE() + s * CH_SIZE + addr, buf, len);
243 | }
244 |
245 | #define __SOCKET_REGISTER8(name, address) \
246 | static inline void write##name(SOCKET _s, uint8_t _data) { \
247 | writeSn(_s, address, _data); \
248 | } \
249 | static inline uint8_t read##name(SOCKET _s) { \
250 | return readSn(_s, address); \
251 | }
252 | #define __SOCKET_REGISTER16(name, address) \
253 | static void write##name(SOCKET _s, uint16_t _data) { \
254 | uint8_t buf[2]; \
255 | buf[0] = _data >> 8; \
256 | buf[1] = _data & 0xFF; \
257 | writeSn(_s, address, buf, 2); \
258 | } \
259 | static uint16_t read##name(SOCKET _s) { \
260 | uint8_t buf[2]; \
261 | readSn(_s, address, buf, 2); \
262 | return (buf[0] << 8) | buf[1]; \
263 | }
264 | #define __SOCKET_REGISTER_N(name, address, size) \
265 | static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \
266 | return writeSn(_s, address, _buff, size); \
267 | } \
268 | static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \
269 | return readSn(_s, address, _buff, size); \
270 | }
271 |
272 | public:
273 | __SOCKET_REGISTER8(SnMR, 0x0000) // Mode
274 | __SOCKET_REGISTER8(SnCR, 0x0001) // Command
275 | __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt
276 | __SOCKET_REGISTER8(SnSR, 0x0003) // Status
277 | __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port
278 | __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr
279 | __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr
280 | __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port
281 | __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size
282 | __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode
283 | __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS
284 | __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL
285 | __SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only)
286 | __SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only)
287 | __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size
288 | __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer
289 | __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer
290 | __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size
291 | __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer
292 | __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?)
293 |
294 | #undef __SOCKET_REGISTER8
295 | #undef __SOCKET_REGISTER16
296 | #undef __SOCKET_REGISTER_N
297 |
298 |
299 | private:
300 | static uint8_t chip;
301 | static uint8_t ss_pin;
302 | static uint8_t softReset(void);
303 | static uint8_t isW5100(void);
304 | static uint8_t isW5200(void);
305 | static uint8_t isW5500(void);
306 |
307 | public:
308 | static uint8_t getChip(void) { return chip; }
309 | #ifdef ETHERNET_LARGE_BUFFERS
310 | static uint16_t SSIZE;
311 | static uint16_t SMASK;
312 | #else
313 | static const uint16_t SSIZE = 2048;
314 | static const uint16_t SMASK = 0x07FF;
315 | #endif
316 | static uint16_t SBASE(uint8_t socknum) {
317 | if (chip == 51) {
318 | return socknum * SSIZE + 0x4000;
319 | } else {
320 | return socknum * SSIZE + 0x8000;
321 | }
322 | }
323 | static uint16_t RBASE(uint8_t socknum) {
324 | if (chip == 51) {
325 | return socknum * SSIZE + 0x6000;
326 | } else {
327 | return socknum * SSIZE + 0xC000;
328 | }
329 | }
330 |
331 | static bool hasOffsetAddressMapping(void) {
332 | if (chip == 55) return true;
333 | return false;
334 | }
335 | static void setSS(uint8_t pin) { ss_pin = pin; }
336 |
337 | private:
338 | #if defined(__AVR__)
339 | static volatile uint8_t *ss_pin_reg;
340 | static uint8_t ss_pin_mask;
341 | inline static void initSS() {
342 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
343 | ss_pin_mask = digitalPinToBitMask(ss_pin);
344 | pinMode(ss_pin, OUTPUT);
345 | }
346 | inline static void setSS() {
347 | *(ss_pin_reg) &= ~ss_pin_mask;
348 | }
349 | inline static void resetSS() {
350 | *(ss_pin_reg) |= ss_pin_mask;
351 | }
352 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__)
353 | static volatile uint8_t *ss_pin_reg;
354 | inline static void initSS() {
355 | ss_pin_reg = portOutputRegister(ss_pin);
356 | pinMode(ss_pin, OUTPUT);
357 | }
358 | inline static void setSS() {
359 | *(ss_pin_reg+256) = 1;
360 | }
361 | inline static void resetSS() {
362 | *(ss_pin_reg+128) = 1;
363 | }
364 | #elif defined(__MKL26Z64__)
365 | static volatile uint8_t *ss_pin_reg;
366 | static uint8_t ss_pin_mask;
367 | inline static void initSS() {
368 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin));
369 | ss_pin_mask = digitalPinToBitMask(ss_pin);
370 | pinMode(ss_pin, OUTPUT);
371 | }
372 | inline static void setSS() {
373 | *(ss_pin_reg+8) = ss_pin_mask;
374 | }
375 | inline static void resetSS() {
376 | *(ss_pin_reg+4) = ss_pin_mask;
377 | }
378 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__)
379 | static volatile uint32_t *ss_pin_reg;
380 | static uint32_t ss_pin_mask;
381 | inline static void initSS() {
382 | ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER);
383 | ss_pin_mask = digitalPinToBitMask(ss_pin);
384 | pinMode(ss_pin, OUTPUT);
385 | }
386 | inline static void setSS() {
387 | *(ss_pin_reg+13) = ss_pin_mask;
388 | }
389 | inline static void resetSS() {
390 | *(ss_pin_reg+12) = ss_pin_mask;
391 | }
392 | #elif defined(__PIC32MX__)
393 | static volatile uint32_t *ss_pin_reg;
394 | static uint32_t ss_pin_mask;
395 | inline static void initSS() {
396 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
397 | ss_pin_mask = digitalPinToBitMask(ss_pin);
398 | pinMode(ss_pin, OUTPUT);
399 | }
400 | inline static void setSS() {
401 | *(ss_pin_reg+8+1) = ss_pin_mask;
402 | }
403 | inline static void resetSS() {
404 | *(ss_pin_reg+8+2) = ss_pin_mask;
405 | }
406 |
407 | #elif defined(ARDUINO_ARCH_ESP8266)
408 | static volatile uint32_t *ss_pin_reg;
409 | static uint32_t ss_pin_mask;
410 | inline static void initSS() {
411 | ss_pin_reg = (volatile uint32_t*)GPO;
412 | ss_pin_mask = 1 << ss_pin;
413 | pinMode(ss_pin, OUTPUT);
414 | }
415 | inline static void setSS() {
416 | GPOC = ss_pin_mask;
417 | }
418 | inline static void resetSS() {
419 | GPOS = ss_pin_mask;
420 | }
421 |
422 | #elif defined(__SAMD21G18A__)
423 | static volatile uint32_t *ss_pin_reg;
424 | static uint32_t ss_pin_mask;
425 | inline static void initSS() {
426 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin));
427 | ss_pin_mask = digitalPinToBitMask(ss_pin);
428 | pinMode(ss_pin, OUTPUT);
429 | }
430 | inline static void setSS() {
431 | *(ss_pin_reg+5) = ss_pin_mask;
432 | }
433 | inline static void resetSS() {
434 | *(ss_pin_reg+6) = ss_pin_mask;
435 | }
436 | #else
437 | inline static void initSS() {
438 | pinMode(ss_pin, OUTPUT);
439 | }
440 | inline static void setSS() {
441 | digitalWrite(ss_pin, LOW);
442 | }
443 | inline static void resetSS() {
444 | digitalWrite(ss_pin, HIGH);
445 | }
446 | #endif
447 | };
448 |
449 | extern W5100Class W5100;
450 |
451 |
452 |
453 | #endif
454 |
455 | #ifndef UTIL_H
456 | #define UTIL_H
457 |
458 | #define htons(x) ( (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) )
459 | #define ntohs(x) htons(x)
460 |
461 | #define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
462 | ((x)<< 8 & 0x00FF0000UL) | \
463 | ((x)>> 8 & 0x0000FF00UL) | \
464 | ((x)>>24 & 0x000000FFUL) )
465 | #define ntohl(x) htonl(x)
466 |
467 | #endif
468 |
--------------------------------------------------------------------------------
/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 "M5_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) 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) 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 | // SPI.setFrequency(30000000);
405 | SPI.endTransaction();
406 | SPI.beginTransaction(SPI_ETHERNET_40_SETTINGS);
407 |
408 | if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) {
409 | W5100.write(dstAddr, data, len);
410 | } else {
411 | // Wrap around circular buffer
412 | uint16_t size = W5100.SSIZE - offset;
413 | W5100.write(dstAddr, data, size);
414 | W5100.write(W5100.SBASE(s), data + size, len - size);
415 | }
416 | ptr += len;
417 | W5100.writeSnTX_WR(s, ptr);
418 | }
419 |
420 |
421 | /**
422 | * @brief This function used to send the data in TCP mode
423 | * @return 1 for success else 0.
424 | */
425 | uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len)
426 | {
427 | uint8_t status=0;
428 | uint16_t ret=0;
429 | uint16_t freesize=0;
430 |
431 | if (len > W5100.SSIZE) {
432 | ret = W5100.SSIZE; // check size not to exceed MAX size.
433 | } else {
434 | ret = len;
435 | }
436 |
437 | // if freebuf is available, start.
438 | do {
439 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
440 | freesize = getSnTX_FSR(s);
441 | status = W5100.readSnSR(s);
442 | SPI.endTransaction();
443 | if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) {
444 | ret = 0;
445 | break;
446 | }
447 | yield();
448 | } while (freesize < ret);
449 |
450 | // copy data
451 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
452 | write_data(s, 0, (uint8_t *)buf, ret);
453 | W5100.execCmdSn(s, Sock_SEND);
454 |
455 | /* +2008.01 bj */
456 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
457 | /* m2008.01 [bj] : reduce code */
458 | if ( W5100.readSnSR(s) == SnSR::CLOSED ) {
459 | SPI.endTransaction();
460 | return 0;
461 | }
462 | SPI.endTransaction();
463 | yield();
464 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
465 | }
466 | /* +2008.01 bj */
467 | W5100.writeSnIR(s, SnIR::SEND_OK);
468 | SPI.endTransaction();
469 | return ret;
470 | }
471 |
472 | uint16_t EthernetClass::socketSendAvailable(uint8_t s)
473 | {
474 | uint8_t status=0;
475 | uint16_t freesize=0;
476 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
477 | freesize = getSnTX_FSR(s);
478 | status = W5100.readSnSR(s);
479 | SPI.endTransaction();
480 | if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) {
481 | return freesize;
482 | }
483 | return 0;
484 | }
485 |
486 | uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len)
487 | {
488 | //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len);
489 | uint16_t ret =0;
490 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
491 | uint16_t txfree = getSnTX_FSR(s);
492 | if (len > txfree) {
493 | ret = txfree; // check size not to exceed MAX size.
494 | } else {
495 | ret = len;
496 | }
497 | write_data(s, offset, buf, ret);
498 | SPI.endTransaction();
499 | return ret;
500 | }
501 |
502 | bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port)
503 | {
504 | if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
505 | ((port == 0x00)) ) {
506 | return false;
507 | }
508 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
509 | W5100.writeSnDIPR(s, addr);
510 | W5100.writeSnDPORT(s, port);
511 | SPI.endTransaction();
512 | return true;
513 | }
514 |
515 | bool EthernetClass::socketSendUDP(uint8_t s)
516 | {
517 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
518 | W5100.execCmdSn(s, Sock_SEND);
519 |
520 | /* +2008.01 bj */
521 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) {
522 | if (W5100.readSnIR(s) & SnIR::TIMEOUT) {
523 | /* +2008.01 [bj]: clear interrupt */
524 | W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT));
525 | SPI.endTransaction();
526 | //Serial.printf("sendUDP timeout\n");
527 | return false;
528 | }
529 | SPI.endTransaction();
530 | yield();
531 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
532 | }
533 |
534 | /* +2008.01 bj */
535 | W5100.writeSnIR(s, SnIR::SEND_OK);
536 | SPI.endTransaction();
537 |
538 | //Serial.printf("sendUDP ok\n");
539 | /* Sent ok */
540 | return true;
541 | }
542 |
543 |
--------------------------------------------------------------------------------