├── .codespellrc ├── .github ├── dependabot.yml └── workflows │ ├── check-arduino.yml │ ├── compile-examples.yml │ ├── report-size-deltas.yml │ ├── spell-check.yml │ └── sync-labels.yml ├── AUTHORS ├── README.adoc ├── docs ├── api.md ├── arduino_mega_ethernet_pins.png ├── arduino_uno_ethernet_pins.png └── readme.md ├── examples ├── AdvancedChatServer │ └── AdvancedChatServer.ino ├── BarometricPressureWebServer │ └── BarometricPressureWebServer.ino ├── ChatServer │ └── ChatServer.ino ├── DhcpAddressPrinter │ └── DhcpAddressPrinter.ino ├── DhcpChatServer │ └── DhcpChatServer.ino ├── LinkStatus │ └── LinkStatus.ino ├── PagerServer │ └── PagerServer.ino ├── TelnetClient │ └── TelnetClient.ino ├── UDPSendReceiveString │ └── UDPSendReceiveString.ino ├── UdpNtpClient │ └── UdpNtpClient.ino ├── WebClient │ └── WebClient.ino ├── WebClientRepeating │ └── WebClientRepeating.ino └── WebServer │ └── WebServer.ino ├── keywords.txt ├── library.properties └── src ├── Dhcp.cpp ├── Dhcp.h ├── Dns.cpp ├── Dns.h ├── Ethernet.cpp ├── Ethernet.h ├── EthernetClient.cpp ├── EthernetClient.h ├── EthernetServer.cpp ├── EthernetServer.h ├── EthernetUdp.cpp ├── EthernetUdp.h ├── socket.cpp └── utility ├── w5100.cpp └── w5100.h /.codespellrc: -------------------------------------------------------------------------------- 1 | # See: https://github.com/codespell-project/codespell#using-a-config-file 2 | [codespell] 3 | # In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: 4 | ignore-words-list = nd, 5 | check-filenames = 6 | check-hidden = 7 | skip = ./.git 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # See: https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#about-the-dependabotyml-file 2 | version: 2 3 | 4 | updates: 5 | # Configure check for outdated GitHub Actions actions in workflows. 6 | # See: https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot 7 | - package-ecosystem: github-actions 8 | directory: / # Check the repository's workflows under /.github/workflows/ 9 | schedule: 10 | interval: daily 11 | -------------------------------------------------------------------------------- /.github/workflows/check-arduino.yml: -------------------------------------------------------------------------------- 1 | name: Check Arduino 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | pull_request: 7 | schedule: 8 | # Run every Tuesday at 8 AM UTC to catch breakage caused by new rules added to Arduino Lint. 9 | - cron: "0 8 * * TUE" 10 | workflow_dispatch: 11 | repository_dispatch: 12 | 13 | jobs: 14 | lint: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Arduino Lint 22 | uses: arduino/arduino-lint-action@v2 23 | with: 24 | compliance: specification 25 | library-manager: update 26 | # Always use this setting for official repositories. Remove for 3rd party projects. 27 | official: true 28 | project-type: library 29 | -------------------------------------------------------------------------------- /.github/workflows/compile-examples.yml: -------------------------------------------------------------------------------- 1 | name: Compile Examples 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | paths: 7 | - ".github/workflows/compile-examples.yml" 8 | - "examples/**" 9 | - "src/**" 10 | pull_request: 11 | paths: 12 | - ".github/workflows/compile-examples.yml" 13 | - "examples/**" 14 | - "src/**" 15 | schedule: 16 | # Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms). 17 | - cron: "0 8 * * TUE" 18 | workflow_dispatch: 19 | repository_dispatch: 20 | 21 | jobs: 22 | build: 23 | name: ${{ matrix.board.fqbn }} 24 | runs-on: ubuntu-latest 25 | 26 | env: 27 | SKETCHES_REPORTS_PATH: sketches-reports 28 | 29 | strategy: 30 | fail-fast: false 31 | 32 | matrix: 33 | board: 34 | - fqbn: arduino:avr:nano 35 | platforms: | 36 | - name: arduino:avr 37 | artifact-name-suffix: arduino-avr-nano 38 | - fqbn: arduino:avr:mega 39 | platforms: | 40 | - name: arduino:avr 41 | artifact-name-suffix: arduino-avr-mega 42 | - fqbn: arduino:avr:leonardo 43 | platforms: | 44 | - name: arduino:avr 45 | artifact-name-suffix: arduino-avr-leonardo 46 | - fqbn: arduino:megaavr:uno2018 47 | platforms: | 48 | - name: arduino:megaavr 49 | artifact-name-suffix: arduino-megaavr-uno2018 50 | - fqbn: arduino:megaavr:nona4809 51 | platforms: | 52 | - name: arduino:megaavr 53 | artifact-name-suffix: arduino-megaavr-nona4809 54 | - fqbn: arduino:sam:arduino_due_x_dbg 55 | platforms: | 56 | - name: arduino:sam 57 | artifact-name-suffix: arduino-sam-arduino_due_x_dbg 58 | - fqbn: arduino:samd:arduino_zero_edbg 59 | platforms: | 60 | - name: arduino:samd 61 | artifact-name-suffix: arduino-samd-arduino_zero_edbg 62 | - fqbn: arduino:samd:mkr1000 63 | platforms: | 64 | - name: arduino:samd 65 | artifact-name-suffix: arduino-samd-mkr1000 66 | - fqbn: arduino:samd:mkrzero 67 | platforms: | 68 | - name: arduino:samd 69 | artifact-name-suffix: arduino-samd-mkrzero 70 | - fqbn: arduino:samd:mkrwifi1010 71 | platforms: | 72 | - name: arduino:samd 73 | artifact-name-suffix: arduino-samd-mkrwifi100 74 | - fqbn: arduino:samd:mkrfox1200 75 | platforms: | 76 | - name: arduino:samd 77 | artifact-name-suffix: arduino-samd-mkr1200 78 | - fqbn: arduino:samd:mkrwan1300 79 | platforms: | 80 | - name: arduino:samd 81 | artifact-name-suffix: arduino-samd-mkrwan1300 82 | - fqbn: arduino:samd:mkrwan1310 83 | platforms: | 84 | - name: arduino:samd 85 | artifact-name-suffix: arduino-samd-mkrwan1310 86 | - fqbn: arduino:samd:mkrgsm1400 87 | platforms: | 88 | - name: arduino:samd 89 | artifact-name-suffix: arduino-samd-mkrgsm1400 90 | - fqbn: arduino:samd:mkrnb1500 91 | platforms: | 92 | - name: arduino:samd 93 | artifact-name-suffix: arduino-samd-mkrnb1500 94 | - fqbn: arduino:samd:mkrvidor4000 95 | platforms: | 96 | - name: arduino:samd 97 | artifact-name-suffix: arduino-samd-mkrvidor4000 98 | - fqbn: arduino:samd:nano_33_iot 99 | platforms: | 100 | - name: arduino:samd 101 | artifact-name-suffix: arduino-samd-nano_33_iot 102 | 103 | steps: 104 | - name: Checkout repository 105 | uses: actions/checkout@v4 106 | 107 | - name: Compile examples 108 | uses: arduino/compile-sketches@v1 109 | with: 110 | github-token: ${{ secrets.GITHUB_TOKEN }} 111 | fqbn: ${{ matrix.board.fqbn }} 112 | platforms: ${{ matrix.board.platforms }} 113 | libraries: | 114 | # Install the library from the local path. 115 | - source-path: ./ 116 | # Additional library dependencies can be listed here. 117 | # See: https://github.com/arduino/compile-sketches#libraries 118 | sketch-paths: | 119 | - examples 120 | enable-deltas-report: true 121 | sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }} 122 | 123 | - name: Save sketches report as workflow artifact 124 | uses: actions/upload-artifact@v4 125 | with: 126 | if-no-files-found: error 127 | path: ${{ env.SKETCHES_REPORTS_PATH }} 128 | name: sketches-report-${{ matrix.board.artifact-name-suffix }} 129 | -------------------------------------------------------------------------------- /.github/workflows/report-size-deltas.yml: -------------------------------------------------------------------------------- 1 | name: Report Size Deltas 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | paths: 7 | - ".github/workflows/report-size-deltas.yml" 8 | schedule: 9 | # Run at the minimum interval allowed by GitHub Actions. 10 | # Note: GitHub Actions periodically has outages which result in workflow failures. 11 | # In this event, the workflows will start passing again once the service recovers. 12 | - cron: "*/5 * * * *" 13 | workflow_dispatch: 14 | repository_dispatch: 15 | 16 | jobs: 17 | report: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Comment size deltas reports to PRs 21 | uses: arduino/report-size-deltas@v1 22 | with: 23 | # Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow 24 | sketches-reports-source: ^sketches-report-.+ 25 | -------------------------------------------------------------------------------- /.github/workflows/spell-check.yml: -------------------------------------------------------------------------------- 1 | name: Spell Check 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | pull_request: 7 | schedule: 8 | # Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates. 9 | - cron: "0 8 * * TUE" 10 | workflow_dispatch: 11 | repository_dispatch: 12 | 13 | jobs: 14 | spellcheck: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Spell check 22 | uses: codespell-project/actions-codespell@master 23 | -------------------------------------------------------------------------------- /.github/workflows/sync-labels.yml: -------------------------------------------------------------------------------- 1 | # Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md 2 | name: Sync Labels 3 | 4 | # See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows 5 | on: 6 | push: 7 | paths: 8 | - ".github/workflows/sync-labels.ya?ml" 9 | - ".github/label-configuration-files/*.ya?ml" 10 | pull_request: 11 | paths: 12 | - ".github/workflows/sync-labels.ya?ml" 13 | - ".github/label-configuration-files/*.ya?ml" 14 | schedule: 15 | # Run daily at 8 AM UTC to sync with changes to shared label configurations. 16 | - cron: "0 8 * * *" 17 | workflow_dispatch: 18 | repository_dispatch: 19 | 20 | env: 21 | CONFIGURATIONS_FOLDER: .github/label-configuration-files 22 | CONFIGURATIONS_ARTIFACT: label-configuration-files 23 | 24 | jobs: 25 | check: 26 | runs-on: ubuntu-latest 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | 32 | - name: Download JSON schema for labels configuration file 33 | id: download-schema 34 | uses: carlosperate/download-file-action@v2 35 | with: 36 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json 37 | location: ${{ runner.temp }}/label-configuration-schema 38 | 39 | - name: Install JSON schema validator 40 | run: | 41 | sudo npm install \ 42 | --global \ 43 | ajv-cli \ 44 | ajv-formats 45 | 46 | - name: Validate local labels configuration 47 | run: | 48 | # See: https://github.com/ajv-validator/ajv-cli#readme 49 | ajv validate \ 50 | --all-errors \ 51 | -c ajv-formats \ 52 | -s "${{ steps.download-schema.outputs.file-path }}" \ 53 | -d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}" 54 | 55 | download: 56 | needs: check 57 | runs-on: ubuntu-latest 58 | 59 | strategy: 60 | matrix: 61 | filename: 62 | # Filenames of the shared configurations to apply to the repository in addition to the local configuration. 63 | # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels 64 | - universal.yml 65 | 66 | steps: 67 | - name: Download 68 | uses: carlosperate/download-file-action@v2 69 | with: 70 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }} 71 | 72 | - name: Pass configuration files to next job via workflow artifact 73 | uses: actions/upload-artifact@v4 74 | with: 75 | path: | 76 | *.yaml 77 | *.yml 78 | if-no-files-found: error 79 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 80 | 81 | sync: 82 | needs: download 83 | runs-on: ubuntu-latest 84 | 85 | steps: 86 | - name: Set environment variables 87 | run: | 88 | # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable 89 | echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV" 90 | 91 | - name: Determine whether to dry run 92 | id: dry-run 93 | if: > 94 | github.event_name == 'pull_request' || 95 | ( 96 | ( 97 | github.event_name == 'push' || 98 | github.event_name == 'workflow_dispatch' 99 | ) && 100 | github.ref != format('refs/heads/{0}', github.event.repository.default_branch) 101 | ) 102 | run: | 103 | # Use of this flag in the github-label-sync command will cause it to only check the validity of the 104 | # configuration. 105 | echo "::set-output name=flag::--dry-run" 106 | 107 | - name: Checkout repository 108 | uses: actions/checkout@v4 109 | 110 | - name: Download configuration files artifact 111 | uses: actions/download-artifact@v4 112 | with: 113 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 114 | path: ${{ env.CONFIGURATIONS_FOLDER }} 115 | 116 | - name: Remove unneeded artifact 117 | uses: geekyeggo/delete-artifact@v5 118 | with: 119 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 120 | 121 | - name: Merge label configuration files 122 | run: | 123 | # Merge all configuration files 124 | shopt -s extglob 125 | cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}" 126 | 127 | - name: Install github-label-sync 128 | run: sudo npm install --global github-label-sync 129 | 130 | - name: Sync labels 131 | env: 132 | GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }} 133 | run: | 134 | # See: https://github.com/Financial-Times/github-label-sync 135 | github-label-sync \ 136 | --labels "${{ env.MERGED_CONFIGURATION_PATH }}" \ 137 | ${{ steps.dry-run.outputs.flag }} \ 138 | ${{ github.repository }} 139 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Alberto Panu https://github.com/bigjohnson 2 | Alasdair Allan https://github.com/aallan 3 | Alice Pintus https://github.com/00alis 4 | Adrian McEwen https://github.com/amcewen 5 | Arduino LLC https://arduino.cc/ 6 | Arnie97 https://github.com/Arnie97 7 | Arturo Guadalupi https://github.com/agdl 8 | Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ 9 | chaveiro https://github.com/chaveiro 10 | Cristian Maglie https://github.com/cmaglie 11 | David A. Mellis https://github.com/damellis 12 | Dino Tinitigan https://github.com/bigdinotech 13 | Eddy https://github.com/eddyst 14 | Federico Vanzati https://github.com/Fede85 15 | Federico Fissore https://github.com/ffissore 16 | Jack Christensen https://github.com/JChristensen 17 | Johann Richard https://github.com/johannrichard 18 | Jordan Terrell https://github.com/iSynaptic 19 | Justin Paulin https://github.com/interwho 20 | lathoub https://github.com/lathoub 21 | Martino Facchin https://github.com/facchinm 22 | Matthias Hertel https://github.com/mathertel 23 | Matthijs Kooijman https://github.com/matthijskooijman 24 | Matt Robinson https://github.com/ribbons 25 | MCQN Ltd. http://mcqn.com/ 26 | Michael Amie https://github.com/michaelamie 27 | Michael Margolis https://github.com/michaelmargolis 28 | Norbert Truchsess https://github.com/ntruchsess 29 | Paul Stoffregen https://github.com/PaulStoffregen 30 | per1234 https://github.com/per1234 31 | Richard Sim 32 | Scott Fitzgerald https://github.com/shfitz 33 | Thibaut Viard https://github.com/aethaniel 34 | Tom Igoe https://github.com/tigoe 35 | WIZnet http://www.wiznet.co.kr 36 | Zach Eveland https://github.com/zeveland 37 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | :repository-owner: arduino-libraries 2 | :repository-name: Ethernet 3 | 4 | = {repository-name} Library for Arduino = 5 | 6 | image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"] 7 | image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"] 8 | image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"] 9 | 10 | With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. 11 | 12 | For more information about this library please visit us at 13 | https://www.arduino.cc/en/Reference/{repository-name} 14 | 15 | == License == 16 | 17 | Copyright (c) 2010 Arduino LLC. All right reserved. 18 | 19 | This library is free software; you can redistribute it and/or 20 | modify it under the terms of the GNU Lesser General Public 21 | License as published by the Free Software Foundation; either 22 | version 2.1 of the License, or (at your option) any later version. 23 | 24 | This library is distributed in the hope that it will be useful, 25 | but WITHOUT ANY WARRANTY; without even the implied warranty of 26 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 27 | Lesser General Public License for more details. 28 | 29 | You should have received a copy of the GNU Lesser General Public 30 | License along with this library; if not, write to the Free Software 31 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 32 | -------------------------------------------------------------------------------- /docs/arduino_mega_ethernet_pins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Ethernet/b16c38a5bd0e25143da8d0e9cdeba5b90db62d0a/docs/arduino_mega_ethernet_pins.png -------------------------------------------------------------------------------- /docs/arduino_uno_ethernet_pins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Ethernet/b16c38a5bd0e25143da8d0e9cdeba5b90db62d0a/docs/arduino_uno_ethernet_pins.png -------------------------------------------------------------------------------- /docs/readme.md: -------------------------------------------------------------------------------- 1 | # Ethernet Library 2 | 3 | This library is designed to work with the Arduino Ethernet Shield, Arduino Ethernet Shield 2, Leonardo Ethernet, and any other W5100/W5200/W5500-based devices. The library allows an Arduino board to connect to the Internet. The board can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports up to eight (W5100 and boards with <= 2 kB SRAM are limited to four) concurrent connections (incoming, outgoing, or a combination). 4 | 5 | The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work. 6 | 7 | ![Arduino UNO Pin map.](https://raw.githubusercontent.com/arduino-libraries/Ethernet/master/docs/arduino_uno_ethernet_pins.png) 8 | 9 | ![Arduino MEGA Pin map.](https://raw.githubusercontent.com/arduino-libraries/Ethernet/master/docs/arduino_mega_ethernet_pins.png) 10 | 11 | To use this library 12 | 13 | ``` 14 | #include 15 | #include 16 | ``` 17 | -------------------------------------------------------------------------------- /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/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 | // initialize 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 to 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 | bool 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 | 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 | -------------------------------------------------------------------------------- /examples/ChatServer/ChatServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Chat Server 3 | 4 | A simple server that distributes any incoming messages to all 5 | connected clients. To use, telnet to your device's IP address and type. 6 | You can see the client's input in the serial monitor as well. 7 | Using an Arduino WIZnet Ethernet shield. 8 | 9 | Circuit: 10 | * Ethernet shield attached to pins 10, 11, 12, 13 11 | 12 | created 18 Dec 2009 13 | by David A. Mellis 14 | modified 9 Apr 2012 15 | by Tom Igoe 16 | 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | // Enter a MAC address and IP address for your controller below. 23 | // The IP address will be dependent on your local network. 24 | // gateway and subnet are optional: 25 | byte mac[] = { 26 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 27 | IPAddress ip(192, 168, 1, 177); 28 | IPAddress myDns(192, 168, 1, 1); 29 | IPAddress gateway(192, 168, 1, 1); 30 | IPAddress subnet(255, 255, 0, 0); 31 | 32 | 33 | // telnet defaults to port 23 34 | EthernetServer server(23); 35 | bool alreadyConnected = false; // whether or not the client was connected previously 36 | 37 | void setup() { 38 | // You can use Ethernet.init(pin) to configure the CS pin 39 | //Ethernet.init(10); // Most Arduino shields 40 | //Ethernet.init(5); // MKR ETH Shield 41 | //Ethernet.init(0); // Teensy 2.0 42 | //Ethernet.init(20); // Teensy++ 2.0 43 | //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet 44 | //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet 45 | 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 | -------------------------------------------------------------------------------- /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 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 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 | -------------------------------------------------------------------------------- /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 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 31 | }; 32 | IPAddress ip(192, 168, 1, 177); 33 | IPAddress myDns(192, 168, 1, 1); 34 | IPAddress gateway(192, 168, 1, 1); 35 | IPAddress subnet(255, 255, 0, 0); 36 | 37 | // telnet defaults to port 23 38 | EthernetServer server(23); 39 | bool gotAMessage = false; // whether or not you got a message from the client yet 40 | 41 | void setup() { 42 | // You can use Ethernet.init(pin) to configure the CS pin 43 | //Ethernet.init(10); // Most Arduino shields 44 | //Ethernet.init(5); // MKR ETH Shield 45 | //Ethernet.init(0); // Teensy 2.0 46 | //Ethernet.init(20); // Teensy++ 2.0 47 | //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet 48 | //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet 49 | 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 | -------------------------------------------------------------------------------- /examples/LinkStatus/LinkStatus.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Link Status 3 | 4 | This sketch prints the Ethernet link status. When the 5 | Ethernet cable is connected the link status should go to "ON". 6 | NOTE: Only WIZnet W5200 and W5500 are capable of reporting 7 | the link status. W5100 will report "Unknown". 8 | Hardware: 9 | - Ethernet shield or equivalent board/shield with WIZnet W5200/W5500 10 | Written by Cristian Maglie 11 | This example is public domain. 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | void setup() { 18 | // You can use Ethernet.init(pin) to configure the CS pin 19 | //Ethernet.init(10); // Most Arduino shields 20 | //Ethernet.init(5); // MKR ETH Shield 21 | //Ethernet.init(0); // Teensy 2.0 22 | //Ethernet.init(20); // Teensy++ 2.0 23 | //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet 24 | //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet 25 | 26 | Serial.begin(9600); 27 | } 28 | 29 | void loop() { 30 | auto link = Ethernet.linkStatus(); 31 | Serial.print("Link status: "); 32 | switch (link) { 33 | case Unknown: 34 | Serial.println("Unknown"); 35 | break; 36 | case LinkON: 37 | Serial.println("ON"); 38 | break; 39 | case LinkOFF: 40 | Serial.println("OFF"); 41 | break; 42 | } 43 | delay(1000); 44 | } 45 | -------------------------------------------------------------------------------- /examples/PagerServer/PagerServer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Pager Server 3 | 4 | A simple server that echoes any incoming messages to all 5 | connected clients. Connect two or more telnet sessions 6 | to see how server.available() and server.print() works. 7 | 8 | created in September 2020 for the Ethernet library 9 | by Juraj Andrassy https://github.com/jandrassy 10 | 11 | */ 12 | #include 13 | 14 | // Enter a MAC address for your controller below. 15 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 16 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 17 | 18 | // Set the static IP address to use if the DHCP fails to assign 19 | IPAddress ip(192, 168, 0, 177); 20 | 21 | EthernetServer server(2323); 22 | 23 | void setup() { 24 | 25 | Serial.begin(9600); 26 | while (!Serial); 27 | 28 | // start the Ethernet connection: 29 | Serial.println("Initialize Ethernet with DHCP:"); 30 | if (Ethernet.begin(mac) == 0) { 31 | Serial.println("Failed to configure Ethernet using DHCP"); 32 | // Check for Ethernet hardware present 33 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 34 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 35 | while (true) { 36 | delay(1); // do nothing, no point running without Ethernet hardware 37 | } 38 | } 39 | if (Ethernet.linkStatus() == LinkOFF) { 40 | Serial.println("Ethernet cable is not connected."); 41 | } 42 | // try to configure using IP address instead of DHCP: 43 | Ethernet.begin(mac, ip); 44 | } else { 45 | Serial.print(" DHCP assigned IP "); 46 | Serial.println(Ethernet.localIP()); 47 | } 48 | 49 | server.begin(); 50 | 51 | IPAddress ip = Ethernet.localIP(); 52 | Serial.println(); 53 | Serial.print("To access the server, connect with Telnet client to "); 54 | Serial.print(ip); 55 | Serial.println(" 2323"); 56 | } 57 | 58 | void loop() { 59 | 60 | EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client 61 | if (client) { // client is true only if it is connected and has data to read 62 | String s = client.readStringUntil('\n'); // read the message incoming from one of the clients 63 | s.trim(); // trim eventual \r 64 | Serial.println(s); // print the message to Serial Monitor 65 | client.print("echo: "); // this is only for the sending client 66 | server.println(s); // send the message to all connected clients 67 | #ifndef ARDUINO_ARCH_SAM 68 | server.flush(); // flush the buffers 69 | #endif /* !defined(ARDUINO_ARCH_SAM) */ 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /examples/TelnetClient/TelnetClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Telnet client 3 | 4 | This sketch connects to 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 | https://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 | -------------------------------------------------------------------------------- /examples/UDPSendReceiveString/UDPSendReceiveString.ino: -------------------------------------------------------------------------------- 1 | /* 2 | UDPSendReceiveString 3 | 4 | This sketch receives UDP message strings, prints them to the serial port 5 | and sends an "acknowledge" string back to the sender 6 | 7 | A Processing sketch is included at the end of file that can be used to send 8 | and receive messages for testing with a computer. 9 | 10 | created 21 Aug 2010 11 | by Michael Margolis 12 | 13 | This code is in the public domain. 14 | */ 15 | 16 | 17 | #include 18 | #include 19 | 20 | // Enter a MAC address and IP address for your controller below. 21 | // The IP address will be dependent on your local network: 22 | byte mac[] = { 23 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 24 | }; 25 | IPAddress ip(192, 168, 1, 177); 26 | 27 | unsigned int localPort = 8888; // local port to listen on 28 | 29 | // buffers for receiving and sending data 30 | char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, 31 | char ReplyBuffer[] = "acknowledged"; // a string to send back 32 | 33 | // An EthernetUDP instance to let us send and receive packets over UDP 34 | EthernetUDP Udp; 35 | 36 | void setup() { 37 | // You can use Ethernet.init(pin) to configure the CS pin 38 | //Ethernet.init(10); // Most Arduino shields 39 | //Ethernet.init(5); // MKR ETH Shield 40 | //Ethernet.init(0); // Teensy 2.0 41 | //Ethernet.init(20); // Teensy++ 2.0 42 | //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet 43 | //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet 44 | 45 | // start the Ethernet 46 | Ethernet.begin(mac, ip); 47 | 48 | // Open serial communications and wait for port to open: 49 | Serial.begin(9600); 50 | while (!Serial) { 51 | ; // wait for serial port to connect. Needed for native USB port only 52 | } 53 | 54 | // Check for Ethernet hardware present 55 | if (Ethernet.hardwareStatus() == EthernetNoHardware) { 56 | Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); 57 | while (true) { 58 | delay(1); // do nothing, no point running without Ethernet hardware 59 | } 60 | } 61 | if (Ethernet.linkStatus() == LinkOFF) { 62 | Serial.println("Ethernet cable is not connected."); 63 | } 64 | 65 | // start UDP 66 | Udp.begin(localPort); 67 | } 68 | 69 | void loop() { 70 | // if there's data available, read a packet 71 | int packetSize = Udp.parsePacket(); 72 | if (packetSize) { 73 | Serial.print("Received packet of size "); 74 | Serial.println(packetSize); 75 | Serial.print("From "); 76 | IPAddress remote = Udp.remoteIP(); 77 | for (int i=0; i < 4; i++) { 78 | Serial.print(remote[i], DEC); 79 | if (i < 3) { 80 | Serial.print("."); 81 | } 82 | } 83 | Serial.print(", port "); 84 | Serial.println(Udp.remotePort()); 85 | 86 | // read the packet into packetBuffer 87 | Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); 88 | Serial.println("Contents:"); 89 | Serial.println(packetBuffer); 90 | 91 | // send a reply to the IP address and port that sent us the packet we received 92 | Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); 93 | Udp.write(ReplyBuffer); 94 | Udp.endPacket(); 95 | } 96 | delay(10); 97 | } 98 | 99 | 100 | /* 101 | Processing sketch to run with this example 102 | ===================================================== 103 | 104 | // Processing UDP example to send and receive string data from Arduino 105 | // press any key to send the "Hello Arduino" message 106 | 107 | 108 | import hypermedia.net.*; 109 | 110 | UDP udp; // define the UDP object 111 | 112 | 113 | void setup() { 114 | udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 115 | //udp.log( true ); // <-- printout the connection activity 116 | udp.listen( true ); // and wait for incoming message 117 | } 118 | 119 | void draw() 120 | { 121 | } 122 | 123 | void keyPressed() { 124 | String ip = "192.168.1.177"; // the remote IP address 125 | int port = 8888; // the destination port 126 | 127 | udp.send("Hello World", ip, port ); // the message to send 128 | 129 | } 130 | 131 | void receive( byte[] data ) { // <-- default handler 132 | //void receive( byte[] data, String ip, int port ) { // <-- extended handler 133 | 134 | for(int i=0; i < data.length; i++) 135 | print(char(data[i])); 136 | println(); 137 | } 138 | */ 139 | -------------------------------------------------------------------------------- /examples/UdpNtpClient/UdpNtpClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Udp NTP Client 3 | 4 | Get the time from a Network Time Protocol (NTP) time server 5 | Demonstrates use of UDP sendPacket and ReceivePacket 6 | For more on NTP time servers and the messages needed to communicate with them, 7 | see https://en.wikipedia.org/wiki/Network_Time_Protocol 8 | 9 | created 4 Sep 2010 10 | by Michael Margolis 11 | modified 9 Apr 2012 12 | by Tom Igoe 13 | modified 02 Sept 2015 14 | by Arturo Guadalupi 15 | 16 | This code is in the public domain. 17 | 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | // Enter a MAC address for your controller below. 25 | // Newer Ethernet shields have a MAC address printed on a sticker on the shield 26 | byte mac[] = { 27 | 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 28 | }; 29 | 30 | unsigned int localPort = 8888; // local port to listen for UDP packets 31 | 32 | const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server 33 | 34 | const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message 35 | 36 | byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 37 | 38 | // A UDP instance to let us send and receive packets over UDP 39 | EthernetUDP Udp; 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 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 | -------------------------------------------------------------------------------- /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 configure 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 | -------------------------------------------------------------------------------- /examples/WebClientRepeating/WebClientRepeating.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Repeating Web client 3 | 4 | This sketch connects to 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 | https://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 configure 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 Ethernet 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 | -------------------------------------------------------------------------------- /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 | bool 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=Ethernet 2 | version=2.0.2 3 | author=Various (see AUTHORS file for details) 4 | maintainer=Arduino 5 | sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. 6 | paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS. 7 | category=Communication 8 | url=https://www.arduino.cc/en/Reference/Ethernet 9 | architectures=* 10 | includes=Ethernet.h 11 | -------------------------------------------------------------------------------- /src/Dhcp.cpp: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #include 5 | #include "Ethernet.h" 6 | #include "Dhcp.h" 7 | #include "utility/w5100.h" 8 | 9 | int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 10 | { 11 | _dhcpLeaseTime=0; 12 | _dhcpT1=0; 13 | _dhcpT2=0; 14 | _timeout = timeout; 15 | _responseTimeout = responseTimeout; 16 | 17 | // zero out _dhcpMacAddr 18 | memset(_dhcpMacAddr, 0, 6); 19 | reset_DHCP_lease(); 20 | 21 | memcpy((void*)_dhcpMacAddr, (void*)mac, 6); 22 | _dhcp_state = STATE_DHCP_START; 23 | return request_DHCP_lease(); 24 | } 25 | 26 | void DhcpClass::reset_DHCP_lease() 27 | { 28 | // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp 29 | memset(_dhcpLocalIp, 0, 20); 30 | } 31 | 32 | //return:0 on error, 1 if request is sent and response is received 33 | int DhcpClass::request_DHCP_lease() 34 | { 35 | uint8_t messageType = 0; 36 | 37 | // Pick an initial transaction ID 38 | _dhcpTransactionId = random(1UL, 2000UL); 39 | _dhcpInitialTransactionId = _dhcpTransactionId; 40 | 41 | _dhcpUdpSocket.stop(); 42 | if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) { 43 | // Couldn't get a socket 44 | return 0; 45 | } 46 | 47 | presend_DHCP(); 48 | 49 | int result = 0; 50 | 51 | unsigned long startTime = millis(); 52 | 53 | while (_dhcp_state != STATE_DHCP_LEASED) { 54 | if (_dhcp_state == STATE_DHCP_START) { 55 | _dhcpTransactionId++; 56 | send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); 57 | _dhcp_state = STATE_DHCP_DISCOVER; 58 | } else if (_dhcp_state == STATE_DHCP_REREQUEST) { 59 | _dhcpTransactionId++; 60 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); 61 | _dhcp_state = STATE_DHCP_REQUEST; 62 | } else if (_dhcp_state == STATE_DHCP_DISCOVER) { 63 | uint32_t respId; 64 | messageType = parseDHCPResponse(_responseTimeout, respId); 65 | if (messageType == DHCP_OFFER) { 66 | // We'll use the transaction ID that the offer came with, 67 | // rather than the one we were up to 68 | _dhcpTransactionId = respId; 69 | send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); 70 | _dhcp_state = STATE_DHCP_REQUEST; 71 | } 72 | } else if (_dhcp_state == STATE_DHCP_REQUEST) { 73 | uint32_t respId; 74 | messageType = parseDHCPResponse(_responseTimeout, respId); 75 | if (messageType == DHCP_ACK) { 76 | _dhcp_state = STATE_DHCP_LEASED; 77 | result = 1; 78 | //use default lease time if we didn't get it 79 | if (_dhcpLeaseTime == 0) { 80 | _dhcpLeaseTime = DEFAULT_LEASE; 81 | } 82 | // Calculate T1 & T2 if we didn't get it 83 | if (_dhcpT1 == 0) { 84 | // T1 should be 50% of _dhcpLeaseTime 85 | _dhcpT1 = _dhcpLeaseTime >> 1; 86 | } 87 | if (_dhcpT2 == 0) { 88 | // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime 89 | _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3); 90 | } 91 | _renewInSec = _dhcpT1; 92 | _rebindInSec = _dhcpT2; 93 | } else if (messageType == DHCP_NAK) { 94 | _dhcp_state = STATE_DHCP_START; 95 | } 96 | } 97 | 98 | if (messageType == 255) { 99 | messageType = 0; 100 | _dhcp_state = STATE_DHCP_START; 101 | } 102 | 103 | if (result != 1 && ((millis() - startTime) > _timeout)) 104 | break; 105 | } 106 | 107 | // We're done with the socket now 108 | _dhcpUdpSocket.stop(); 109 | _dhcpTransactionId++; 110 | 111 | _lastCheckLeaseMillis = millis(); 112 | return result; 113 | } 114 | 115 | void DhcpClass::presend_DHCP() 116 | { 117 | } 118 | 119 | void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) 120 | { 121 | uint8_t buffer[32]; 122 | memset(buffer, 0, 32); 123 | IPAddress dest_addr(255, 255, 255, 255); // Broadcast address 124 | 125 | if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) { 126 | //Serial.printf("DHCP transmit error\n"); 127 | // FIXME Need to return errors 128 | return; 129 | } 130 | 131 | buffer[0] = DHCP_BOOTREQUEST; // op 132 | buffer[1] = DHCP_HTYPE10MB; // htype 133 | buffer[2] = DHCP_HLENETHERNET; // hlen 134 | buffer[3] = DHCP_HOPS; // hops 135 | 136 | // xid 137 | unsigned long xid = htonl(_dhcpTransactionId); 138 | memcpy(buffer + 4, &(xid), 4); 139 | 140 | // 8, 9 - seconds elapsed 141 | buffer[8] = ((secondsElapsed & 0xff00) >> 8); 142 | buffer[9] = (secondsElapsed & 0x00ff); 143 | 144 | // flags 145 | unsigned short flags = htons(DHCP_FLAGSBROADCAST); 146 | memcpy(buffer + 10, &(flags), 2); 147 | 148 | // ciaddr: already zeroed 149 | // yiaddr: already zeroed 150 | // siaddr: already zeroed 151 | // giaddr: already zeroed 152 | 153 | //put data in W5100 transmit buffer 154 | _dhcpUdpSocket.write(buffer, 28); 155 | 156 | memset(buffer, 0, 32); // clear local buffer 157 | 158 | memcpy(buffer, _dhcpMacAddr, 6); // chaddr 159 | 160 | //put data in W5100 transmit buffer 161 | _dhcpUdpSocket.write(buffer, 16); 162 | 163 | memset(buffer, 0, 32); // clear local buffer 164 | 165 | // leave zeroed out for sname && file 166 | // put in W5100 transmit buffer x 6 (192 bytes) 167 | 168 | for(int i = 0; i < 6; i++) { 169 | _dhcpUdpSocket.write(buffer, 32); 170 | } 171 | 172 | // OPT - Magic Cookie 173 | buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); 174 | buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); 175 | buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); 176 | buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); 177 | 178 | // OPT - message type 179 | buffer[4] = dhcpMessageType; 180 | buffer[5] = 0x01; 181 | buffer[6] = messageType; //DHCP_REQUEST; 182 | 183 | // OPT - client identifier 184 | buffer[7] = dhcpClientIdentifier; 185 | buffer[8] = 0x07; 186 | buffer[9] = 0x01; 187 | memcpy(buffer + 10, _dhcpMacAddr, 6); 188 | 189 | // OPT - host name 190 | buffer[16] = hostName; 191 | buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address 192 | strcpy((char*)&(buffer[18]), HOST_NAME); 193 | 194 | printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); 195 | printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); 196 | printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); 197 | 198 | //put data in W5100 transmit buffer 199 | _dhcpUdpSocket.write(buffer, 30); 200 | 201 | if (messageType == DHCP_REQUEST) { 202 | buffer[0] = dhcpRequestedIPaddr; 203 | buffer[1] = 0x04; 204 | buffer[2] = _dhcpLocalIp[0]; 205 | buffer[3] = _dhcpLocalIp[1]; 206 | buffer[4] = _dhcpLocalIp[2]; 207 | buffer[5] = _dhcpLocalIp[3]; 208 | 209 | buffer[6] = dhcpServerIdentifier; 210 | buffer[7] = 0x04; 211 | buffer[8] = _dhcpDhcpServerIp[0]; 212 | buffer[9] = _dhcpDhcpServerIp[1]; 213 | buffer[10] = _dhcpDhcpServerIp[2]; 214 | buffer[11] = _dhcpDhcpServerIp[3]; 215 | 216 | //put data in W5100 transmit buffer 217 | _dhcpUdpSocket.write(buffer, 12); 218 | } 219 | 220 | buffer[0] = dhcpParamRequest; 221 | buffer[1] = 0x06; 222 | buffer[2] = subnetMask; 223 | buffer[3] = routersOnSubnet; 224 | buffer[4] = dns; 225 | buffer[5] = domainName; 226 | buffer[6] = dhcpT1value; 227 | buffer[7] = dhcpT2value; 228 | buffer[8] = endOption; 229 | 230 | //put data in W5100 transmit buffer 231 | _dhcpUdpSocket.write(buffer, 9); 232 | 233 | _dhcpUdpSocket.endPacket(); 234 | } 235 | 236 | uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) 237 | { 238 | uint8_t type = 0; 239 | uint8_t opt_len = 0; 240 | 241 | unsigned long startTime = millis(); 242 | 243 | while (_dhcpUdpSocket.parsePacket() <= 0) { 244 | if ((millis() - startTime) > responseTimeout) { 245 | return 255; 246 | } 247 | delay(50); 248 | } 249 | // start reading in the packet 250 | RIP_MSG_FIXED fixedMsg; 251 | _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); 252 | 253 | if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) { 254 | transactionId = ntohl(fixedMsg.xid); 255 | if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || 256 | (transactionId < _dhcpInitialTransactionId) || 257 | (transactionId > _dhcpTransactionId)) { 258 | // Need to read the rest of the packet here regardless 259 | _dhcpUdpSocket.flush(); // FIXME 260 | return 0; 261 | } 262 | 263 | memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); 264 | 265 | // Skip to the option part 266 | _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED)); 267 | 268 | while (_dhcpUdpSocket.available() > 0) { 269 | switch (_dhcpUdpSocket.read()) { 270 | case endOption : 271 | break; 272 | 273 | case padOption : 274 | break; 275 | 276 | case dhcpMessageType : 277 | opt_len = _dhcpUdpSocket.read(); 278 | type = _dhcpUdpSocket.read(); 279 | break; 280 | 281 | case subnetMask : 282 | opt_len = _dhcpUdpSocket.read(); 283 | _dhcpUdpSocket.read(_dhcpSubnetMask, 4); 284 | break; 285 | 286 | case routersOnSubnet : 287 | opt_len = _dhcpUdpSocket.read(); 288 | _dhcpUdpSocket.read(_dhcpGatewayIp, 4); 289 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 290 | break; 291 | 292 | case dns : 293 | opt_len = _dhcpUdpSocket.read(); 294 | _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); 295 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); 296 | break; 297 | 298 | case dhcpServerIdentifier : 299 | opt_len = _dhcpUdpSocket.read(); 300 | if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) || 301 | IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) { 302 | _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); 303 | } else { 304 | // Skip over the rest of this option 305 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 306 | } 307 | break; 308 | 309 | case dhcpT1value : 310 | opt_len = _dhcpUdpSocket.read(); 311 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); 312 | _dhcpT1 = ntohl(_dhcpT1); 313 | break; 314 | 315 | case dhcpT2value : 316 | opt_len = _dhcpUdpSocket.read(); 317 | _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); 318 | _dhcpT2 = ntohl(_dhcpT2); 319 | break; 320 | 321 | case dhcpIPaddrLeaseTime : 322 | opt_len = _dhcpUdpSocket.read(); 323 | _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); 324 | _dhcpLeaseTime = ntohl(_dhcpLeaseTime); 325 | _renewInSec = _dhcpLeaseTime; 326 | break; 327 | 328 | default : 329 | opt_len = _dhcpUdpSocket.read(); 330 | // Skip over the rest of this option 331 | _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); 332 | break; 333 | } 334 | } 335 | } 336 | 337 | // Need to skip to end of the packet regardless here 338 | _dhcpUdpSocket.flush(); // FIXME 339 | 340 | return type; 341 | } 342 | 343 | 344 | /* 345 | returns: 346 | 0/DHCP_CHECK_NONE: nothing happened 347 | 1/DHCP_CHECK_RENEW_FAIL: renew failed 348 | 2/DHCP_CHECK_RENEW_OK: renew success 349 | 3/DHCP_CHECK_REBIND_FAIL: rebind fail 350 | 4/DHCP_CHECK_REBIND_OK: rebind success 351 | */ 352 | int DhcpClass::checkLease() 353 | { 354 | int rc = DHCP_CHECK_NONE; 355 | 356 | unsigned long now = millis(); 357 | unsigned long elapsed = now - _lastCheckLeaseMillis; 358 | 359 | // if more then one sec passed, reduce the counters accordingly 360 | if (elapsed >= 1000) { 361 | // set the new timestamps 362 | _lastCheckLeaseMillis = now - (elapsed % 1000); 363 | elapsed = elapsed / 1000; 364 | 365 | // decrease the counters by elapsed seconds 366 | // we assume that the cycle time (elapsed) is fairly constant 367 | // if the remainder is less than cycle time * 2 368 | // do it early instead of late 369 | if (_renewInSec < elapsed * 2) { 370 | _renewInSec = 0; 371 | } else { 372 | _renewInSec -= elapsed; 373 | } 374 | if (_rebindInSec < elapsed * 2) { 375 | _rebindInSec = 0; 376 | } else { 377 | _rebindInSec -= elapsed; 378 | } 379 | } 380 | 381 | // if we have a lease but should renew, do it 382 | if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) { 383 | _dhcp_state = STATE_DHCP_REREQUEST; 384 | rc = 1 + request_DHCP_lease(); 385 | } 386 | 387 | // if we have a lease or is renewing but should bind, do it 388 | if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED || 389 | _dhcp_state == STATE_DHCP_START)) { 390 | // this should basically restart completely 391 | _dhcp_state = STATE_DHCP_START; 392 | reset_DHCP_lease(); 393 | rc = 3 + request_DHCP_lease(); 394 | } 395 | return rc; 396 | } 397 | 398 | IPAddress DhcpClass::getLocalIp() 399 | { 400 | return IPAddress(_dhcpLocalIp); 401 | } 402 | 403 | IPAddress DhcpClass::getSubnetMask() 404 | { 405 | return IPAddress(_dhcpSubnetMask); 406 | } 407 | 408 | IPAddress DhcpClass::getGatewayIp() 409 | { 410 | return IPAddress(_dhcpGatewayIp); 411 | } 412 | 413 | IPAddress DhcpClass::getDhcpServerIp() 414 | { 415 | return IPAddress(_dhcpDhcpServerIp); 416 | } 417 | 418 | IPAddress DhcpClass::getDnsServerIp() 419 | { 420 | return IPAddress(_dhcpDnsServerIp); 421 | } 422 | 423 | void DhcpClass::printByte(char * buf, uint8_t n ) 424 | { 425 | char *str = &buf[1]; 426 | buf[0]='0'; 427 | do { 428 | unsigned long m = n; 429 | n /= 16; 430 | char c = m - 16 * n; 431 | *str-- = c < 10 ? c + '0' : c + 'A' - 10; 432 | } while(n); 433 | } 434 | -------------------------------------------------------------------------------- /src/Dhcp.h: -------------------------------------------------------------------------------- 1 | // DHCP Library v0.3 - April 25, 2009 2 | // Author: Jordan Terrell - blog.jordanterrell.com 3 | 4 | #ifndef Dhcp_h 5 | #define Dhcp_h 6 | 7 | /* DHCP state machine. */ 8 | #define STATE_DHCP_START 0 9 | #define STATE_DHCP_DISCOVER 1 10 | #define STATE_DHCP_REQUEST 2 11 | #define STATE_DHCP_LEASED 3 12 | #define STATE_DHCP_REREQUEST 4 13 | #define STATE_DHCP_RELEASE 5 14 | 15 | #define DHCP_FLAGSBROADCAST 0x8000 16 | 17 | /* UDP port numbers for DHCP */ 18 | #define DHCP_SERVER_PORT 67 /* from server to client */ 19 | #define DHCP_CLIENT_PORT 68 /* from client to server */ 20 | 21 | /* DHCP message OP code */ 22 | #define DHCP_BOOTREQUEST 1 23 | #define DHCP_BOOTREPLY 2 24 | 25 | /* DHCP message type */ 26 | #define DHCP_DISCOVER 1 27 | #define DHCP_OFFER 2 28 | #define DHCP_REQUEST 3 29 | #define DHCP_DECLINE 4 30 | #define DHCP_ACK 5 31 | #define DHCP_NAK 6 32 | #define DHCP_RELEASE 7 33 | #define DHCP_INFORM 8 34 | 35 | #define DHCP_HTYPE10MB 1 36 | #define DHCP_HTYPE100MB 2 37 | 38 | #define DHCP_HLENETHERNET 6 39 | #define DHCP_HOPS 0 40 | #define DHCP_SECS 0 41 | 42 | #define MAGIC_COOKIE 0x63825363 43 | #define MAX_DHCP_OPT 16 44 | 45 | #define HOST_NAME "WIZnet" 46 | #define DEFAULT_LEASE (900) //default lease time in seconds 47 | 48 | #define DHCP_CHECK_NONE (0) 49 | #define DHCP_CHECK_RENEW_FAIL (1) 50 | #define DHCP_CHECK_RENEW_OK (2) 51 | #define DHCP_CHECK_REBIND_FAIL (3) 52 | #define DHCP_CHECK_REBIND_OK (4) 53 | 54 | enum 55 | { 56 | padOption = 0, 57 | subnetMask = 1, 58 | timerOffset = 2, 59 | routersOnSubnet = 3, 60 | /* timeServer = 4, 61 | nameServer = 5,*/ 62 | dns = 6, 63 | /*logServer = 7, 64 | cookieServer = 8, 65 | lprServer = 9, 66 | impressServer = 10, 67 | resourceLocationServer = 11,*/ 68 | hostName = 12, 69 | /*bootFileSize = 13, 70 | meritDumpFile = 14,*/ 71 | domainName = 15, 72 | /*swapServer = 16, 73 | rootPath = 17, 74 | extentionsPath = 18, 75 | IPforwarding = 19, 76 | nonLocalSourceRouting = 20, 77 | policyFilter = 21, 78 | maxDgramReasmSize = 22, 79 | defaultIPTTL = 23, 80 | pathMTUagingTimeout = 24, 81 | pathMTUplateauTable = 25, 82 | ifMTU = 26, 83 | allSubnetsLocal = 27, 84 | broadcastAddr = 28, 85 | performMaskDiscovery = 29, 86 | maskSupplier = 30, 87 | performRouterDiscovery = 31, 88 | routerSolicitationAddr = 32, 89 | staticRoute = 33, 90 | trailerEncapsulation = 34, 91 | arpCacheTimeout = 35, 92 | ethernetEncapsulation = 36, 93 | tcpDefaultTTL = 37, 94 | tcpKeepaliveInterval = 38, 95 | tcpKeepaliveGarbage = 39, 96 | nisDomainName = 40, 97 | nisServers = 41, 98 | ntpServers = 42, 99 | vendorSpecificInfo = 43, 100 | netBIOSnameServer = 44, 101 | netBIOSdgramDistServer = 45, 102 | netBIOSnodeType = 46, 103 | netBIOSscope = 47, 104 | xFontServer = 48, 105 | xDisplayManager = 49,*/ 106 | dhcpRequestedIPaddr = 50, 107 | dhcpIPaddrLeaseTime = 51, 108 | /*dhcpOptionOverload = 52,*/ 109 | dhcpMessageType = 53, 110 | dhcpServerIdentifier = 54, 111 | dhcpParamRequest = 55, 112 | /*dhcpMsg = 56, 113 | dhcpMaxMsgSize = 57,*/ 114 | dhcpT1value = 58, 115 | dhcpT2value = 59, 116 | /*dhcpClassIdentifier = 60,*/ 117 | dhcpClientIdentifier = 61, 118 | endOption = 255 119 | }; 120 | 121 | typedef struct _RIP_MSG_FIXED 122 | { 123 | uint8_t op; 124 | uint8_t htype; 125 | uint8_t hlen; 126 | uint8_t hops; 127 | uint32_t xid; 128 | uint16_t secs; 129 | uint16_t flags; 130 | uint8_t ciaddr[4]; 131 | uint8_t yiaddr[4]; 132 | uint8_t siaddr[4]; 133 | uint8_t giaddr[4]; 134 | uint8_t chaddr[6]; 135 | } RIP_MSG_FIXED; 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /src/Dns.cpp: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WIZnet W5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #include 6 | #include "Ethernet.h" 7 | #include "Dns.h" 8 | #include "utility/w5100.h" 9 | 10 | 11 | #define SOCKET_NONE 255 12 | // Various flags and header field values for a DNS message 13 | #define UDP_HEADER_SIZE 8 14 | #define DNS_HEADER_SIZE 12 15 | #define TTL_SIZE 4 16 | #define QUERY_FLAG (0) 17 | #define RESPONSE_FLAG (1<<15) 18 | #define QUERY_RESPONSE_MASK (1<<15) 19 | #define OPCODE_STANDARD_QUERY (0) 20 | #define OPCODE_INVERSE_QUERY (1<<11) 21 | #define OPCODE_STATUS_REQUEST (2<<11) 22 | #define OPCODE_MASK (15<<11) 23 | #define AUTHORITATIVE_FLAG (1<<10) 24 | #define TRUNCATION_FLAG (1<<9) 25 | #define RECURSION_DESIRED_FLAG (1<<8) 26 | #define RECURSION_AVAILABLE_FLAG (1<<7) 27 | #define RESP_NO_ERROR (0) 28 | #define RESP_FORMAT_ERROR (1) 29 | #define RESP_SERVER_FAILURE (2) 30 | #define RESP_NAME_ERROR (3) 31 | #define RESP_NOT_IMPLEMENTED (4) 32 | #define RESP_REFUSED (5) 33 | #define RESP_MASK (15) 34 | #define TYPE_A (0x0001) 35 | #define CLASS_IN (0x0001) 36 | #define LABEL_COMPRESSION_MASK (0xC0) 37 | // Port number that DNS servers listen on 38 | #define DNS_PORT 53 39 | 40 | // Possible return codes from ProcessResponse 41 | #define SUCCESS 1 42 | #define TIMED_OUT -1 43 | #define INVALID_SERVER -2 44 | #define TRUNCATED -3 45 | #define INVALID_RESPONSE -4 46 | 47 | void DNSClient::begin(const IPAddress& aDNSServer) 48 | { 49 | iDNSServer = aDNSServer; 50 | iRequestId = 0; 51 | } 52 | 53 | 54 | int DNSClient::inet_aton(const char* address, IPAddress& result) 55 | { 56 | uint16_t acc = 0; // Accumulator 57 | uint8_t dots = 0; 58 | 59 | while (*address) { 60 | char c = *address++; 61 | if (c >= '0' && c <= '9') { 62 | acc = acc * 10 + (c - '0'); 63 | if (acc > 255) { 64 | // Value out of [0..255] range 65 | return 0; 66 | } 67 | } else if (c == '.') { 68 | if (dots == 3) { 69 | // Too much dots (there must be 3 dots) 70 | return 0; 71 | } 72 | result[dots++] = acc; 73 | acc = 0; 74 | } else { 75 | // Invalid char 76 | return 0; 77 | } 78 | } 79 | 80 | if (dots != 3) { 81 | // Too few dots (there must be 3 dots) 82 | return 0; 83 | } 84 | result[3] = acc; 85 | return 1; 86 | } 87 | 88 | int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout) 89 | { 90 | int ret = 0; 91 | 92 | // See if it's a numeric IP address 93 | if (inet_aton(aHostname, aResult)) { 94 | // It is, our work here is done 95 | return 1; 96 | } 97 | 98 | // Check we've got a valid DNS server to use 99 | if (iDNSServer == INADDR_NONE) { 100 | return INVALID_SERVER; 101 | } 102 | 103 | // Find a socket to use 104 | if (iUdp.begin(1024+(millis() & 0xF)) == 1) { 105 | // Try up to three times 106 | int retries = 0; 107 | // while ((retries < 3) && (ret <= 0)) { 108 | // Send DNS request 109 | ret = iUdp.beginPacket(iDNSServer, DNS_PORT); 110 | if (ret != 0) { 111 | // Now output the request data 112 | ret = BuildRequest(aHostname); 113 | if (ret != 0) { 114 | // And finally send the request 115 | ret = iUdp.endPacket(); 116 | if (ret != 0) { 117 | // Now wait for a response 118 | int wait_retries = 0; 119 | ret = TIMED_OUT; 120 | while ((wait_retries < 3) && (ret == TIMED_OUT)) { 121 | ret = ProcessResponse(timeout, aResult); 122 | wait_retries++; 123 | } 124 | } 125 | } 126 | } 127 | retries++; 128 | //} 129 | 130 | // We're done with the socket now 131 | iUdp.stop(); 132 | } 133 | 134 | return ret; 135 | } 136 | 137 | uint16_t DNSClient::BuildRequest(const char* aName) 138 | { 139 | // Build header 140 | // 1 1 1 1 1 1 141 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 142 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 143 | // | ID | 144 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 145 | // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | 146 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 147 | // | QDCOUNT | 148 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 149 | // | ANCOUNT | 150 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 151 | // | NSCOUNT | 152 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 153 | // | ARCOUNT | 154 | // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 155 | // As we only support one request at a time at present, we can simplify 156 | // some of this header 157 | iRequestId = millis(); // generate a random ID 158 | uint16_t twoByteBuffer; 159 | 160 | // FIXME We should also check that there's enough space available to write to, rather 161 | // FIXME than assume there's enough space (as the code does at present) 162 | iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); 163 | 164 | twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); 165 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 166 | 167 | twoByteBuffer = htons(1); // One question record 168 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 169 | 170 | twoByteBuffer = 0; // Zero answer records 171 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 172 | 173 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 174 | // and zero additional records 175 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 176 | 177 | // Build question 178 | const char* start =aName; 179 | const char* end =start; 180 | uint8_t len; 181 | // Run through the name being requested 182 | while (*end) { 183 | // Find out how long this section of the name is 184 | end = start; 185 | while (*end && (*end != '.') ) { 186 | end++; 187 | } 188 | 189 | if (end-start > 0) { 190 | // Write out the size of this section 191 | len = end-start; 192 | iUdp.write(&len, sizeof(len)); 193 | // And then write out the section 194 | iUdp.write((uint8_t*)start, end-start); 195 | } 196 | start = end+1; 197 | } 198 | 199 | // We've got to the end of the question name, so 200 | // terminate it with a zero-length section 201 | len = 0; 202 | iUdp.write(&len, sizeof(len)); 203 | // Finally the type and class of question 204 | twoByteBuffer = htons(TYPE_A); 205 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 206 | 207 | twoByteBuffer = htons(CLASS_IN); // Internet class of question 208 | iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); 209 | // Success! Everything buffered okay 210 | return 1; 211 | } 212 | 213 | 214 | uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) 215 | { 216 | uint32_t startTime = millis(); 217 | 218 | // Wait for a response packet 219 | while (iUdp.parsePacket() <= 0) { 220 | if ((millis() - startTime) > aTimeout) { 221 | return TIMED_OUT; 222 | } 223 | delay(50); 224 | } 225 | 226 | // We've had a reply! 227 | // Read the UDP header 228 | //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 229 | union { 230 | uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header 231 | uint16_t word[DNS_HEADER_SIZE/2]; 232 | } header; 233 | 234 | // Check that it's a response from the right server and the right port 235 | if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) { 236 | // It's not from who we expected 237 | return INVALID_SERVER; 238 | } 239 | 240 | // Read through the rest of the response 241 | if (iUdp.available() < DNS_HEADER_SIZE) { 242 | return TRUNCATED; 243 | } 244 | iUdp.read(header.byte, DNS_HEADER_SIZE); 245 | 246 | uint16_t header_flags = htons(header.word[1]); 247 | // Check that it's a response to this request 248 | if ((iRequestId != (header.word[0])) || 249 | ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) { 250 | // Mark the entire packet as read 251 | iUdp.flush(); // FIXME 252 | return INVALID_RESPONSE; 253 | } 254 | // Check for any errors in the response (or in our request) 255 | // although we don't do anything to get round these 256 | if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) { 257 | // Mark the entire packet as read 258 | iUdp.flush(); // FIXME 259 | return -5; //INVALID_RESPONSE; 260 | } 261 | 262 | // And make sure we've got (at least) one answer 263 | uint16_t answerCount = htons(header.word[3]); 264 | if (answerCount == 0) { 265 | // Mark the entire packet as read 266 | iUdp.flush(); // FIXME 267 | return -6; //INVALID_RESPONSE; 268 | } 269 | 270 | // Skip over any questions 271 | for (uint16_t i=0; i < htons(header.word[2]); i++) { 272 | // Skip over the name 273 | uint8_t len; 274 | do { 275 | iUdp.read(&len, sizeof(len)); 276 | if (len > 0) { 277 | // Don't need to actually read the data out for the string, just 278 | // advance ptr to beyond it 279 | iUdp.read((uint8_t *)NULL, (size_t)len); 280 | } 281 | } while (len != 0); 282 | 283 | // Now jump over the type and class 284 | iUdp.read((uint8_t *)NULL, 4); 285 | } 286 | 287 | // Now we're up to the bit we're interested in, the answer 288 | // There might be more than one answer (although we'll just use the first 289 | // type A answer) and some authority and additional resource records but 290 | // we're going to ignore all of them. 291 | 292 | for (uint16_t i=0; i < answerCount; i++) { 293 | // Skip the name 294 | uint8_t len; 295 | do { 296 | iUdp.read(&len, sizeof(len)); 297 | if ((len & LABEL_COMPRESSION_MASK) == 0) { 298 | // It's just a normal label 299 | if (len > 0) { 300 | // And it's got a length 301 | // Don't need to actually read the data out for the string, 302 | // just advance ptr to beyond it 303 | iUdp.read((uint8_t *)NULL, len); 304 | } 305 | } else { 306 | // This is a pointer to a somewhere else in the message for the 307 | // rest of the name. We don't care about the name, and RFC1035 308 | // says that a name is either a sequence of labels ended with a 309 | // 0 length octet or a pointer or a sequence of labels ending in 310 | // a pointer. Either way, when we get here we're at the end of 311 | // the name 312 | // Skip over the pointer 313 | iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte 314 | // And set len so that we drop out of the name loop 315 | len = 0; 316 | } 317 | } while (len != 0); 318 | 319 | // Check the type and class 320 | uint16_t answerType; 321 | uint16_t answerClass; 322 | iUdp.read((uint8_t*)&answerType, sizeof(answerType)); 323 | iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); 324 | 325 | // Ignore the Time-To-Live as we don't do any caching 326 | iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes 327 | 328 | // And read out the length of this answer 329 | // Don't need header_flags anymore, so we can reuse it here 330 | iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); 331 | 332 | if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) { 333 | if (htons(header_flags) != 4) { 334 | // It's a weird size 335 | // Mark the entire packet as read 336 | iUdp.flush(); // FIXME 337 | return -9;//INVALID_RESPONSE; 338 | } 339 | // FIXME: seems 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 | -------------------------------------------------------------------------------- /src/Dns.h: -------------------------------------------------------------------------------- 1 | // Arduino DNS client for WIZnet W5100-based Ethernet shield 2 | // (c) Copyright 2009-2010 MCQN Ltd. 3 | // Released under Apache License, version 2.0 4 | 5 | #ifndef DNSClient_h 6 | #define DNSClient_h 7 | 8 | #include "Ethernet.h" 9 | 10 | class DNSClient 11 | { 12 | public: 13 | void begin(const IPAddress& aDNSServer); 14 | 15 | /** Convert a numeric IP address string into a four-byte IP address. 16 | @param aIPAddrString IP address to convert 17 | @param aResult IPAddress structure to store the returned IP address 18 | @result 1 if aIPAddrString was successfully converted to an IP address, 19 | else error code 20 | */ 21 | int inet_aton(const char *aIPAddrString, IPAddress& aResult); 22 | 23 | /** Resolve the given hostname to an IP address. 24 | @param aHostname Name to be resolved 25 | @param aResult IPAddress structure to store the returned IP address 26 | @result 1 if aIPAddrString was successfully converted to an IP address, 27 | else error code 28 | */ 29 | int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000); 30 | 31 | protected: 32 | uint16_t BuildRequest(const char* aName); 33 | uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); 34 | 35 | IPAddress iDNSServer; 36 | uint16_t iRequestId; 37 | EthernetUDP iUdp; 38 | }; 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /src/Ethernet.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | #include "Dhcp.h" 25 | 26 | IPAddress EthernetClass::_dnsServerAddress; 27 | DhcpClass* EthernetClass::_dhcp = NULL; 28 | 29 | int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) 30 | { 31 | static DhcpClass s_dhcp; 32 | _dhcp = &s_dhcp; 33 | 34 | // Initialise the basic info 35 | if (W5100.init() == 0) return 0; 36 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 37 | W5100.setMACAddress(mac); 38 | W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); 39 | SPI.endTransaction(); 40 | 41 | // Now try to get our config info from a DHCP server 42 | int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout); 43 | if (ret == 1) { 44 | // We've successfully found a DHCP server and got our configuration 45 | // info, so set things accordingly 46 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 47 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 48 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 49 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 50 | SPI.endTransaction(); 51 | _dnsServerAddress = _dhcp->getDnsServerIp(); 52 | socketPortRand(micros()); 53 | } 54 | return ret; 55 | } 56 | 57 | void EthernetClass::begin(uint8_t *mac, IPAddress ip) 58 | { 59 | // Assume the DNS server will be the machine on the same network as the local IP 60 | // but with last octet being '1' 61 | IPAddress dns = ip; 62 | dns[3] = 1; 63 | begin(mac, ip, dns); 64 | } 65 | 66 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns) 67 | { 68 | // Assume the gateway will be the machine on the same network as the local IP 69 | // but with last octet being '1' 70 | IPAddress gateway = ip; 71 | gateway[3] = 1; 72 | begin(mac, ip, dns, gateway); 73 | } 74 | 75 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) 76 | { 77 | IPAddress subnet(255, 255, 255, 0); 78 | begin(mac, ip, dns, gateway, subnet); 79 | } 80 | 81 | void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) 82 | { 83 | if (W5100.init() == 0) return; 84 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 85 | W5100.setMACAddress(mac); 86 | W5100.setIPAddress(ip.raw_address()); 87 | W5100.setGatewayIp(gateway.raw_address()); 88 | W5100.setSubnetMask(subnet.raw_address()); 89 | SPI.endTransaction(); 90 | _dnsServerAddress = dns; 91 | } 92 | 93 | void EthernetClass::init(uint8_t sspin) 94 | { 95 | W5100.setSS(sspin); 96 | } 97 | 98 | EthernetLinkStatus EthernetClass::linkStatus() 99 | { 100 | switch (W5100.getLinkStatus()) { 101 | case UNKNOWN: return Unknown; 102 | case LINK_ON: return LinkON; 103 | case LINK_OFF: return LinkOFF; 104 | default: return Unknown; 105 | } 106 | } 107 | 108 | EthernetHardwareStatus EthernetClass::hardwareStatus() 109 | { 110 | switch (W5100.getChip()) { 111 | case 51: return EthernetW5100; 112 | case 52: return EthernetW5200; 113 | case 55: return EthernetW5500; 114 | default: return EthernetNoHardware; 115 | } 116 | } 117 | 118 | int EthernetClass::maintain() 119 | { 120 | int rc = DHCP_CHECK_NONE; 121 | if (_dhcp != NULL) { 122 | // we have a pointer to dhcp, use it 123 | rc = _dhcp->checkLease(); 124 | switch (rc) { 125 | case DHCP_CHECK_NONE: 126 | //nothing done 127 | break; 128 | case DHCP_CHECK_RENEW_OK: 129 | case DHCP_CHECK_REBIND_OK: 130 | //we might have got a new IP. 131 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 132 | W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); 133 | W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); 134 | W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); 135 | SPI.endTransaction(); 136 | _dnsServerAddress = _dhcp->getDnsServerIp(); 137 | break; 138 | default: 139 | //this is actually an error, it will retry though 140 | break; 141 | } 142 | } 143 | return rc; 144 | } 145 | 146 | 147 | void EthernetClass::MACAddress(uint8_t *mac_address) 148 | { 149 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 150 | W5100.getMACAddress(mac_address); 151 | SPI.endTransaction(); 152 | } 153 | 154 | IPAddress EthernetClass::localIP() 155 | { 156 | IPAddress ret; 157 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 158 | W5100.getIPAddress(ret.raw_address()); 159 | SPI.endTransaction(); 160 | return ret; 161 | } 162 | 163 | IPAddress EthernetClass::subnetMask() 164 | { 165 | IPAddress ret; 166 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 167 | W5100.getSubnetMask(ret.raw_address()); 168 | SPI.endTransaction(); 169 | return ret; 170 | } 171 | 172 | IPAddress EthernetClass::gatewayIP() 173 | { 174 | IPAddress ret; 175 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 176 | W5100.getGatewayIp(ret.raw_address()); 177 | SPI.endTransaction(); 178 | return ret; 179 | } 180 | 181 | void EthernetClass::setMACAddress(const uint8_t *mac_address) 182 | { 183 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 184 | W5100.setMACAddress(mac_address); 185 | SPI.endTransaction(); 186 | } 187 | 188 | void EthernetClass::setLocalIP(const IPAddress local_ip) 189 | { 190 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 191 | IPAddress ip = local_ip; 192 | W5100.setIPAddress(ip.raw_address()); 193 | SPI.endTransaction(); 194 | } 195 | 196 | void EthernetClass::setSubnetMask(const IPAddress subnet) 197 | { 198 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 199 | IPAddress ip = subnet; 200 | W5100.setSubnetMask(ip.raw_address()); 201 | SPI.endTransaction(); 202 | } 203 | 204 | void EthernetClass::setGatewayIP(const IPAddress gateway) 205 | { 206 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 207 | IPAddress ip = gateway; 208 | W5100.setGatewayIp(ip.raw_address()); 209 | SPI.endTransaction(); 210 | } 211 | 212 | void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds) 213 | { 214 | if (milliseconds > 6553) milliseconds = 6553; 215 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 216 | W5100.setRetransmissionTime(milliseconds * 10); 217 | SPI.endTransaction(); 218 | } 219 | 220 | void EthernetClass::setRetransmissionCount(uint8_t num) 221 | { 222 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 223 | W5100.setRetransmissionCount(num); 224 | SPI.endTransaction(); 225 | } 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | EthernetClass Ethernet; 237 | -------------------------------------------------------------------------------- /src/Ethernet.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #ifndef ethernet_h_ 22 | #define ethernet_h_ 23 | 24 | // All symbols exposed to Arduino sketches are contained in this header file 25 | // 26 | // Older versions had much of this stuff in EthernetClient.h, EthernetServer.h, 27 | // and socket.h. Including headers in different order could cause trouble, so 28 | // these "friend" classes are now defined in the same header file. socket.h 29 | // was removed to avoid possible conflict with the C library header files. 30 | 31 | 32 | // Configure the maximum number of sockets to support. W5100 chips can have 33 | // up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes 34 | // of RAM are used for each socket. Reducing the maximum can save RAM, but 35 | // you are limited to fewer simultaneous connections. 36 | #if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048) 37 | #define MAX_SOCK_NUM 4 38 | #else 39 | #define MAX_SOCK_NUM 8 40 | #endif 41 | 42 | // By default, each socket uses 2K buffers inside the WIZnet chip. If 43 | // MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting 44 | // this will use larger buffers within the WIZnet chip. Large buffers 45 | // can really help with UDP protocols like Artnet. In theory larger 46 | // buffers should allow faster TCP over high-latency links, but this 47 | // does not always seem to work in practice (maybe WIZnet bugs?) 48 | //#define ETHERNET_LARGE_BUFFERS 49 | 50 | 51 | #include 52 | #include "Client.h" 53 | #include "Server.h" 54 | #include "Udp.h" 55 | 56 | enum EthernetLinkStatus { 57 | Unknown, 58 | LinkON, 59 | LinkOFF 60 | }; 61 | 62 | enum EthernetHardwareStatus { 63 | EthernetNoHardware, 64 | EthernetW5100, 65 | EthernetW5200, 66 | EthernetW5500 67 | }; 68 | 69 | class EthernetUDP; 70 | class EthernetClient; 71 | class EthernetServer; 72 | class DhcpClass; 73 | 74 | class EthernetClass { 75 | private: 76 | static IPAddress _dnsServerAddress; 77 | static DhcpClass* _dhcp; 78 | public: 79 | // Initialise the Ethernet shield to use the provided MAC address and 80 | // gain the rest of the configuration through DHCP. 81 | // Returns 0 if the DHCP configuration failed, and 1 if it succeeded 82 | static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 83 | static int maintain(); 84 | static EthernetLinkStatus linkStatus(); 85 | static EthernetHardwareStatus hardwareStatus(); 86 | 87 | // Manual configuration 88 | static void begin(uint8_t *mac, IPAddress ip); 89 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); 90 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); 91 | static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); 92 | static void init(uint8_t sspin = 10); 93 | 94 | static void MACAddress(uint8_t *mac_address); 95 | static IPAddress localIP(); 96 | static IPAddress subnetMask(); 97 | static IPAddress gatewayIP(); 98 | static IPAddress dnsServerIP() { return _dnsServerAddress; } 99 | 100 | void setMACAddress(const uint8_t *mac_address); 101 | void setLocalIP(const IPAddress local_ip); 102 | void setSubnetMask(const IPAddress subnet); 103 | void setGatewayIP(const IPAddress gateway); 104 | void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; } 105 | void setRetransmissionTimeout(uint16_t milliseconds); 106 | void setRetransmissionCount(uint8_t num); 107 | 108 | friend class EthernetClient; 109 | friend class EthernetServer; 110 | friend class EthernetUDP; 111 | private: 112 | // Opens a socket(TCP or UDP or IP_RAW mode) 113 | static uint8_t socketBegin(uint8_t protocol, uint16_t port); 114 | static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port); 115 | static uint8_t socketStatus(uint8_t s); 116 | // Close socket 117 | static void socketClose(uint8_t s); 118 | // Establish TCP connection (Active connection) 119 | static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port); 120 | // disconnect the connection 121 | static void socketDisconnect(uint8_t s); 122 | // Establish TCP connection (Passive connection) 123 | static uint8_t socketListen(uint8_t s); 124 | // Send data (TCP) 125 | static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len); 126 | static uint16_t socketSendAvailable(uint8_t s); 127 | // Receive data (TCP) 128 | static int socketRecv(uint8_t s, uint8_t * buf, int16_t len); 129 | static uint16_t socketRecvAvailable(uint8_t s); 130 | static uint8_t socketPeek(uint8_t s); 131 | // sets up a UDP datagram, the data for which will be provided by one 132 | // or more calls to bufferData and then finally sent with sendUDP. 133 | // return true if the datagram was successfully set up, or false if there was an error 134 | static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port); 135 | // copy up to len bytes of data from buf into a UDP datagram to be 136 | // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. 137 | // return Number of bytes successfully buffered 138 | static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len); 139 | // Send a UDP datagram built up from a sequence of startUDP followed by one or more 140 | // calls to bufferData. 141 | // return true if the datagram was successfully sent, or false if there was an error 142 | static bool socketSendUDP(uint8_t s); 143 | // Initialize the "random" source port number 144 | static void socketPortRand(uint16_t n); 145 | }; 146 | 147 | extern EthernetClass Ethernet; 148 | 149 | 150 | #define UDP_TX_PACKET_MAX_SIZE 24 151 | 152 | class EthernetUDP : public UDP { 153 | private: 154 | uint16_t _port; // local port to listen on 155 | IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed 156 | uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed 157 | uint16_t _offset; // offset into the packet being sent 158 | 159 | protected: 160 | uint8_t sockindex; 161 | uint16_t _remaining; // remaining bytes of incoming packet yet to be processed 162 | 163 | public: 164 | EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor 165 | 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 166 | 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 167 | virtual void stop(); // Finish with the UDP socket 168 | 169 | // Sending UDP packets 170 | 171 | // Start building up a packet to send to the remote host specific in ip and port 172 | // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port 173 | virtual int beginPacket(IPAddress ip, uint16_t port); 174 | // Start building up a packet to send to the remote host specific in host and port 175 | // Returns 1 if successful, 0 if there was a problem resolving the hostname or port 176 | virtual int beginPacket(const char *host, uint16_t port); 177 | // Finish off this packet and send it 178 | // Returns 1 if the packet was sent successfully, 0 if there was an error 179 | virtual int endPacket(); 180 | // Write a single byte into the packet 181 | virtual size_t write(uint8_t); 182 | // Write size bytes from buffer into the packet 183 | virtual size_t write(const uint8_t *buffer, size_t size); 184 | 185 | using Print::write; 186 | 187 | // Start processing the next available incoming packet 188 | // Returns the size of the packet in bytes, or 0 if no packets are available 189 | virtual int parsePacket(); 190 | // Number of bytes remaining in the current packet 191 | virtual int available(); 192 | // Read a single byte from the current packet 193 | virtual int read(); 194 | // Read up to len bytes from the current packet and place them into buffer 195 | // Returns the number of bytes read, or 0 if none are available 196 | virtual int read(unsigned char* buffer, size_t len); 197 | // Read up to len characters from the current packet and place them into buffer 198 | // Returns the number of characters read, or 0 if none are available 199 | virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; 200 | // Return the next byte from the current packet without moving on to the next byte 201 | virtual int peek(); 202 | virtual void flush(); // Finish reading the current packet 203 | 204 | // Return the IP address of the host who sent the current incoming packet 205 | virtual IPAddress remoteIP() { return _remoteIP; }; 206 | // Return the port of the host who sent the current incoming packet 207 | virtual uint16_t remotePort() { return _remotePort; }; 208 | virtual uint16_t localPort() { return _port; } 209 | }; 210 | 211 | 212 | 213 | 214 | class EthernetClient : public Client { 215 | public: 216 | EthernetClient() : _sockindex(MAX_SOCK_NUM), _timeout(1000) { } 217 | EthernetClient(uint8_t s) : _sockindex(s), _timeout(1000) { } 218 | virtual ~EthernetClient() {}; 219 | 220 | uint8_t status(); 221 | virtual int connect(IPAddress ip, uint16_t port); 222 | virtual int connect(const char *host, uint16_t port); 223 | virtual int availableForWrite(void); 224 | virtual size_t write(uint8_t); 225 | virtual size_t write(const uint8_t *buf, size_t size); 226 | virtual int available(); 227 | virtual int read(); 228 | virtual int read(uint8_t *buf, size_t size); 229 | virtual int peek(); 230 | virtual void flush(); 231 | virtual void stop(); 232 | virtual uint8_t connected(); 233 | virtual operator bool() { return _sockindex < MAX_SOCK_NUM; } 234 | virtual bool operator==(const bool value) { return bool() == value; } 235 | virtual bool operator!=(const bool value) { return bool() != value; } 236 | virtual bool operator==(const EthernetClient&); 237 | virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } 238 | uint8_t getSocketNumber() const { return _sockindex; } 239 | virtual uint16_t localPort(); 240 | virtual IPAddress remoteIP(); 241 | virtual uint16_t remotePort(); 242 | virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; } 243 | 244 | friend class EthernetServer; 245 | 246 | using Print::write; 247 | 248 | private: 249 | uint8_t _sockindex; // MAX_SOCK_NUM means client not in use 250 | uint16_t _timeout; 251 | }; 252 | 253 | 254 | class EthernetServer : public Server { 255 | private: 256 | uint16_t _port; 257 | public: 258 | EthernetServer(uint16_t port) : _port(port) { } 259 | EthernetClient available(); 260 | EthernetClient accept(); 261 | virtual void begin(); 262 | virtual size_t write(uint8_t); 263 | virtual size_t write(const uint8_t *buf, size_t size); 264 | virtual operator bool(); 265 | using Print::write; 266 | //void statusreport(); 267 | 268 | // TODO: make private when socket allocation moves to EthernetClass 269 | static uint16_t server_port[MAX_SOCK_NUM]; 270 | }; 271 | 272 | 273 | class DhcpClass { 274 | private: 275 | uint32_t _dhcpInitialTransactionId; 276 | uint32_t _dhcpTransactionId; 277 | uint8_t _dhcpMacAddr[6]; 278 | #ifdef __arm__ 279 | uint8_t _dhcpLocalIp[4] __attribute__((aligned(4))); 280 | uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4))); 281 | uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4))); 282 | uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4))); 283 | uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4))); 284 | #else 285 | uint8_t _dhcpLocalIp[4]; 286 | uint8_t _dhcpSubnetMask[4]; 287 | uint8_t _dhcpGatewayIp[4]; 288 | uint8_t _dhcpDhcpServerIp[4]; 289 | uint8_t _dhcpDnsServerIp[4]; 290 | #endif 291 | uint32_t _dhcpLeaseTime; 292 | uint32_t _dhcpT1, _dhcpT2; 293 | uint32_t _renewInSec; 294 | uint32_t _rebindInSec; 295 | unsigned long _timeout; 296 | unsigned long _responseTimeout; 297 | unsigned long _lastCheckLeaseMillis; 298 | uint8_t _dhcp_state; 299 | EthernetUDP _dhcpUdpSocket; 300 | 301 | int request_DHCP_lease(); 302 | void reset_DHCP_lease(); 303 | void presend_DHCP(); 304 | void send_DHCP_MESSAGE(uint8_t, uint16_t); 305 | void printByte(char *, uint8_t); 306 | 307 | uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); 308 | public: 309 | IPAddress getLocalIp(); 310 | IPAddress getSubnetMask(); 311 | IPAddress getGatewayIp(); 312 | IPAddress getDhcpServerIp(); 313 | IPAddress getDnsServerIp(); 314 | 315 | int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); 316 | int checkLease(); 317 | }; 318 | 319 | 320 | 321 | 322 | 323 | #endif 324 | -------------------------------------------------------------------------------- /src/EthernetClient.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "Dns.h" 24 | #include "utility/w5100.h" 25 | 26 | int EthernetClient::connect(const char * host, uint16_t port) 27 | { 28 | DNSClient dns; // Look up the host first 29 | IPAddress remote_addr; 30 | 31 | if (_sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { 33 | Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? 34 | } 35 | _sockindex = MAX_SOCK_NUM; 36 | } 37 | dns.begin(Ethernet.dnsServerIP()); 38 | if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout 39 | return connect(remote_addr, port); 40 | } 41 | 42 | int EthernetClient::connect(IPAddress ip, uint16_t port) 43 | { 44 | if (_sockindex < MAX_SOCK_NUM) { 45 | if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { 46 | Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? 47 | } 48 | _sockindex = MAX_SOCK_NUM; 49 | } 50 | #if defined(ESP8266) || defined(ESP32) 51 | if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; 52 | #else 53 | if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; 54 | #endif 55 | _sockindex = Ethernet.socketBegin(SnMR::TCP, 0); 56 | if (_sockindex >= MAX_SOCK_NUM) return 0; 57 | Ethernet.socketConnect(_sockindex, rawIPAddress(ip), port); 58 | uint32_t start = millis(); 59 | while (1) { 60 | uint8_t stat = Ethernet.socketStatus(_sockindex); 61 | if (stat == SnSR::ESTABLISHED) return 1; 62 | if (stat == SnSR::CLOSE_WAIT) return 1; 63 | if (stat == SnSR::CLOSED) return 0; 64 | if (millis() - start > _timeout) break; 65 | delay(1); 66 | } 67 | Ethernet.socketClose(_sockindex); 68 | _sockindex = MAX_SOCK_NUM; 69 | return 0; 70 | } 71 | 72 | int EthernetClient::availableForWrite(void) 73 | { 74 | if (_sockindex >= MAX_SOCK_NUM) return 0; 75 | return Ethernet.socketSendAvailable(_sockindex); 76 | } 77 | 78 | size_t EthernetClient::write(uint8_t b) 79 | { 80 | return write(&b, 1); 81 | } 82 | 83 | size_t EthernetClient::write(const uint8_t *buf, size_t size) 84 | { 85 | if (_sockindex >= MAX_SOCK_NUM) return 0; 86 | if (Ethernet.socketSend(_sockindex, buf, size)) return size; 87 | setWriteError(); 88 | return 0; 89 | } 90 | 91 | int EthernetClient::available() 92 | { 93 | if (_sockindex >= MAX_SOCK_NUM) return 0; 94 | return Ethernet.socketRecvAvailable(_sockindex); 95 | // TODO: do the WIZnet chips automatically retransmit TCP ACK 96 | // packets if they are lost by the network? Someday this should 97 | // be checked by a man-in-the-middle test which discards certain 98 | // packets. If ACKs aren't resent, we would need to check for 99 | // returning 0 here and after a timeout do another Sock_RECV 100 | // command to cause the WIZnet chip to resend the ACK packet. 101 | } 102 | 103 | int EthernetClient::read(uint8_t *buf, size_t size) 104 | { 105 | if (_sockindex >= MAX_SOCK_NUM) return 0; 106 | return Ethernet.socketRecv(_sockindex, buf, size); 107 | } 108 | 109 | int EthernetClient::peek() 110 | { 111 | if (_sockindex >= MAX_SOCK_NUM) return -1; 112 | if (!available()) return -1; 113 | return Ethernet.socketPeek(_sockindex); 114 | } 115 | 116 | int EthernetClient::read() 117 | { 118 | uint8_t b; 119 | if (Ethernet.socketRecv(_sockindex, &b, 1) > 0) return b; 120 | return -1; 121 | } 122 | 123 | void EthernetClient::flush() 124 | { 125 | while (_sockindex < MAX_SOCK_NUM) { 126 | uint8_t stat = Ethernet.socketStatus(_sockindex); 127 | if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; 128 | if (Ethernet.socketSendAvailable(_sockindex) >= W5100.SSIZE) return; 129 | } 130 | } 131 | 132 | void EthernetClient::stop() 133 | { 134 | if (_sockindex >= MAX_SOCK_NUM) return; 135 | 136 | // attempt to close the connection gracefully (send a FIN to other side) 137 | Ethernet.socketDisconnect(_sockindex); 138 | unsigned long start = millis(); 139 | 140 | // wait up to a second for the connection to close 141 | do { 142 | if (Ethernet.socketStatus(_sockindex) == SnSR::CLOSED) { 143 | _sockindex = MAX_SOCK_NUM; 144 | return; // exit the loop 145 | } 146 | delay(1); 147 | } while (millis() - start < _timeout); 148 | 149 | // if it hasn't closed, close it forcefully 150 | Ethernet.socketClose(_sockindex); 151 | _sockindex = MAX_SOCK_NUM; 152 | } 153 | 154 | uint8_t EthernetClient::connected() 155 | { 156 | if (_sockindex >= MAX_SOCK_NUM) return 0; 157 | 158 | uint8_t s = Ethernet.socketStatus(_sockindex); 159 | return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || 160 | (s == SnSR::CLOSE_WAIT && !available())); 161 | } 162 | 163 | uint8_t EthernetClient::status() 164 | { 165 | if (_sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; 166 | return Ethernet.socketStatus(_sockindex); 167 | } 168 | 169 | // the next function allows us to use the client returned by 170 | // EthernetServer::available() as the condition in an if-statement. 171 | bool EthernetClient::operator==(const EthernetClient& rhs) 172 | { 173 | if (_sockindex != rhs._sockindex) return false; 174 | if (_sockindex >= MAX_SOCK_NUM) return false; 175 | if (rhs._sockindex >= MAX_SOCK_NUM) return false; 176 | return true; 177 | } 178 | 179 | // https://github.com/per1234/EthernetMod 180 | // from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd 181 | uint16_t EthernetClient::localPort() 182 | { 183 | if (_sockindex >= MAX_SOCK_NUM) return 0; 184 | uint16_t port; 185 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 186 | port = W5100.readSnPORT(_sockindex); 187 | SPI.endTransaction(); 188 | return port; 189 | } 190 | 191 | // https://github.com/per1234/EthernetMod 192 | // returns the remote IP address: https://forum.arduino.cc/index.php?topic=82416.0 193 | IPAddress EthernetClient::remoteIP() 194 | { 195 | if (_sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); 196 | uint8_t remoteIParray[4]; 197 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 198 | W5100.readSnDIPR(_sockindex, remoteIParray); 199 | SPI.endTransaction(); 200 | return IPAddress(remoteIParray); 201 | } 202 | 203 | // https://github.com/per1234/EthernetMod 204 | // from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75 205 | uint16_t EthernetClient::remotePort() 206 | { 207 | if (_sockindex >= MAX_SOCK_NUM) return 0; 208 | uint16_t port; 209 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 210 | port = W5100.readSnDPORT(_sockindex); 211 | SPI.endTransaction(); 212 | return port; 213 | } 214 | -------------------------------------------------------------------------------- /src/EthernetClient.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /src/EthernetServer.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | 25 | uint16_t EthernetServer::server_port[MAX_SOCK_NUM]; 26 | 27 | 28 | void EthernetServer::begin() 29 | { 30 | uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port); 31 | if (sockindex < MAX_SOCK_NUM) { 32 | if (Ethernet.socketListen(sockindex)) { 33 | server_port[sockindex] = _port; 34 | } else { 35 | Ethernet.socketDisconnect(sockindex); 36 | } 37 | } 38 | } 39 | 40 | EthernetClient EthernetServer::available() 41 | { 42 | bool listening = false; 43 | uint8_t sockindex = MAX_SOCK_NUM; 44 | uint8_t chip, maxindex=MAX_SOCK_NUM; 45 | 46 | chip = W5100.getChip(); 47 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 48 | #if MAX_SOCK_NUM > 4 49 | if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets 50 | #endif 51 | for (uint8_t i=0; i < maxindex; i++) { 52 | if (server_port[i] == _port) { 53 | uint8_t stat = Ethernet.socketStatus(i); 54 | if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) { 55 | if (Ethernet.socketRecvAvailable(i) > 0) { 56 | sockindex = i; 57 | } else { 58 | // remote host closed connection, our end still open 59 | if (stat == SnSR::CLOSE_WAIT) { 60 | Ethernet.socketDisconnect(i); 61 | // status becomes LAST_ACK for short time 62 | } 63 | } 64 | } else if (stat == SnSR::LISTEN) { 65 | listening = true; 66 | } else if (stat == SnSR::CLOSED) { 67 | server_port[i] = 0; 68 | } 69 | } 70 | } 71 | if (!listening) begin(); 72 | return EthernetClient(sockindex); 73 | } 74 | 75 | EthernetClient EthernetServer::accept() 76 | { 77 | bool listening = false; 78 | uint8_t sockindex = MAX_SOCK_NUM; 79 | uint8_t chip, maxindex=MAX_SOCK_NUM; 80 | 81 | chip = W5100.getChip(); 82 | if (!chip) return EthernetClient(MAX_SOCK_NUM); 83 | #if MAX_SOCK_NUM > 4 84 | if (chip == 51) 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/EthernetServer.h: -------------------------------------------------------------------------------- 1 | // This file is in the public domain. No copyright is claimed. 2 | 3 | #include "Ethernet.h" 4 | -------------------------------------------------------------------------------- /src/EthernetUdp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * MIT License: 7 | * Copyright (c) 2008 Bjoern Hartmann 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | * 26 | * bjoern@cs.stanford.edu 12/30/2008 27 | */ 28 | 29 | #include 30 | #include "Ethernet.h" 31 | #include "Dns.h" 32 | #include "utility/w5100.h" 33 | 34 | /* Start EthernetUDP socket, listening at local port PORT */ 35 | uint8_t EthernetUDP::begin(uint16_t port) 36 | { 37 | if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); 38 | sockindex = Ethernet.socketBegin(SnMR::UDP, port); 39 | if (sockindex >= MAX_SOCK_NUM) return 0; 40 | _port = port; 41 | _remaining = 0; 42 | return 1; 43 | } 44 | 45 | /* return number of bytes available in the current packet, 46 | will return zero if parsePacket hasn't been called yet */ 47 | int EthernetUDP::available() 48 | { 49 | return _remaining; 50 | } 51 | 52 | /* Release any resources being used by this EthernetUDP instance */ 53 | void EthernetUDP::stop() 54 | { 55 | if (sockindex < MAX_SOCK_NUM) { 56 | Ethernet.socketClose(sockindex); 57 | sockindex = MAX_SOCK_NUM; 58 | } 59 | } 60 | 61 | int EthernetUDP::beginPacket(const char *host, uint16_t port) 62 | { 63 | // Look up the host first 64 | int ret = 0; 65 | DNSClient dns; 66 | IPAddress remote_addr; 67 | 68 | dns.begin(Ethernet.dnsServerIP()); 69 | ret = dns.getHostByName(host, remote_addr); 70 | if (ret != 1) return ret; 71 | return beginPacket(remote_addr, port); 72 | } 73 | 74 | int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) 75 | { 76 | _offset = 0; 77 | //Serial.printf("UDP beginPacket\n"); 78 | return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port); 79 | } 80 | 81 | int EthernetUDP::endPacket() 82 | { 83 | return Ethernet.socketSendUDP(sockindex); 84 | } 85 | 86 | size_t EthernetUDP::write(uint8_t byte) 87 | { 88 | return write(&byte, 1); 89 | } 90 | 91 | size_t EthernetUDP::write(const uint8_t *buffer, size_t size) 92 | { 93 | //Serial.printf("UDP write %d\n", size); 94 | uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size); 95 | _offset += bytes_written; 96 | return bytes_written; 97 | } 98 | 99 | int EthernetUDP::parsePacket() 100 | { 101 | // discard any remaining bytes in the last packet 102 | while (_remaining) { 103 | // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? 104 | // should only occur if recv fails after telling us the data is there, lets 105 | // hope the w5100 always behaves :) 106 | read((uint8_t *)NULL, _remaining); 107 | } 108 | 109 | if (Ethernet.socketRecvAvailable(sockindex) > 0) { 110 | //HACK - hand-parse the UDP packet using TCP recv method 111 | uint8_t tmpBuf[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 | -------------------------------------------------------------------------------- /src/EthernetUdp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. 3 | * This version only offers minimal wrapping of socket.cpp 4 | * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ 5 | * 6 | * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) 7 | * 1) UDP does not guarantee the order in which assembled UDP packets are received. This 8 | * might not happen often in practice, but in larger network topologies, a UDP 9 | * packet can be received out of sequence. 10 | * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being 11 | * aware of it. Again, this may not be a concern in practice on small local networks. 12 | * For more information, see http://www.cafeaulait.org/course/week12/35.html 13 | * 14 | * MIT License: 15 | * Copyright (c) 2008 Bjoern Hartmann 16 | * Permission is hereby granted, free of charge, to any person obtaining a copy 17 | * of this software and associated documentation files (the "Software"), to deal 18 | * in the Software without restriction, including without limitation the rights 19 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 | * copies of the Software, and to permit persons to whom the Software is 21 | * furnished to do so, subject to the following conditions: 22 | * 23 | * The above copyright notice and this permission notice shall be included in 24 | * all copies or substantial portions of the Software. 25 | * 26 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 29 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 32 | * THE SOFTWARE. 33 | * 34 | * bjoern@cs.stanford.edu 12/30/2008 35 | */ 36 | 37 | #include "Ethernet.h" 38 | 39 | -------------------------------------------------------------------------------- /src/socket.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Paul Stoffregen 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | * software and associated documentation files (the "Software"), to deal in the Software 5 | * without restriction, including without limitation the rights to use, copy, modify, 6 | * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | * permit persons to whom the Software is furnished to do so, subject to the following 8 | * conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 14 | * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 15 | * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 16 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 18 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #include 22 | #include "Ethernet.h" 23 | #include "utility/w5100.h" 24 | 25 | #if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32) 26 | extern void yield(void); 27 | #else 28 | #define yield() 29 | #endif 30 | 31 | // TODO: randomize this when not using DHCP, but how? 32 | static uint16_t local_port = 49152; // 49152 to 65535 33 | 34 | typedef struct { 35 | uint16_t RX_RSR; // Number of bytes received 36 | uint16_t RX_RD; // Address to read 37 | uint16_t TX_FSR; // Free space ready for transmit 38 | uint8_t RX_inc; // how much have we advanced RX_RD 39 | } socketstate_t; 40 | 41 | static socketstate_t state[MAX_SOCK_NUM]; 42 | 43 | 44 | static uint16_t getSnTX_FSR(uint8_t s); 45 | static uint16_t getSnRX_RSR(uint8_t s); 46 | static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len); 47 | static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len); 48 | 49 | 50 | 51 | /*****************************************/ 52 | /* Socket management */ 53 | /*****************************************/ 54 | 55 | 56 | void EthernetClass::socketPortRand(uint16_t n) 57 | { 58 | n &= 0x3FFF; 59 | local_port ^= n; 60 | //Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port); 61 | } 62 | 63 | uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port) 64 | { 65 | uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; 66 | 67 | // first check hardware compatibility 68 | chip = W5100.getChip(); 69 | if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected 70 | #if MAX_SOCK_NUM > 4 71 | if (chip == 51) 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 | 405 | if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) { 406 | W5100.write(dstAddr, data, len); 407 | } else { 408 | // Wrap around circular buffer 409 | uint16_t size = W5100.SSIZE - offset; 410 | W5100.write(dstAddr, data, size); 411 | W5100.write(W5100.SBASE(s), data + size, len - size); 412 | } 413 | ptr += len; 414 | W5100.writeSnTX_WR(s, ptr); 415 | } 416 | 417 | 418 | /** 419 | * @brief This function used to send the data in TCP mode 420 | * @return 1 for success else 0. 421 | */ 422 | uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len) 423 | { 424 | uint8_t status=0; 425 | uint16_t ret=0; 426 | uint16_t freesize=0; 427 | 428 | if (len > W5100.SSIZE) { 429 | ret = W5100.SSIZE; // check size not to exceed MAX size. 430 | } else { 431 | ret = len; 432 | } 433 | 434 | // if freebuf is available, start. 435 | do { 436 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 437 | freesize = getSnTX_FSR(s); 438 | status = W5100.readSnSR(s); 439 | SPI.endTransaction(); 440 | if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) { 441 | ret = 0; 442 | break; 443 | } 444 | yield(); 445 | } while (freesize < ret); 446 | 447 | // copy data 448 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 449 | write_data(s, 0, (uint8_t *)buf, ret); 450 | W5100.execCmdSn(s, Sock_SEND); 451 | 452 | /* +2008.01 bj */ 453 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { 454 | /* m2008.01 [bj] : reduce code */ 455 | if ( W5100.readSnSR(s) == SnSR::CLOSED ) { 456 | SPI.endTransaction(); 457 | return 0; 458 | } 459 | SPI.endTransaction(); 460 | yield(); 461 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 462 | } 463 | /* +2008.01 bj */ 464 | W5100.writeSnIR(s, SnIR::SEND_OK); 465 | SPI.endTransaction(); 466 | return ret; 467 | } 468 | 469 | uint16_t EthernetClass::socketSendAvailable(uint8_t s) 470 | { 471 | uint8_t status=0; 472 | uint16_t freesize=0; 473 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 474 | freesize = getSnTX_FSR(s); 475 | status = W5100.readSnSR(s); 476 | SPI.endTransaction(); 477 | if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) { 478 | return freesize; 479 | } 480 | return 0; 481 | } 482 | 483 | uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len) 484 | { 485 | //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len); 486 | uint16_t ret =0; 487 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 488 | uint16_t txfree = getSnTX_FSR(s); 489 | if (len > txfree) { 490 | ret = txfree; // check size not to exceed MAX size. 491 | } else { 492 | ret = len; 493 | } 494 | write_data(s, offset, buf, ret); 495 | SPI.endTransaction(); 496 | return ret; 497 | } 498 | 499 | bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port) 500 | { 501 | if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || 502 | ((port == 0x00)) ) { 503 | return false; 504 | } 505 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 506 | W5100.writeSnDIPR(s, addr); 507 | W5100.writeSnDPORT(s, port); 508 | SPI.endTransaction(); 509 | return true; 510 | } 511 | 512 | bool EthernetClass::socketSendUDP(uint8_t s) 513 | { 514 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 515 | W5100.execCmdSn(s, Sock_SEND); 516 | 517 | /* +2008.01 bj */ 518 | while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { 519 | if (W5100.readSnIR(s) & SnIR::TIMEOUT) { 520 | /* +2008.01 [bj]: clear interrupt */ 521 | W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT)); 522 | SPI.endTransaction(); 523 | //Serial.printf("sendUDP timeout\n"); 524 | return false; 525 | } 526 | SPI.endTransaction(); 527 | yield(); 528 | SPI.beginTransaction(SPI_ETHERNET_SETTINGS); 529 | } 530 | 531 | /* +2008.01 bj */ 532 | W5100.writeSnIR(s, SnIR::SEND_OK); 533 | SPI.endTransaction(); 534 | 535 | //Serial.printf("sendUDP ok\n"); 536 | /* Sent ok */ 537 | return true; 538 | } 539 | -------------------------------------------------------------------------------- /src/utility/w5100.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Paul Stoffregen 3 | * Copyright (c) 2010 by Cristian Maglie 4 | * 5 | * This file is free software; you can redistribute it and/or modify 6 | * it under the terms of either the GNU General Public License version 2 7 | * or the GNU Lesser General Public License version 2.1, both as 8 | * published by the Free Software Foundation. 9 | */ 10 | 11 | #include 12 | #include "Ethernet.h" 13 | #include "w5100.h" 14 | 15 | 16 | /***************************************************/ 17 | /** Default SS pin setting **/ 18 | /***************************************************/ 19 | 20 | // If variant.h or other headers specifically define the 21 | // default SS pin for Ethernet, use it. 22 | #if defined(PIN_SPI_SS_ETHERNET_LIB) 23 | #define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB 24 | 25 | // MKR boards default to pin 5 for MKR ETH 26 | // Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10 27 | #elif defined(USE_ARDUINO_MKR_PIN_LAYOUT) || defined(ARDUINO_SAMD_MKRZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRVIDOR4000) 28 | #define SS_PIN_DEFAULT 5 29 | 30 | // For boards using AVR, assume shields with SS on pin 10 31 | // will be used. This allows for Arduino Mega (where 32 | // SS is pin 53) and Arduino Leonardo (where SS is pin 17) 33 | // to work by default with Arduino Ethernet Shield R2 & R3. 34 | #elif defined(__AVR__) 35 | #define SS_PIN_DEFAULT 10 36 | 37 | // If variant.h or other headers define these names 38 | // use them if none of the other cases match 39 | #elif defined(PIN_SPI_SS) 40 | #define SS_PIN_DEFAULT PIN_SPI_SS 41 | #elif defined(CORE_SS0_PIN) 42 | #define SS_PIN_DEFAULT CORE_SS0_PIN 43 | 44 | // As a final fallback, use pin 10 45 | #else 46 | #define SS_PIN_DEFAULT 10 47 | #endif 48 | 49 | 50 | 51 | 52 | // W5100 controller instance 53 | uint8_t W5100Class::chip = 0; 54 | uint8_t W5100Class::CH_BASE_MSB; 55 | 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(void) 87 | { 88 | static bool initialized = false; 89 | uint8_t i; 90 | 91 | if (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(560); 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.transfer(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.transfer(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 | memset(buf, 0, len); 462 | SPI.transfer(buf, len); 463 | resetSS(); 464 | } 465 | return len; 466 | } 467 | 468 | void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) 469 | { 470 | // Send command to socket 471 | writeSnCR(s, _cmd); 472 | // Wait for command to complete 473 | while (readSnCR(s)) ; 474 | } 475 | -------------------------------------------------------------------------------- /src/utility/w5100.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Paul Stoffregen 3 | * Copyright (c) 2010 by Cristian Maglie 4 | * 5 | * This file is free software; you can redistribute it and/or modify 6 | * it under the terms of either the GNU General Public License version 2 7 | * or the GNU Lesser General Public License version 2.1, both as 8 | * published by the Free Software Foundation. 9 | */ 10 | 11 | // w5100.h contains private W5x00 hardware "driver" level definitions 12 | // which are not meant to be exposed to other libraries or Arduino users 13 | 14 | #ifndef W5100_H_INCLUDED 15 | #define W5100_H_INCLUDED 16 | 17 | #include 18 | #include 19 | 20 | // Safe for all chips 21 | #define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0) 22 | 23 | // Safe for W5200 and W5500, but too fast for W5100 24 | // Uncomment this if you know you'll never need W5100 support. 25 | // Higher SPI clock only results in faster transfer to hosts on a LAN 26 | // or with very low packet latency. With ordinary internet latency, 27 | // the TCP window size & packet loss determine your overall speed. 28 | //#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0) 29 | 30 | 31 | // Require Ethernet.h, because we need MAX_SOCK_NUM 32 | #ifndef ethernet_h_ 33 | #error "Ethernet.h must be included before w5100.h" 34 | #endif 35 | 36 | 37 | // Arduino 101's SPI can not run faster than 8 MHz. 38 | #if defined(ARDUINO_ARCH_ARC32) 39 | #undef SPI_ETHERNET_SETTINGS 40 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) 41 | #endif 42 | 43 | // Arduino Zero can't use W5100-based shields faster than 8 MHz 44 | // https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848 45 | // W5500 does seem to work at 12 MHz. Delete this if only using W5500 46 | #if defined(__SAMD21G18A__) 47 | #undef SPI_ETHERNET_SETTINGS 48 | #define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) 49 | #endif 50 | 51 | 52 | typedef uint8_t SOCKET; 53 | 54 | class SnMR { 55 | public: 56 | static const uint8_t CLOSE = 0x00; 57 | static const uint8_t TCP = 0x21; 58 | static const uint8_t UDP = 0x02; 59 | static const uint8_t IPRAW = 0x03; 60 | static const uint8_t MACRAW = 0x04; 61 | static const uint8_t PPPOE = 0x05; 62 | static const uint8_t ND = 0x20; 63 | static const uint8_t MULTI = 0x80; 64 | }; 65 | 66 | enum SockCMD { 67 | Sock_OPEN = 0x01, 68 | Sock_LISTEN = 0x02, 69 | Sock_CONNECT = 0x04, 70 | Sock_DISCON = 0x08, 71 | Sock_CLOSE = 0x10, 72 | Sock_SEND = 0x20, 73 | Sock_SEND_MAC = 0x21, 74 | Sock_SEND_KEEP = 0x22, 75 | Sock_RECV = 0x40 76 | }; 77 | 78 | class SnIR { 79 | public: 80 | static const uint8_t SEND_OK = 0x10; 81 | static const uint8_t TIMEOUT = 0x08; 82 | static const uint8_t RECV = 0x04; 83 | static const uint8_t DISCON = 0x02; 84 | static const uint8_t CON = 0x01; 85 | }; 86 | 87 | class SnSR { 88 | public: 89 | static const uint8_t CLOSED = 0x00; 90 | static const uint8_t INIT = 0x13; 91 | static const uint8_t LISTEN = 0x14; 92 | static const uint8_t SYNSENT = 0x15; 93 | static const uint8_t SYNRECV = 0x16; 94 | static const uint8_t ESTABLISHED = 0x17; 95 | static const uint8_t FIN_WAIT = 0x18; 96 | static const uint8_t CLOSING = 0x1A; 97 | static const uint8_t TIME_WAIT = 0x1B; 98 | static const uint8_t CLOSE_WAIT = 0x1C; 99 | static const uint8_t LAST_ACK = 0x1D; 100 | static const uint8_t UDP = 0x22; 101 | static const uint8_t IPRAW = 0x32; 102 | static const uint8_t MACRAW = 0x42; 103 | static const uint8_t PPPOE = 0x5F; 104 | }; 105 | 106 | class IPPROTO { 107 | public: 108 | static const uint8_t IP = 0; 109 | static const uint8_t ICMP = 1; 110 | static const uint8_t IGMP = 2; 111 | static const uint8_t GGP = 3; 112 | static const uint8_t TCP = 6; 113 | static const uint8_t PUP = 12; 114 | static const uint8_t UDP = 17; 115 | static const uint8_t IDP = 22; 116 | static const uint8_t ND = 77; 117 | static const uint8_t RAW = 255; 118 | }; 119 | 120 | enum W5100Linkstatus { 121 | UNKNOWN, 122 | LINK_ON, 123 | LINK_OFF 124 | }; 125 | 126 | class W5100Class { 127 | 128 | public: 129 | static uint8_t init(void); 130 | 131 | inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); } 132 | inline void getGatewayIp(uint8_t * addr) { readGAR(addr); } 133 | 134 | inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); } 135 | inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); } 136 | 137 | inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); } 138 | inline void getMACAddress(uint8_t * addr) { readSHAR(addr); } 139 | 140 | inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); } 141 | inline void getIPAddress(uint8_t * addr) { readSIPR(addr); } 142 | 143 | inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); } 144 | inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); } 145 | 146 | static void execCmdSn(SOCKET s, SockCMD _cmd); 147 | 148 | 149 | // W5100 Registers 150 | // --------------- 151 | //private: 152 | public: 153 | static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len); 154 | static uint8_t write(uint16_t addr, uint8_t data) { 155 | return write(addr, &data, 1); 156 | } 157 | static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len); 158 | static uint8_t read(uint16_t addr) { 159 | uint8_t data; 160 | read(addr, &data, 1); 161 | return data; 162 | } 163 | 164 | #define __GP_REGISTER8(name, address) \ 165 | static inline void write##name(uint8_t _data) { \ 166 | write(address, _data); \ 167 | } \ 168 | static inline uint8_t read##name() { \ 169 | return read(address); \ 170 | } 171 | #define __GP_REGISTER16(name, address) \ 172 | static void write##name(uint16_t _data) { \ 173 | uint8_t buf[2]; \ 174 | buf[0] = _data >> 8; \ 175 | buf[1] = _data & 0xFF; \ 176 | write(address, buf, 2); \ 177 | } \ 178 | static uint16_t read##name() { \ 179 | uint8_t buf[2]; \ 180 | read(address, buf, 2); \ 181 | return (buf[0] << 8) | buf[1]; \ 182 | } 183 | #define __GP_REGISTER_N(name, address, size) \ 184 | static uint16_t write##name(const uint8_t *_buff) { \ 185 | return write(address, _buff, size); \ 186 | } \ 187 | static uint16_t read##name(uint8_t *_buff) { \ 188 | return read(address, _buff, size); \ 189 | } 190 | static W5100Linkstatus getLinkStatus(); 191 | 192 | public: 193 | __GP_REGISTER8 (MR, 0x0000); // Mode 194 | __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address 195 | __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address 196 | __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address 197 | __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address 198 | __GP_REGISTER8 (IR, 0x0015); // Interrupt 199 | __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask 200 | __GP_REGISTER16(RTR, 0x0017); // Timeout address 201 | __GP_REGISTER8 (RCR, 0x0019); // Retry count 202 | __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only) 203 | __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only) 204 | __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode 205 | __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer 206 | __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number 207 | __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only) 208 | __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only) 209 | __GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only) 210 | __GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only) 211 | __GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status 212 | __GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx 213 | 214 | 215 | #undef __GP_REGISTER8 216 | #undef __GP_REGISTER16 217 | #undef __GP_REGISTER_N 218 | 219 | // W5100 Socket registers 220 | // ---------------------- 221 | private: 222 | static uint16_t CH_BASE(void) { 223 | //if (chip == 55) return 0x1000; 224 | //if (chip == 52) return 0x4000; 225 | //return 0x0400; 226 | return CH_BASE_MSB << 8; 227 | } 228 | static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR 229 | static const uint16_t CH_SIZE = 0x0100; 230 | 231 | static inline uint8_t readSn(SOCKET s, uint16_t addr) { 232 | return read(CH_BASE() + s * CH_SIZE + addr); 233 | } 234 | static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) { 235 | return write(CH_BASE() + s * CH_SIZE + addr, data); 236 | } 237 | static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { 238 | return read(CH_BASE() + s * CH_SIZE + addr, buf, len); 239 | } 240 | static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { 241 | return write(CH_BASE() + s * CH_SIZE + addr, buf, len); 242 | } 243 | 244 | #define __SOCKET_REGISTER8(name, address) \ 245 | static inline void write##name(SOCKET _s, uint8_t _data) { \ 246 | writeSn(_s, address, _data); \ 247 | } \ 248 | static inline uint8_t read##name(SOCKET _s) { \ 249 | return readSn(_s, address); \ 250 | } 251 | #define __SOCKET_REGISTER16(name, address) \ 252 | static void write##name(SOCKET _s, uint16_t _data) { \ 253 | uint8_t buf[2]; \ 254 | buf[0] = _data >> 8; \ 255 | buf[1] = _data & 0xFF; \ 256 | writeSn(_s, address, buf, 2); \ 257 | } \ 258 | static uint16_t read##name(SOCKET _s) { \ 259 | uint8_t buf[2]; \ 260 | readSn(_s, address, buf, 2); \ 261 | return (buf[0] << 8) | buf[1]; \ 262 | } 263 | #define __SOCKET_REGISTER_N(name, address, size) \ 264 | static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \ 265 | return writeSn(_s, address, _buff, size); \ 266 | } \ 267 | static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \ 268 | return readSn(_s, address, _buff, size); \ 269 | } 270 | 271 | public: 272 | __SOCKET_REGISTER8(SnMR, 0x0000) // Mode 273 | __SOCKET_REGISTER8(SnCR, 0x0001) // Command 274 | __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt 275 | __SOCKET_REGISTER8(SnSR, 0x0003) // Status 276 | __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port 277 | __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr 278 | __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr 279 | __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port 280 | __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size 281 | __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode 282 | __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS 283 | __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL 284 | __SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only) 285 | __SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only) 286 | __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size 287 | __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer 288 | __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer 289 | __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size 290 | __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer 291 | __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?) 292 | 293 | #undef __SOCKET_REGISTER8 294 | #undef __SOCKET_REGISTER16 295 | #undef __SOCKET_REGISTER_N 296 | 297 | 298 | private: 299 | static uint8_t chip; 300 | static uint8_t ss_pin; 301 | static uint8_t softReset(void); 302 | static uint8_t isW5100(void); 303 | static uint8_t isW5200(void); 304 | static uint8_t isW5500(void); 305 | 306 | public: 307 | static uint8_t getChip(void) { return chip; } 308 | #ifdef ETHERNET_LARGE_BUFFERS 309 | static uint16_t SSIZE; 310 | static uint16_t SMASK; 311 | #else 312 | static const uint16_t SSIZE = 2048; 313 | static const uint16_t SMASK = 0x07FF; 314 | #endif 315 | static uint16_t SBASE(uint8_t socknum) { 316 | if (chip == 51) { 317 | return socknum * SSIZE + 0x4000; 318 | } else { 319 | return socknum * SSIZE + 0x8000; 320 | } 321 | } 322 | static uint16_t RBASE(uint8_t socknum) { 323 | if (chip == 51) { 324 | return socknum * SSIZE + 0x6000; 325 | } else { 326 | return socknum * SSIZE + 0xC000; 327 | } 328 | } 329 | 330 | static bool hasOffsetAddressMapping(void) { 331 | if (chip == 55) return true; 332 | return false; 333 | } 334 | static void setSS(uint8_t pin) { ss_pin = pin; } 335 | 336 | private: 337 | #if defined(__AVR__) 338 | static volatile uint8_t *ss_pin_reg; 339 | static uint8_t ss_pin_mask; 340 | inline static void initSS() { 341 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); 342 | ss_pin_mask = digitalPinToBitMask(ss_pin); 343 | pinMode(ss_pin, OUTPUT); 344 | } 345 | inline static void setSS() { 346 | *(ss_pin_reg) &= ~ss_pin_mask; 347 | } 348 | inline static void resetSS() { 349 | *(ss_pin_reg) |= ss_pin_mask; 350 | } 351 | #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) 352 | static volatile uint8_t *ss_pin_reg; 353 | inline static void initSS() { 354 | ss_pin_reg = portOutputRegister(ss_pin); 355 | pinMode(ss_pin, OUTPUT); 356 | } 357 | inline static void setSS() { 358 | *(ss_pin_reg+256) = 1; 359 | } 360 | inline static void resetSS() { 361 | *(ss_pin_reg+128) = 1; 362 | } 363 | #elif defined(__MKL26Z64__) 364 | static volatile uint8_t *ss_pin_reg; 365 | static uint8_t ss_pin_mask; 366 | inline static void initSS() { 367 | ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); 368 | ss_pin_mask = digitalPinToBitMask(ss_pin); 369 | pinMode(ss_pin, OUTPUT); 370 | } 371 | inline static void setSS() { 372 | *(ss_pin_reg+8) = ss_pin_mask; 373 | } 374 | inline static void resetSS() { 375 | *(ss_pin_reg+4) = ss_pin_mask; 376 | } 377 | #elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) 378 | static volatile uint32_t *ss_pin_reg; 379 | static uint32_t ss_pin_mask; 380 | inline static void initSS() { 381 | ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER); 382 | ss_pin_mask = digitalPinToBitMask(ss_pin); 383 | pinMode(ss_pin, OUTPUT); 384 | } 385 | inline static void setSS() { 386 | *(ss_pin_reg+13) = ss_pin_mask; 387 | } 388 | inline static void resetSS() { 389 | *(ss_pin_reg+12) = ss_pin_mask; 390 | } 391 | #elif defined(__PIC32MX__) 392 | static volatile uint32_t *ss_pin_reg; 393 | static uint32_t ss_pin_mask; 394 | inline static void initSS() { 395 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); 396 | ss_pin_mask = digitalPinToBitMask(ss_pin); 397 | pinMode(ss_pin, OUTPUT); 398 | } 399 | inline static void setSS() { 400 | *(ss_pin_reg+8+1) = ss_pin_mask; 401 | } 402 | inline static void resetSS() { 403 | *(ss_pin_reg+8+2) = ss_pin_mask; 404 | } 405 | 406 | #elif defined(ARDUINO_ARCH_ESP8266) 407 | static volatile uint32_t *ss_pin_reg; 408 | static uint32_t ss_pin_mask; 409 | inline static void initSS() { 410 | ss_pin_reg = (volatile uint32_t*)GPO; 411 | ss_pin_mask = 1 << ss_pin; 412 | pinMode(ss_pin, OUTPUT); 413 | } 414 | inline static void setSS() { 415 | GPOC = ss_pin_mask; 416 | } 417 | inline static void resetSS() { 418 | GPOS = ss_pin_mask; 419 | } 420 | 421 | #elif defined(__SAMD21G18A__) 422 | static volatile uint32_t *ss_pin_reg; 423 | static uint32_t ss_pin_mask; 424 | inline static void initSS() { 425 | ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); 426 | ss_pin_mask = digitalPinToBitMask(ss_pin); 427 | pinMode(ss_pin, OUTPUT); 428 | } 429 | inline static void setSS() { 430 | *(ss_pin_reg+5) = ss_pin_mask; 431 | } 432 | inline static void resetSS() { 433 | *(ss_pin_reg+6) = ss_pin_mask; 434 | } 435 | #else 436 | inline static void initSS() { 437 | pinMode(ss_pin, OUTPUT); 438 | } 439 | inline static void setSS() { 440 | digitalWrite(ss_pin, LOW); 441 | } 442 | inline static void resetSS() { 443 | digitalWrite(ss_pin, HIGH); 444 | } 445 | #endif 446 | }; 447 | 448 | extern W5100Class W5100; 449 | 450 | 451 | 452 | #endif 453 | 454 | #ifndef UTIL_H 455 | #define UTIL_H 456 | 457 | #ifndef htons 458 | // The host order of the Arduino platform is little endian. 459 | // Sometimes it is desired to convert to big endian (or 460 | // network order) 461 | 462 | // Host to Network short 463 | #define htons(x) ( (((x)&0xFF)<<8) | (((x)>>8)&0xFF) ) 464 | 465 | // Network to Host short 466 | #define ntohs(x) htons(x) 467 | 468 | // Host to Network long 469 | #define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ 470 | ((x)<< 8 & 0x00FF0000UL) | \ 471 | ((x)>> 8 & 0x0000FF00UL) | \ 472 | ((x)>>24 & 0x000000FFUL) ) 473 | 474 | // Network to Host long 475 | #define ntohl(x) htonl(x) 476 | 477 | #endif // !defined(htons) 478 | 479 | #endif 480 | --------------------------------------------------------------------------------