diff --git a/libs/Arduino_BuiltIn/LICENSE.txt b/libs/Arduino_BuiltIn/LICENSE.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/libs/Arduino_BuiltIn/LICENSE.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/libs/Arduino_BuiltIn/README.md b/libs/Arduino_BuiltIn/README.md new file mode 100644 index 0000000..a7e3f68 --- /dev/null +++ b/libs/Arduino_BuiltIn/README.md @@ -0,0 +1,8 @@ +# Arduino_BuiltIn library for Arduino + +[![Check Arduino status](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/check-arduino.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/check-arduino.yml) +[![Spell Check status](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/spell-check.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_BuiltIn/actions/workflows/spell-check.yml) + +Shell Arduino library to provide the standard built-in libraries. + +The sole purpose of this library is to install the standard Arduino libraries which are typically included with the Arduino IDE. This is accomplished by defining the built-in libraries as dependencies in [the library.properties metadata file](https://arduino.github.io/arduino-cli/latest/library-specification/#library-metadata). diff --git a/libs/Arduino_BuiltIn/library.properties b/libs/Arduino_BuiltIn/library.properties new file mode 100644 index 0000000..963c34c --- /dev/null +++ b/libs/Arduino_BuiltIn/library.properties @@ -0,0 +1,10 @@ +name=Arduino_BuiltIn +version=1.0.0 +author=Arduino +maintainer=Arduino +sentence=Shell Arduino library to provide the standard built-in libraries +paragraph=The sole purpose of this library is to install the standard Arduino libraries which are typically included with the Arduino IDE. +category=Other +url=https://github.com/arduino-libraries/Arduino_BuiltIn +architectures=* +depends=Ethernet,Firmata,Keyboard,LiquidCrystal,Mouse,SD,Servo,Stepper,TFT diff --git a/libs/Arduino_BuiltIn/src/Arduino_BuiltIn.h b/libs/Arduino_BuiltIn/src/Arduino_BuiltIn.h new file mode 100644 index 0000000..16a34d4 --- /dev/null +++ b/libs/Arduino_BuiltIn/src/Arduino_BuiltIn.h @@ -0,0 +1,2 @@ +// This file intentionally left empty. +// It serves only to make this shell library fully valid. diff --git a/libs/Ethernet/AUTHORS b/libs/Ethernet/AUTHORS new file mode 100644 index 0000000..1faeec4 --- /dev/null +++ b/libs/Ethernet/AUTHORS @@ -0,0 +1,36 @@ +Alberto Panu https://github.com/bigjohnson +Alasdair Allan https://github.com/aallan +Alice Pintus https://github.com/00alis +Adrian McEwen https://github.com/amcewen +Arduino LLC https://arduino.cc/ +Arnie97 https://github.com/Arnie97 +Arturo Guadalupi https://github.com/agdl +Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ +chaveiro https://github.com/chaveiro +Cristian Maglie https://github.com/cmaglie +David A. Mellis https://github.com/damellis +Dino Tinitigan https://github.com/bigdinotech +Eddy https://github.com/eddyst +Federico Vanzati https://github.com/Fede85 +Federico Fissore https://github.com/ffissore +Jack Christensen https://github.com/JChristensen +Johann Richard https://github.com/johannrichard +Jordan Terrell https://github.com/iSynaptic +Justin Paulin https://github.com/interwho +lathoub https://github.com/lathoub +Martino Facchin https://github.com/facchinm +Matthias Hertel https://github.com/mathertel +Matthijs Kooijman https://github.com/matthijskooijman +Matt Robinson https://github.com/ribbons +MCQN Ltd. http://mcqn.com/ +Michael Amie https://github.com/michaelamie +Michael Margolis https://github.com/michaelmargolis +Norbert Truchsess https://github.com/ntruchsess +Paul Stoffregen https://github.com/PaulStoffregen +per1234 https://github.com/per1234 +Richard Sim +Scott Fitzgerald https://github.com/shfitz +Thibaut Viard https://github.com/aethaniel +Tom Igoe https://github.com/tigoe +WIZnet http://www.wiznet.co.kr +Zach Eveland https://github.com/zeveland diff --git a/libs/Ethernet/README.adoc b/libs/Ethernet/README.adoc new file mode 100644 index 0000000..ed937b1 --- /dev/null +++ b/libs/Ethernet/README.adoc @@ -0,0 +1,31 @@ +:repository-owner: arduino-libraries +:repository-name: Ethernet + += {repository-name} Library for Arduino = + +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"] +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"] +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"] + +With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. + +For more information about this library please visit us at +https://www.arduino.cc/en/Reference/{repository-name} + +== License == + +Copyright (c) 2010 Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libs/Ethernet/docs/api.md b/libs/Ethernet/docs/api.md new file mode 100644 index 0000000..76265c8 --- /dev/null +++ b/libs/Ethernet/docs/api.md @@ -0,0 +1,2607 @@ +# Ethernet Library + +## Ethernet Class + +### `Ethernet.begin()` + +#### Description + +Initializes the Ethernet library and network settings. + +With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly. To make sure the DHCP lease is properly renewed when needed, be sure to call Ethernet.maintain() regularly. + + +#### Syntax + +``` +Ethernet.begin(mac); +Ethernet.begin(mac, ip); +Ethernet.begin(mac, ip, dns); +Ethernet.begin(mac, ip, dns, gateway); +Ethernet.begin(mac, ip, dns, gateway, subnet); +``` + +#### Parameters +- mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own. +- ip: the IP address of the device (array of 4 bytes) +- dns: the IP address of the DNS server (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1 +- gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1 +- subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0 + +#### Returns +- The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. +- The other versions don't return anything. + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; + +void setup() +{ + Ethernet.begin(mac, ip); +} + +void loop () {} +``` + +### `Ethernet.dnsServerIP()` + +#### Description + +Returns the DNS server IP address for the device. + + +#### Syntax + +``` +Ethernet.dnsServerIP() + +``` + +#### Parameters +none + +#### Returns +- the DNS server IP address for the device (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The DNS server IP address is: "); + Serial.println(Ethernet.dnsServerIP()); +} + +void loop () {} +``` + +### `Ethernet.gatewayIP()` + +#### Description + +Returns the gateway IP address for the device. + + +#### Syntax + +``` +Ethernet.gatewayIP() + +``` + +#### Parameters +none + +#### Returns +- the gateway IP address for the device (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The gateway IP address is: "); + Serial.println(Ethernet.gatewayIP()); +} + +void loop () {} +``` + +### `Ethernet.hardwareStatus()` + +#### Description + +Ethernet.hardwareStatus() tells you which WIZnet Ethernet controller chip was detected during Ethernet.begin(), if any. This can be used for troubleshooting. If no Ethernet controller was detected then there is likely a hardware problem. + + +#### Syntax + +``` +Ethernet.hardwareStatus() + +``` + +#### Parameters +none + +#### Returns +- which WIZnet Ethernet controller chip was detected during Ethernet.begin() (EthernetHardwareStatus): + +``` +EthernetNoHardware +EthernetW5100 +EthernetW5200 +EthernetW5500 +``` + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found."); + } + else if (Ethernet.hardwareStatus() == EthernetW5100) { + Serial.println("W5100 Ethernet controller detected."); + } + else if (Ethernet.hardwareStatus() == EthernetW5200) { + Serial.println("W5200 Ethernet controller detected."); + } + else if (Ethernet.hardwareStatus() == EthernetW5500) { + Serial.println("W5500 Ethernet controller detected."); + } +} + +void loop () {} +``` + +### `Ethernet.init()` + +#### Description + +Used to configure the CS (chip select) pin for the Ethernet controller chip. The Ethernet library has a default CS pin, which is usually correct, but with some non-standard Ethernet hardware you might need to use a different CS pin. + + +#### Syntax + +``` +Ethernet.init(sspin) + +``` + +#### Parameters +- sspin: the pin number to use for CS (byte) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.init(53); // use pin 53 for Ethernet CS + Ethernet.begin(mac, ip); +} + +void loop () {} +``` + +### `Ethernet.linkStatus()` + +#### Description + +Tells you whether the link is active. LinkOFF could indicate the Ethernet cable is unplugged or defective. This feature is only available when using the W5200 and W5500 Ethernet controller chips. + + +#### Syntax + +``` +Ethernet.linkStatus() + +``` + +#### Parameters +none + +#### Returns +- the link status (EthernetLinkStatus): + +- Unknown + +- LinkON + +- LinkOFF + +#### Example + +``` +#include +#include + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } +} + +void loop () { + if (Ethernet.linkStatus() == Unknown) { + Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500."); + } + else if (Ethernet.linkStatus() == LinkON) { + Serial.println("Link status: On"); + } + else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Link status: Off"); + } +} +``` + +### `Ethernet.localIP()` + +#### Description + +Obtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP. + + +#### Syntax + +``` +Ethernet.localIP(); + +``` + +#### Parameters +none + +#### Returns +- the IP address + +#### Example + +``` +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +EthernetClient client; + +void setup() { + // start the serial library: + Serial.begin(9600); + // start the Ethernet connection: + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for(;;) + ; + } + // print your local IP address: + Serial.println(Ethernet.localIP()); + +} + +void loop() { + +} +``` + +### `Ethernet.MACAddress()` + +#### Description + +Fills the supplied buffer with the MAC address of the device. + + +#### Syntax + +``` +Ethernet.MACAddress(mac_address) + +``` + +#### Parameters +- mac_address: buffer to receive the MAC address (array of 6 bytes) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + byte macBuffer[6]; // create a buffer to hold the MAC address + Ethernet.MACAddress(macBuffer); // fill the buffer + Serial.print("The MAC address is: "); + for (byte octet = 0; octet < 6; octet++) { + Serial.print(macBuffer[octet], HEX); + if (octet < 5) { + Serial.print('-'); + } + } +} + +void loop () {} + +``` + +### `Ethernet.maintain()` + +#### Description + +Allows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of time. With Ethernet.maintain(), it is possible to request a renewal from the DHCP server. Depending on the server's configuration, you may receive the same address, a new one, or none at all. + +You can call this function as often as you want, it will only re-request a DHCP lease when needed (returning 0 in all other cases). The easiest way is to just call it on every loop() invocation, but less often is also fine. Not calling this function (or calling it significantly less then once per second) will prevent the lease to be renewed when the DHCP protocol requires this, continuing to use the expired lease instead (which will not directly break connectivity, but if the DHCP server leases the same address to someone else, things will likely break). + +Ethernet.maintain() was added to Arduino 1.0.1. + + +#### Syntax + +``` +Ethernet.maintain(); + +``` + +#### Parameters +none + +#### Returns + +byte: + +- 0: nothing happened + +- 1: renew failed + +- 2: renew success + +- 3: rebind fail + +- 4: rebind success + +### `Ethernet.setDnsServerIP()` + +#### Description + +Set the IP address of the DNS server. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setDnsServerIP(dns_server) + +``` + +#### Parameters +- dns_server: the IP address of the DNS server (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); + +void setup() { + Ethernet.begin(mac, ip, myDns); + IPAddress newDns(192, 168, 1, 1); + Ethernet.setDnsServerIP(newDns); // change the DNS server IP address +} + +void loop () {} +``` + +### `Ethernet.setGatewayIP()` + +#### Description + +Set the IP address of the network gateway. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setGatewayIP(gateway) + +``` + +#### Parameters +- gateway: the IP address of the network gateway (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); + +void setup() { + Ethernet.begin(mac, ip, myDns, gateway); + IPAddress newGateway(192, 168, 100, 1); + Ethernet.setGatewayIP(newGateway); // change the gateway IP address +} + +void loop () {} +``` + +### `Ethernet.setLocalIP()` + +#### Description + +Set the IP address of the device. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setLocalIP(local_ip) + +``` + +#### Parameters +- local_ip: the IP address to use (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + IPAddress newIp(10, 0, 0, 178); + Ethernet.setLocalIP(newIp); // change the IP address +} + +void loop () {} +``` + +### `Ethernet.setMACAddress()` + +#### Description + +Set the MAC address. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setMACAddress(mac) + +``` + +#### Parameters +- mac: the MAC address to use (array of 6 bytes) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + byte newMac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; + Ethernet.setMACAddress(newMac); // change the MAC address +} + +void loop () {} +``` + +### `Ethernet.setRetransmissionCount()` + +#### Description + +Set the number of transmission attempts the Ethernet controller will make before giving up. The initial value is 8. 8 transmission attempts times the 200 ms default timeout equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a lower number to make your program more responsive in the event something goes wrong with communications. Despite the name, this sets the total number of transmission attempts (not the number of retries after the first attempt fails) so the minimum value you would ever want to set is 1. + + +#### Syntax + +``` +Ethernet.setRetransmissionCount(number) + +``` + +#### Parameters +- number: number of transmission attempts the Ethernet controller should make before giving up (byte) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + Ethernet.setRetransmissionCount(1); // configure the Ethernet controller to only attempt one transmission before giving up +} + +void loop () {} +``` + +### `Ethernet.setRetransmissionTimeout()` + +#### Description + +Set the Ethernet controller's timeout. The initial value is 200 ms. A 200 ms timeout times the default of 8 attempts equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a shorter timeout to make your program more responsive in the event something goes wrong with communications. You will need to do some experimentation to determine an appropriate value for your specific application. + + +#### Syntax + +``` +Ethernet.setRetransmissionTimeout(milliseconds) + +``` + +#### Parameters +- milliseconds: the timeout duration (uint16_t) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + Ethernet.setRetransmissionTimeout(50); // set the Ethernet controller's timeout to 50 ms +} + +void loop () {} +``` + +### `Ethernet.setSubnetMask()` + +#### Description + +Set the subnet mask of the network. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setSubnetMask(subnet) + +``` + +#### Parameters +- subnet: the subnet mask of the network (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + +void setup() { + Ethernet.begin(mac, ip, myDns, gateway, subnet); + IPAddress newSubnet(255, 255, 255, 0); + Ethernet.setSubnetMask(newSubnet); // change the subnet mask +} + +void loop () {} +``` + +### `Ethernet.subnetMask()` + +#### Description + +Returns the subnet mask of the device. + + +#### Syntax + +``` +Ethernet.subnetMask() + +``` + +#### Parameters +none + +#### Returns +- the subnet mask of the device (IPAddress) + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The subnet mask is: "); + Serial.println(Ethernet.subnetMask()); +} + +void loop () {} +``` + +## IPAddress Class + +### `IPAddress()` + +#### Description + +Defines an IP address. It can be used to declare both local and remote addresses. + + +#### Syntax + +``` +IPAddress(address); + +``` + +#### Parameters +- address: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1) + +#### Returns +None + +#### Example + +``` +#include +#include + +// network configuration. dns server, gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// the dns server ip +IPAddress dnServer(192, 168, 0, 1); +// the router's gateway address: +IPAddress gateway(192, 168, 0, 1); +// the subnet: +IPAddress subnet(255, 255, 255, 0); + +//the IP address is dependent on your network +IPAddress ip(192, 168, 0, 2); + +void setup() { + Serial.begin(9600); + + // initialize the ethernet device + Ethernet.begin(mac, ip, dnServer, gateway, subnet); + //print out the IP address + Serial.print("IP = "); + Serial.println(Ethernet.localIP()); +} + +void loop() { +} +``` + +## Server Class + +### `Server` + +#### Description +Server is the base class for all Ethernet server based calls. It is not called directly, but invoked whenever you use a function that relies on it. + +### `EthernetServer()` + +#### Description + +Create a server that listens for incoming connections on the specified port. + + +#### Syntax + +``` +Server(port); + +``` + +#### Parameters +- port: the port to listen on (int) + +#### Returns +None + +#### Example + +``` +#include +#include + +// network configuration. gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.begin()` + +#### Description + +Tells the server to begin listening for incoming connections. + + +#### Syntax + +``` +server.begin() + +``` + +#### Parameters +None + +#### Returns +None + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.accept()` + +#### Description + +The traditional server.available() function would only tell you of a new client after it sent data, which makes some protocols like FTP impossible to properly implement. + +The intention is programs will use either available() or accept(), but not both. With available(), the client connection continues to be managed by EthernetServer. You don’t need to keep a client object, since calling available() will give you whatever client has sent data. Simple servers can be written with very little code using available(). + +With accept(), EthernetServer gives you the client only once, regardless of whether it has sent any data. You must keep track of the connected clients. This requires more code, but you gain more control. + + +#### Syntax + +``` +server.accept() + +``` + +#### Parameters +none + +#### Returns +- a Client object. If no client has data available for reading, this object will evaluate to false in an if-statement. (EthernetClient). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(192, 168, 69, 104); + +// telnet defaults to port 23 +EthernetServer server(23); + +EthernetClient clients[8]; + +void setup() { + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start listening for clients + server.begin(); +} + +void loop() { + // check for any new client connecting, and say hello (before any incoming data) + EthernetClient newClient = server.accept(); + if (newClient) { + for (byte i = 0; i < 8; i++) { + if (!clients[i]) { + newClient.print("Hello, client number: "); + newClient.println(i); + // Once we "accept", the client is no longer tracked by EthernetServer + // so we must store it into our list of clients + clients[i] = newClient; + break; + } + } + } + + // check for incoming data from all clients + for (byte i = 0; i < 8; i++) { + while (clients[i] && clients[i].available() > 0) { + // read incoming data from the client + Serial.write(clients[i].read()); + } + } + + // stop any clients which disconnect + for (byte i = 0; i < 8; i++) { + if (clients[i] && !clients[i].connected()) { + clients[i].stop(); + } + } +} +``` + +### `server.available()` + +#### Description + +Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop(). + + +#### Syntax + +``` +server.available() + +``` + +#### Parameters +None + +#### Returns +- a Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement (see the example below) + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `if(server)` + +#### Description +Indicates whether the server is listening for new clients. You can use this to detect whether server.begin() was successful. It can also tell you when no more sockets are available to listen for more clients, because the maximum number have connected. + + +#### Syntax + +``` +if(server) + +``` + +#### Parameters +none + +#### Returns +- whether the server is listening for new clients (bool). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + if (server) { + Serial.println("Server is listening"); + } + else { + Serial.println("Server is not listening"); + } +} +``` + +### `server.write()` + +#### Description + +Write data to all the clients connected to a server. This data is sent as a byte or series of bytes. + + +#### Syntax + +``` +server.write(val) +server.write(buf, len) + +``` + +#### Parameters +- val: a value to send as a single byte (byte or char) + +- buf: an array to send as a series of bytes (byte or char) + +- len: the length of the buffer + +#### Returns +- byte +- write() returns the number of bytes written. It is not necessary to read this. + +#### Example + +``` +#include +#include + +// network configuration. gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.print()` + +#### Description + +Print data to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +server.print(data) +server.print(data, BASE) + +``` + +#### Parameters +- data: the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte +- print() will return the number of bytes written, though reading that number is optional + + +### `server.println()` + +#### Description + +Print data, followed by a newline, to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +server.println() +server.println(data) +server.println(data, BASE) + +``` + +#### Parameters +- data (optional): the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte + +- println() will return the number of bytes written, though reading that number is optional + +## Client Class + +### `Client` + +#### Description +Client is the base class for all Ethernet client based calls. It is not called directly, but invoked whenever you use a function that relies on it. + +### `EthernetClient()` + +#### Description + +Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function). + + +#### Syntax + +``` +EthernetClient() + +``` + +#### Parameters +None + +#### Example + +``` +#include +#include + + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `if (EthernetClient)` + +#### Description +Indicates if the specified Ethernet client is ready. + + +#### Syntax + +``` +if (client) + +``` + +#### Parameters +none + +#### Returns +- boolean : returns true if the specified client is available. + +#### Example + +``` +#include +#include + + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + while(!client){ + ; // wait until there is a client connected to proceed + } + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} + +``` + +### `client.connected()` + +#### Description + +Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data. + + +#### Syntax + +``` +client.connected() + +``` + +#### Parameters +none + +#### Returns +- Returns true if the client is connected, false if not. + +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + client.connect(server, 80); + delay(1000); + + Serial.println("connecting..."); + + if (client.connected()) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.connect()` + +#### Description + +Connects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name. + + +#### Syntax + +``` +client.connect() +client.connect(ip, port) +client.connect(URL, port) + +``` + +#### Parameters +- ip: the IP address that the client will connect to (array of 4 bytes) + +- URL: the domain name the client will connect to (string, ex.:"arduino.cc") + +- port: the port that the client will connect to (int) + +#### Returns +- Returns an int (1,-1,-2,-3,-4) indicating connection status : + +- SUCCESS 1 +- TIMED_OUT -1 +- INVALID_SERVER -2 +- TRUNCATED -3 +- INVALID_RESPONSE -4 +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.localPort()` + +#### Description + +Returns the local port number the client is connected to. + + +#### Syntax + +``` +client.localPort + +``` + +#### Parameters +none + +#### Returns +- the local port number the client is connected to (uint16_t). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Client is connected on port: "); + Serial.println(client.localPort()); + client.stop(); + } +} +``` + +### `client.remoteIP()` + +#### Description + +Returns the IP address of the client. + + +#### Syntax + +``` +client.remoteIP() + +``` + +#### Parameters +none + +#### Returns +- the client's IP address (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Remote IP address: "); + Serial.println(client.remoteIP()); + client.stop(); + } +} +``` + +### `client.remotePort()` + +#### Description + +Returns the port of the host that sent the current incoming packet. + + +#### Syntax + +``` +client.remotePort() + +``` + +#### Parameters +none + +#### Returns +- the port of the host that sent the current incoming packet (uint16_t). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Remote port: "); + Serial.println(client.remotePort()); + client.stop(); + } +} +``` + +### `client.setConnectionTimeout()` + +#### Description + +Set the timeout for client.connect() and client.stop(). The initial value is 1000 ms. You might prefer to set a lower timeout value to make your program more responsive in the event something goes wrong. + + +#### Syntax + +``` +client.setConnectionTimeout(milliseconds) + +``` + +#### Parameters +- milliseconds: the timeout duration for client.connect() and client.stop() (uint16_t) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + client.setConnectionTimeout(100); // set the timeout duration for client.connect() and client.stop() + } +} +``` + +### `client.write()` + +#### Description + +Write data to the server the client is connected to. This data is sent as a byte or series of bytes. + + +#### Syntax + +``` +client.write(val) +client.write(buf, len) + +``` + +#### Parameters +- val: a value to send as a single byte (byte or char) + +- buf: an array to send as a series of bytes (byte or char) + +- len: the length of the buffer + +#### Returns +byte: +- write() returns the number of bytes written. It is not necessary to read this value. + +### `print()` + +#### Description + +Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +client.print(data) +client.print(data, BASE) + +``` + +#### Parameters +- data: the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). +#### Returns +- byte: returns the number of bytes written, though reading that number is optional + +### `client.println()` + +#### Description + +Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +client.println() +client.println(data) +client.print(data, BASE) + +``` + +#### Parameters +- data (optional): the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte: return the number of bytes written, though reading that number is optional + + +### `client.available()` + +#### Description + +Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to). + +available() inherits from the Stream utility class. + + +#### Syntax + +``` +client.available() + +``` + +#### Parameters +none + +#### Returns +- The number of bytes available. + +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.read()` + +#### Description + +Read the next byte received from the server the client is connected to (after the last call to read()). + +read() inherits from the Stream utility class. + + +#### Syntax + +``` +client.read() + +``` + +#### Parameters +none + +#### Returns +- The next byte (or character), or -1 if none is available. + +### `client.flush()` +Waits until all outgoing characters in buffer have been sent. + +flush() inherits from the Stream utility class. + + +#### Syntax + +``` +client.flush() + +``` + +#### Parameters +none + +#### Returns +none + +### `client.stop()` + +#### Description + +Disconnect from the server. + + +#### Syntax + +``` +client.stop() + +``` + +#### Parameters +none + +#### Returns +none + +## EthernetUDP Class + +### `EthernetUDP.begin()` + +#### Description +Initializes the ethernet UDP library and network settings. + + +#### Syntax + +``` +EthernetUDP.begin(localPort); +``` + +#### Parameters +- localPort: the local port to listen on (int) + +#### Returns +- 1 if successful, 0 if there are no sockets available to use. + +#### Example + +``` + +#include + +#include + +#include + + + +// Enter a MAC address and IP address for your controller below. + +// The IP address will be dependent on your local network: + +byte mac[] = { + + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +IPAddress ip(192, 168, 1, 177); + + + +unsigned int localPort = 8888; // local port to listen on + + + +// An EthernetUDP instance to let us send and receive packets over UDP + +EthernetUDP Udp; + + + +void setup() { + + // start the Ethernet and UDP: + + Ethernet.begin(mac,ip); + + Udp.begin(localPort); + + + +} + + + +void loop() { +} + + +``` + +### `EthernetUDP.read()` + +#### Description +Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer. + +This function can only be successfully called after UDP.parsePacket(). + + +#### Syntax + +``` +EthernetUDP.read(); +EthernetUDP.read(packetBuffer, MaxSize); +``` + +#### Parameters +- packetBuffer: buffer to hold incoming packets (char) +- MaxSize: maximum size of the buffer (int) + +#### Returns +- char : returns the characters in the buffer + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); +} +} +``` + +### `EthernetUDP.write()` + +#### Description +Writes UDP data to the remote connection. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called. + + +#### Syntax + +``` +EthernetUDP.write(message); +EthernetUDP.write(buffer, size); + +``` + +#### Parameters + +- message: the outgoing message (char) + +- buffer: an array to send as a series of bytes (byte or char) + +- size: the length of the buffer + +#### Returns +- byte : returns the number of characters sent. This does not have to be read + +#### Example + +``` + + + +#include + +#include + +#include + + + +// Enter a MAC address and IP address for your controller below. + +// The IP address will be dependent on your local network: + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +IPAddress ip(192, 168, 1, 177); + + + +unsigned int localPort = 8888; // local port to listen on + + + +// An EthernetUDP instance to let us send and receive packets over UDP + +EthernetUDP Udp; + + + +void setup() { + + // start the Ethernet and UDP: + + Ethernet.begin(mac,ip); + + Udp.begin(localPort); + +} + + + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + + Udp.write("hello"); + + Udp.endPacket(); + +} + + +``` + +### `EthernetUDP.beginPacket()` + +#### Description +Starts a connection to write UDP data to the remote connection + + +#### Syntax + +``` +EthernetUDP.beginPacket(remoteIP, remotePort); +``` + +#### Parameters +- remoteIP: the IP address of the remote connection (4 bytes) +- remotePort: the port of the remote connection (int) +#### Returns +- Returns an int: 1 if successful, 0 if there was a problem resolving the hostname or port. + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write("hello"); + Udp.endPacket(); + +} +``` + +### `EthernetUDP.endPacket()` + +#### Description +Called after writing UDP data to the remote connection. + + +#### Syntax + +``` +EthernetUDP.endPacket(); +``` + +#### Parameters +None + +#### Returns +- Returns an int: 1 if the packet was sent successfully, 0 if there was an error + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write("hello"); + Udp.endPacket(); + +} +``` + +### `EthernetUDP.parsePacket()` + +#### Description +Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read(). + + +#### Syntax + +``` +EthernetUDP.parsePacket(); +``` + +#### Parameters +None + +#### Returns +- int: the size of a received UDP packet + +#### Example + +``` + +#include // needed for Arduino versions later than 0018 +#include +#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008 + + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + + Serial.begin(9600); +} + +void loop() { + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + } + delay(10); +} +``` + +### `EthernetUDP.available()` + +#### Description + +Get the number of bytes (characters) available for reading from the buffer. This is data that's already arrived. + +This function can only be successfully called after UDP.parsePacket(). + +available() inherits from the Stream utility class. + + +#### Syntax + +``` +EthernetUDP.available() + +``` + +#### Parameters +None + +#### Returns +- the number of bytes available to read + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(Udp.available()) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + } +} +``` + +## UDP class + +### `UDP.stop()` + +#### Description + +Disconnect from the server. Release any resource being used during the UDP session. + + +#### Syntax + +``` +UDP.stop() + +``` + +#### Parameters +none + +#### Returns +none + +### `UDP.remoteIP()` + +#### Description +Gets the IP address of the remote connection. + +This function must be called after UDP.parsePacket(). + + +#### Syntax + +``` +UDP.remoteIP(); +``` + +#### Parameters +None + +#### Returns +- 4 bytes : the IP address of the remote connection + +#### Example + +``` + +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From IP : "); + + IPAddress remote = Udp.remoteIP(); + //print out the remote connection's IP address + Serial.print(remote); + + Serial.print(" on port : "); + //print out the remote connection's port + Serial.println(Udp.remotePort()); + } + +} + + +``` + +### `UDP.remotePort()` + +#### Description +Gets the port of the remote UDP connection. + +This function must be called after UDP.parsePacket(). + + +#### Syntax + +``` +UDP.remotePort(); +``` + +#### Parameters +None + +#### Returns +- int : the port of the UDP connection to a remote host + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + } +} +``` \ No newline at end of file diff --git a/libs/Ethernet/docs/arduino_mega_ethernet_pins.png b/libs/Ethernet/docs/arduino_mega_ethernet_pins.png new file mode 100644 index 0000000..e35edc2 Binary files /dev/null and b/libs/Ethernet/docs/arduino_mega_ethernet_pins.png differ diff --git a/libs/Ethernet/docs/arduino_uno_ethernet_pins.png b/libs/Ethernet/docs/arduino_uno_ethernet_pins.png new file mode 100644 index 0000000..ae7e520 Binary files /dev/null and b/libs/Ethernet/docs/arduino_uno_ethernet_pins.png differ diff --git a/libs/Ethernet/docs/readme.md b/libs/Ethernet/docs/readme.md new file mode 100644 index 0000000..cdb2044 --- /dev/null +++ b/libs/Ethernet/docs/readme.md @@ -0,0 +1,16 @@ +# Ethernet Library + +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). + +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. + +![Arduino UNO Pin map.](./arduino_uno_ethernet_pins.png) + +![Arduino MEGA Pin map.](./arduino_mega_ethernet_pins.png) + +To use this library + +``` +#include +#include +``` \ No newline at end of file diff --git a/libs/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino b/libs/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino new file mode 100644 index 0000000..c97a958 --- /dev/null +++ b/libs/Ethernet/examples/AdvancedChatServer/AdvancedChatServer.ino @@ -0,0 +1,119 @@ +/* + Advanced Chat Server + + A more advanced server that distributes any incoming messages + to all connected clients but the client the message comes from. + To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino WIZnet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + redesigned to make use of operator== 25 Nov 2013 + by Norbert Truchsess + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + + +// telnet defaults to port 23 +EthernetServer server(23); + +EthernetClient clients[8]; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // initialize the Ethernet device + Ethernet.begin(mac, ip, myDns, gateway, subnet); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + Serial.print("Chat server address:"); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // check for any new client connecting, and say hello (before any incoming data) + EthernetClient newClient = server.accept(); + if (newClient) { + for (byte i=0; i < 8; i++) { + if (!clients[i]) { + Serial.print("We have a new client #"); + Serial.println(i); + newClient.print("Hello, client number: "); + newClient.println(i); + // Once we "accept", the client is no longer tracked by EthernetServer + // so we must store it into our list of clients + clients[i] = newClient; + break; + } + } + } + + // check for incoming data from all clients + for (byte i=0; i < 8; i++) { + if (clients[i] && clients[i].available() > 0) { + // read bytes from a client + byte buffer[80]; + int count = clients[i].read(buffer, 80); + // write the bytes to all other connected clients + for (byte j=0; j < 8; j++) { + if (j != i && clients[j].connected()) { + clients[j].write(buffer, count); + } + } + } + } + + // stop any clients which disconnect + for (byte i=0; i < 8; i++) { + if (clients[i] && !clients[i].connected()) { + Serial.print("disconnect client #"); + Serial.println(i); + clients[i].stop(); + } + } +} diff --git a/libs/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino b/libs/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino new file mode 100644 index 0000000..831f17f --- /dev/null +++ b/libs/Ethernet/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino @@ -0,0 +1,247 @@ +/* + SCP1000 Barometric Pressure Sensor Display + + Serves the output of a Barometric Pressure Sensor as a web page. + Uses the SPI library. For details on the sensor, see: + http://www.sparkfun.com/commerce/product_info.php?products_id=8161 + + This sketch adapted from Nathan Seidle's SCP1000 example for PIC: + http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip + + TODO: this hardware is long obsolete. This example program should + be rewritten to use https://www.sparkfun.com/products/9721 + + Circuit: + SCP1000 sensor attached to pins 6,7, and 11 - 13: + DRDY: pin 6 + CSB: pin 7 + MOSI: pin 11 + MISO: pin 12 + SCK: pin 13 + + created 31 July 2010 + by Tom Igoe + */ + +#include +// the sensor communicates using SPI, so include the library: +#include + + +// assign a MAC address for the Ethernet controller. +// fill in your address here: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +// assign an IP address for the controller: +IPAddress ip(192, 168, 1, 20); + + +// Initialize the Ethernet server library +// with the IP address and port you want to use +// (port 80 is default for HTTP): +EthernetServer server(80); + + +//Sensor's memory register addresses: +const int PRESSURE = 0x1F; //3 most significant bits of pressure +const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure +const int TEMPERATURE = 0x21; //16 bit temperature reading + +// pins used for the connection with the sensor +// the others you need are controlled by the SPI library): +const int dataReadyPin = 6; +const int chipSelectPin = 7; + +float temperature = 0.0; +long pressure = 0; +long lastReadingTime = 0; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // start the SPI library: + SPI.begin(); + + // start the Ethernet connection + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + // initialize the data ready and chip select pins: + pinMode(dataReadyPin, INPUT); + pinMode(chipSelectPin, OUTPUT); + + //Configure SCP1000 for low noise configuration: + writeRegister(0x02, 0x2D); + writeRegister(0x01, 0x03); + writeRegister(0x03, 0x02); + + // give the sensor and Ethernet shield time to set up: + delay(1000); + + //Set the sensor to high resolution mode to start readings: + writeRegister(0x03, 0x0A); + +} + +void loop() { + // check for a reading no more than once a second. + if (millis() - lastReadingTime > 1000) { + // if there's a reading ready, read it: + // don't do anything until the data ready pin is high: + if (digitalRead(dataReadyPin) == HIGH) { + getData(); + // timestamp the last time you got a reading: + lastReadingTime = millis(); + } + } + + // listen for incoming Ethernet connections: + listenForEthernetClients(); +} + + +void getData() { + Serial.println("Getting reading"); + //Read the temperature data + int tempData = readRegister(0x21, 2); + + // convert the temperature to Celsius and display it: + temperature = (float)tempData / 20.0; + + //Read the pressure data highest 3 bits: + byte pressureDataHigh = readRegister(0x1F, 1); + pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0 + + //Read the pressure data lower 16 bits: + unsigned int pressureDataLow = readRegister(0x20, 2); + //combine the two parts into one 19-bit number: + pressure = ((pressureDataHigh << 16) | pressureDataLow) / 4; + + Serial.print("Temperature: "); + Serial.print(temperature); + Serial.println(" degrees C"); + Serial.print("Pressure: " + String(pressure)); + Serial.println(" Pa"); +} + +void listenForEthernetClients() { + // listen for incoming clients + EthernetClient client = server.available(); + if (client) { + Serial.println("Got a client"); + // an HTTP request ends with a blank line + bool currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the HTTP request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard HTTP response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println(); + // print the current readings, in HTML format: + client.print("Temperature: "); + client.print(temperature); + client.print(" degrees C"); + client.println("
"); + client.print("Pressure: " + String(pressure)); + client.print(" Pa"); + client.println("
"); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + // close the connection: + client.stop(); + } +} + + +//Send a write command to SCP1000 +void writeRegister(byte registerName, byte registerValue) { + // SCP1000 expects the register name in the upper 6 bits + // of the byte: + registerName <<= 2; + // command (read or write) goes in the lower two bits: + registerName |= 0b00000010; //Write command + + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + + SPI.transfer(registerName); //Send register location + SPI.transfer(registerValue); //Send value to record into register + + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); +} + + +//Read register from the SCP1000: +unsigned int readRegister(byte registerName, int numBytes) { + byte inByte = 0; // incoming from the SPI read + unsigned int result = 0; // result to return + + // SCP1000 expects the register name in the upper 6 bits + // of the byte: + registerName <<= 2; + // command (read or write) goes in the lower two bits: + registerName &= 0b11111100; //Read command + + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + // send the device the register you want to read: + SPI.transfer(registerName); + // send a value of 0 to read the first byte returned: + inByte = SPI.transfer(0x00); + + result = inByte; + // if there's more than one byte returned, + // shift the first byte then get the second byte: + if (numBytes > 1) { + result = inByte << 8; + inByte = SPI.transfer(0x00); + result = result | inByte; + } + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); + // return the result: + return (result); +} diff --git a/libs/Ethernet/examples/ChatServer/ChatServer.ino b/libs/Ethernet/examples/ChatServer/ChatServer.ino new file mode 100644 index 0000000..3e28060 --- /dev/null +++ b/libs/Ethernet/examples/ChatServer/ChatServer.ino @@ -0,0 +1,96 @@ +/* + Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino WIZnet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + + +// telnet defaults to port 23 +EthernetServer server(23); +bool alreadyConnected = false; // whether or not the client was connected previously + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // initialize the Ethernet device + Ethernet.begin(mac, ip, myDns, gateway, subnet); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start listening for clients + server.begin(); + + Serial.print("Chat server address:"); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // wait for a new client: + EthernetClient client = server.available(); + + // when the client sends the first byte, say hello: + if (client) { + if (!alreadyConnected) { + // clear out the input buffer: + client.flush(); + Serial.println("We have a new client"); + client.println("Hello, client!"); + alreadyConnected = true; + } + + if (client.available() > 0) { + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.write(thisChar); + } + } +} diff --git a/libs/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/libs/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino new file mode 100644 index 0000000..612106f --- /dev/null +++ b/libs/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino @@ -0,0 +1,94 @@ +/* + DHCP-based IP printer + + This sketch uses the DHCP extensions to the Ethernet library + to get an IP address via DHCP and print the address obtained. + using an Arduino WIZnet Ethernet shield. + + Circuit: + Ethernet shield attached to pins 10, 11, 12, 13 + + created 12 April 2011 + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + */ + +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + } else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // no point in carrying on, so do nothing forevermore: + while (true) { + delay(1); + } + } + // print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); +} + +void loop() { + switch (Ethernet.maintain()) { + case 1: + //renewed fail + Serial.println("Error: renewed fail"); + break; + + case 2: + //renewed success + Serial.println("Renewed success"); + //print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + break; + + case 3: + //rebind fail + Serial.println("Error: rebind fail"); + break; + + case 4: + //rebind success + Serial.println("Rebind success"); + //print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + break; + + default: + //nothing happened + break; + } +} diff --git a/libs/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino b/libs/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino new file mode 100644 index 0000000..01cd814 --- /dev/null +++ b/libs/Ethernet/examples/DhcpChatServer/DhcpChatServer.ino @@ -0,0 +1,101 @@ +/* + DHCP Chat Server + + A simple server that distributes any incoming messages to all + connected clients. To use, telnet to your device's IP address and type. + You can see the client's input in the serial monitor as well. + Using an Arduino WIZnet Ethernet shield. + + THis version attempts to get an IP address using DHCP + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 21 May 2011 + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + Based on ChatServer example by David A. Mellis + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network. +// gateway and subnet are optional: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + +// telnet defaults to port 23 +EthernetServer server(23); +bool gotAMessage = false; // whether or not you got a message from the client yet + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Trying to get an IP address using DHCP"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // initialize the Ethernet device not using DHCP: + Ethernet.begin(mac, ip, myDns, gateway, subnet); + } + // print your local IP address: + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + + // start listening for clients + server.begin(); +} + +void loop() { + // wait for a new client: + EthernetClient client = server.available(); + + // when the client sends the first byte, say hello: + if (client) { + if (!gotAMessage) { + Serial.println("We have a new client"); + client.println("Hello, client!"); + gotAMessage = true; + } + + // read the bytes incoming from the client: + char thisChar = client.read(); + // echo the bytes back to the client: + server.write(thisChar); + // echo the bytes to the server as well: + Serial.print(thisChar); + Ethernet.maintain(); + } +} diff --git a/libs/Ethernet/examples/LinkStatus/LinkStatus.ino b/libs/Ethernet/examples/LinkStatus/LinkStatus.ino new file mode 100644 index 0000000..84651d0 --- /dev/null +++ b/libs/Ethernet/examples/LinkStatus/LinkStatus.ino @@ -0,0 +1,44 @@ +/* + Link Status + + This sketch prints the Ethernet link status. When the + Ethernet cable is connected the link status should go to "ON". + NOTE: Only WIZnet W5200 and W5500 are capable of reporting + the link status. W5100 will report "Unknown". + Hardware: + - Ethernet shield or equivalent board/shield with WIZnet W5200/W5500 + Written by Cristian Maglie + This example is public domain. +*/ + +#include +#include + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + Serial.begin(9600); +} + +void loop() { + auto link = Ethernet.linkStatus(); + Serial.print("Link status: "); + switch (link) { + case Unknown: + Serial.println("Unknown"); + break; + case LinkON: + Serial.println("ON"); + break; + case LinkOFF: + Serial.println("OFF"); + break; + } + delay(1000); +} diff --git a/libs/Ethernet/examples/PagerServer/PagerServer.ino b/libs/Ethernet/examples/PagerServer/PagerServer.ino new file mode 100644 index 0000000..e17ae6e --- /dev/null +++ b/libs/Ethernet/examples/PagerServer/PagerServer.ino @@ -0,0 +1,71 @@ +/* + Pager Server + + A simple server that echoes any incoming messages to all + connected clients. Connect two or more telnet sessions + to see how server.available() and server.print() works. + + created in September 2020 for the Ethernet library + by Juraj Andrassy https://github.com/jandrassy + +*/ +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); + +EthernetServer server(2323); + +void setup() { + + Serial.begin(9600); + while (!Serial); + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to configure using IP address instead of DHCP: + Ethernet.begin(mac, ip); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + + server.begin(); + + IPAddress ip = Ethernet.localIP(); + Serial.println(); + Serial.print("To access the server, connect with Telnet client to "); + Serial.print(ip); + Serial.println(" 2323"); +} + +void loop() { + + EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client + if (client) { // client is true only if it is connected and has data to read + String s = client.readStringUntil('\n'); // read the message incoming from one of the clients + s.trim(); // trim eventual \r + Serial.println(s); // print the message to Serial Monitor + client.print("echo: "); // this is only for the sending client + server.println(s); // send the message to all connected clients +#ifndef ARDUINO_ARCH_SAM + server.flush(); // flush the buffers +#endif /* !defined(ARDUINO_ARCH_SAM) */ + } +} diff --git a/libs/Ethernet/examples/TelnetClient/TelnetClient.ino b/libs/Ethernet/examples/TelnetClient/TelnetClient.ino new file mode 100644 index 0000000..ff554a5 --- /dev/null +++ b/libs/Ethernet/examples/TelnetClient/TelnetClient.ino @@ -0,0 +1,109 @@ +/* + Telnet client + + This sketch connects to a telnet server (http://www.google.com) + using an Arduino WIZnet Ethernet shield. You'll need a telnet server + to test this with. + Processing's ChatServer example (part of the Network library) works well, + running on port 10002. It can be found as part of the examples + in the Processing application, available at + https://processing.org/ + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 14 Sep 2010 + modified 9 Apr 2012 + by Tom Igoe + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +// Enter the IP address of the server you're connecting to: +IPAddress server(1, 1, 1, 1); + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 23 is default for telnet; +// if you're using Processing's ChatServer, use port 10002): +EthernetClient client; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // start the Ethernet connection: + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + while (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + delay(500); + } + + // give the Ethernet shield a second to initialize: + delay(1000); + Serial.println("connecting..."); + + // if you get a connection, report back via serial: + if (client.connect(server, 10002)) { + Serial.println("connected"); + } else { + // if you didn't get a connection to the server: + Serial.println("connection failed"); + } +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + // as long as there are bytes in the serial queue, + // read them and send them out the socket if it's open: + while (Serial.available() > 0) { + char inChar = Serial.read(); + if (client.connected()) { + client.print(inChar); + } + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + // do nothing: + while (true) { + delay(1); + } + } +} diff --git a/libs/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino b/libs/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino new file mode 100644 index 0000000..3995b33 --- /dev/null +++ b/libs/Ethernet/examples/UDPSendReceiveString/UDPSendReceiveString.ino @@ -0,0 +1,138 @@ +/* + UDPSendReceiveString + + This sketch receives UDP message strings, prints them to the serial port + and sends an "acknowledge" string back to the sender + + A Processing sketch is included at the end of file that can be used to send + and receive messages for testing with a computer. + + created 21 Aug 2010 + by Michael Margolis + + This code is in the public domain. + */ + + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// buffers for receiving and sending data +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, +char ReplyBuffer[] = "acknowledged"; // a string to send back + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // start the Ethernet + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start UDP + Udp.begin(localPort); +} + +void loop() { + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if (packetSize) { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i=0; i < 4; i++) { + Serial.print(remote[i], DEC); + if (i < 3) { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + + // send a reply to the IP address and port that sent us the packet we received + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write(ReplyBuffer); + Udp.endPacket(); + } + delay(10); +} + + +/* + Processing sketch to run with this example + ===================================================== + + // Processing UDP example to send and receive string data from Arduino + // press any key to send the "Hello Arduino" message + + + import hypermedia.net.*; + + UDP udp; // define the UDP object + + + void setup() { + udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000 + //udp.log( true ); // <-- printout the connection activity + udp.listen( true ); // and wait for incoming message + } + + void draw() + { + } + + void keyPressed() { + String ip = "192.168.1.177"; // the remote IP address + int port = 8888; // the destination port + + udp.send("Hello World", ip, port ); // the message to send + + } + + void receive( byte[] data ) { // <-- default handler + //void receive( byte[] data, String ip, int port ) { // <-- extended handler + + for(int i=0; i < data.length; i++) + print(char(data[i])); + println(); + } + */ diff --git a/libs/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino b/libs/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino new file mode 100644 index 0000000..1455b40 --- /dev/null +++ b/libs/Ethernet/examples/UdpNtpClient/UdpNtpClient.ino @@ -0,0 +1,145 @@ +/* + Udp NTP Client + + Get the time from a Network Time Protocol (NTP) time server + Demonstrates use of UDP sendPacket and ReceivePacket + For more on NTP time servers and the messages needed to communicate with them, + see https://en.wikipedia.org/wiki/Network_Time_Protocol + + created 4 Sep 2010 + by Michael Margolis + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + This code is in the public domain. + + */ + +#include +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; + +unsigned int localPort = 8888; // local port to listen for UDP packets + +const char timeServer[] = "time.nist.gov"; // time.nist.gov NTP server + +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message + +byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start Ethernet and UDP + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + } else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // no point in carrying on, so do nothing forevermore: + while (true) { + delay(1); + } + } + Udp.begin(localPort); +} + +void loop() { + sendNTPpacket(timeServer); // send an NTP packet to a time server + + // wait to see if a reply is available + delay(1000); + if (Udp.parsePacket()) { + // We've received a packet, read the data from it + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + // the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, extract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = "); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if (((epoch % 3600) / 60) < 10) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ((epoch % 60) < 10) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } + // wait ten seconds before asking for the time again + delay(10000); + Ethernet.maintain(); +} + +// send an NTP request to the time server at the given address +void sendNTPpacket(const char * address) { + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); // NTP requests are to port 123 + Udp.write(packetBuffer, NTP_PACKET_SIZE); + Udp.endPacket(); +} diff --git a/libs/Ethernet/examples/WebClient/WebClient.ino b/libs/Ethernet/examples/WebClient/WebClient.ino new file mode 100644 index 0000000..f4a5d02 --- /dev/null +++ b/libs/Ethernet/examples/WebClient/WebClient.ino @@ -0,0 +1,136 @@ +/* + Web client + + This sketch connects to a website (http://www.google.com) + using an Arduino WIZnet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe, based on work by Adrian McEwen + + */ + +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// if you don't want to use DNS (and reduce your sketch size) +// use the numeric IP instead of the name for the server: +//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) +char server[] = "www.google.com"; // name address for Google (using DNS) + +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); +IPAddress myDns(192, 168, 0, 1); + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +EthernetClient client; + +// Variables to measure the speed +unsigned long beginMicros, endMicros; +unsigned long byteCount = 0; +bool printWebData = true; // set to false for better speed measurement + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to configure using IP address instead of DHCP: + Ethernet.begin(mac, ip, myDns); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + // give the Ethernet shield a second to initialize: + delay(1000); + Serial.print("connecting to "); + Serial.print(server); + Serial.println("..."); + + // if you get a connection, report back via serial: + if (client.connect(server, 80)) { + Serial.print("connected to "); + Serial.println(client.remoteIP()); + // Make a HTTP request: + client.println("GET /search?q=arduino HTTP/1.1"); + client.println("Host: www.google.com"); + client.println("Connection: close"); + client.println(); + } else { + // if you didn't get a connection to the server: + Serial.println("connection failed"); + } + beginMicros = micros(); +} + +void loop() { + // if there are incoming bytes available + // from the server, read them and print them: + int len = client.available(); + if (len > 0) { + byte buffer[80]; + if (len > 80) len = 80; + client.read(buffer, len); + if (printWebData) { + Serial.write(buffer, len); // show in the serial monitor (slows some boards) + } + byteCount = byteCount + len; + } + + // if the server's disconnected, stop the client: + if (!client.connected()) { + endMicros = micros(); + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + Serial.print("Received "); + Serial.print(byteCount); + Serial.print(" bytes in "); + float seconds = (float)(endMicros - beginMicros) / 1000000.0; + Serial.print(seconds, 4); + float rate = (float)byteCount / seconds / 1000.0; + Serial.print(", rate = "); + Serial.print(rate); + Serial.print(" kbytes/second"); + Serial.println(); + + // do nothing forevermore: + while (true) { + delay(1); + } + } +} diff --git a/libs/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino b/libs/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino new file mode 100644 index 0000000..1fb11e1 --- /dev/null +++ b/libs/Ethernet/examples/WebClientRepeating/WebClientRepeating.ino @@ -0,0 +1,126 @@ +/* + Repeating Web client + + This sketch connects to a web server and makes a request + using a WIZnet Ethernet shield. You can use the Arduino Ethernet Shield, or + the Adafruit Ethernet shield, either one will work, as long as it's got + a WIZnet Ethernet module on board. + + This example uses DNS, by assigning the Ethernet client with a MAC address, + IP address, and DNS address. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + + created 19 Apr 2012 + by Tom Igoe + modified 21 Jan 2014 + by Federico Vanzati + + https://www.arduino.cc/en/Tutorial/WebClientRepeating + This code is in the public domain. + + */ + +#include +#include + +// assign a MAC address for the Ethernet controller. +// fill in your address here: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); +IPAddress myDns(192, 168, 0, 1); + +// initialize the library instance: +EthernetClient client; + +char server[] = "www.arduino.cc"; // also change the Host line in httpRequest() +//IPAddress server(64,131,82,241); + +unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds +const unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // start serial port: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to configure using IP address instead of DHCP: + Ethernet.begin(mac, ip, myDns); + Serial.print("My IP address: "); + Serial.println(Ethernet.localIP()); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + // give the Ethernet shield a second to initialize: + delay(1000); +} + +void loop() { + // if there's incoming data from the net connection. + // send it out the serial port. This is for debugging + // purposes only: + if (client.available()) { + char c = client.read(); + Serial.write(c); + } + + // if ten seconds have passed since your last connection, + // then connect again and send data: + if (millis() - lastConnectionTime > postingInterval) { + httpRequest(); + } + +} + +// this method makes a HTTP connection to the server: +void httpRequest() { + // close any connection before send a new request. + // This will free the socket on the Ethernet shield + client.stop(); + + // if there's a successful connection: + if (client.connect(server, 80)) { + Serial.println("connecting..."); + // send the HTTP GET request: + client.println("GET /latest.txt HTTP/1.1"); + client.println("Host: www.arduino.cc"); + client.println("User-Agent: arduino-ethernet"); + client.println("Connection: close"); + client.println(); + + // note the time that the connection was made: + lastConnectionTime = millis(); + } else { + // if you couldn't make a connection: + Serial.println("connection failed"); + } +} diff --git a/libs/Ethernet/examples/WebServer/WebServer.ino b/libs/Ethernet/examples/WebServer/WebServer.ino new file mode 100644 index 0000000..f3929d2 --- /dev/null +++ b/libs/Ethernet/examples/WebServer/WebServer.ino @@ -0,0 +1,122 @@ +/* + Web Server + + A simple web server that shows the value of the analog input pins. + using an Arduino WIZnet Ethernet shield. + + Circuit: + * Ethernet shield attached to pins 10, 11, 12, 13 + * Analog inputs attached to pins A0 through A5 (optional) + + created 18 Dec 2009 + by David A. Mellis + modified 9 Apr 2012 + by Tom Igoe + modified 02 Sept 2015 + by Arturo Guadalupi + + */ + +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED +}; +IPAddress ip(192, 168, 1, 177); + +// Initialize the Ethernet server library +// with the IP address and port you want to use +// (port 80 is default for HTTP): +EthernetServer server(80); + +void setup() { + // You can use Ethernet.init(pin) to configure the CS pin + //Ethernet.init(10); // Most Arduino shields + //Ethernet.init(5); // MKR ETH Shield + //Ethernet.init(0); // Teensy 2.0 + //Ethernet.init(20); // Teensy++ 2.0 + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + Serial.println("Ethernet WebServer Example"); + + // start the Ethernet connection and the server: + Ethernet.begin(mac, ip); + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + + // start the server + server.begin(); + Serial.print("server is at "); + Serial.println(Ethernet.localIP()); +} + + +void loop() { + // listen for incoming clients + EthernetClient client = server.available(); + if (client) { + Serial.println("new client"); + // an HTTP request ends with a blank line + bool currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the HTTP request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard HTTP response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = analogRead(analogChannel); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; + } else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } +} diff --git a/libs/Ethernet/keywords.txt b/libs/Ethernet/keywords.txt new file mode 100644 index 0000000..9fd2541 --- /dev/null +++ b/libs/Ethernet/keywords.txt @@ -0,0 +1,67 @@ +####################################### +# Syntax Coloring Map For Ethernet +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Ethernet KEYWORD1 Ethernet +EthernetClient KEYWORD1 EthernetClient +EthernetServer KEYWORD1 EthernetServer +IPAddress KEYWORD1 EthernetIPAddress + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +status KEYWORD2 +connect KEYWORD2 +write KEYWORD2 +available KEYWORD2 +availableForWrite KEYWORD2 +read KEYWORD2 +peek KEYWORD2 +flush KEYWORD2 +stop KEYWORD2 +connected KEYWORD2 +accept KEYWORD2 +begin KEYWORD2 +beginMulticast KEYWORD2 +beginPacket KEYWORD2 +endPacket KEYWORD2 +parsePacket KEYWORD2 +remoteIP KEYWORD2 +remotePort KEYWORD2 +getSocketNumber KEYWORD2 +localIP KEYWORD2 +localPort KEYWORD2 +maintain KEYWORD2 +linkStatus KEYWORD2 +hardwareStatus KEYWORD2 +MACAddress KEYWORD2 +subnetMask KEYWORD2 +gatewayIP KEYWORD2 +dnsServerIP KEYWORD2 +setMACAddress KEYWORD2 +setLocalIP KEYWORD2 +setSubnetMask KEYWORD2 +setGatewayIP KEYWORD2 +setDnsServerIP KEYWORD2 +setRetransmissionTimeout KEYWORD2 +setRetransmissionCount KEYWORD2 +setConnectionTimeout KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +EthernetLinkStatus LITERAL1 +Unknown LITERAL1 +LinkON LITERAL1 +LinkOFF LITERAL1 +EthernetHardwareStatus LITERAL1 +EthernetNoHardware LITERAL1 +EthernetW5100 LITERAL1 +EthernetW5200 LITERAL1 +EthernetW5500 LITERAL1 diff --git a/libs/Ethernet/library.properties b/libs/Ethernet/library.properties new file mode 100644 index 0000000..f3f3616 --- /dev/null +++ b/libs/Ethernet/library.properties @@ -0,0 +1,10 @@ +name=Ethernet +version=2.0.2 +author=Various (see AUTHORS file for details) +maintainer=Arduino +sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. +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. +category=Communication +url=https://www.arduino.cc/en/Reference/Ethernet +architectures=* +includes=Ethernet.h diff --git a/libs/Ethernet/src/Dhcp.cpp b/libs/Ethernet/src/Dhcp.cpp new file mode 100644 index 0000000..2bfd584 --- /dev/null +++ b/libs/Ethernet/src/Dhcp.cpp @@ -0,0 +1,433 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#include +#include "Ethernet.h" +#include "Dhcp.h" +#include "utility/w5100.h" + +int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) +{ + _dhcpLeaseTime=0; + _dhcpT1=0; + _dhcpT2=0; + _timeout = timeout; + _responseTimeout = responseTimeout; + + // zero out _dhcpMacAddr + memset(_dhcpMacAddr, 0, 6); + reset_DHCP_lease(); + + memcpy((void*)_dhcpMacAddr, (void*)mac, 6); + _dhcp_state = STATE_DHCP_START; + return request_DHCP_lease(); +} + +void DhcpClass::reset_DHCP_lease() +{ + // zero out _dhcpSubnetMask, _dhcpGatewayIp, _dhcpLocalIp, _dhcpDhcpServerIp, _dhcpDnsServerIp + memset(_dhcpLocalIp, 0, 20); +} + + //return:0 on error, 1 if request is sent and response is received +int DhcpClass::request_DHCP_lease() +{ + uint8_t messageType = 0; + + // Pick an initial transaction ID + _dhcpTransactionId = random(1UL, 2000UL); + _dhcpInitialTransactionId = _dhcpTransactionId; + + _dhcpUdpSocket.stop(); + if (_dhcpUdpSocket.begin(DHCP_CLIENT_PORT) == 0) { + // Couldn't get a socket + return 0; + } + + presend_DHCP(); + + int result = 0; + + unsigned long startTime = millis(); + + while (_dhcp_state != STATE_DHCP_LEASED) { + if (_dhcp_state == STATE_DHCP_START) { + _dhcpTransactionId++; + send_DHCP_MESSAGE(DHCP_DISCOVER, ((millis() - startTime) / 1000)); + _dhcp_state = STATE_DHCP_DISCOVER; + } else if (_dhcp_state == STATE_DHCP_REREQUEST) { + _dhcpTransactionId++; + send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime)/1000)); + _dhcp_state = STATE_DHCP_REQUEST; + } else if (_dhcp_state == STATE_DHCP_DISCOVER) { + uint32_t respId; + messageType = parseDHCPResponse(_responseTimeout, respId); + if (messageType == DHCP_OFFER) { + // We'll use the transaction ID that the offer came with, + // rather than the one we were up to + _dhcpTransactionId = respId; + send_DHCP_MESSAGE(DHCP_REQUEST, ((millis() - startTime) / 1000)); + _dhcp_state = STATE_DHCP_REQUEST; + } + } else if (_dhcp_state == STATE_DHCP_REQUEST) { + uint32_t respId; + messageType = parseDHCPResponse(_responseTimeout, respId); + if (messageType == DHCP_ACK) { + _dhcp_state = STATE_DHCP_LEASED; + result = 1; + //use default lease time if we didn't get it + if (_dhcpLeaseTime == 0) { + _dhcpLeaseTime = DEFAULT_LEASE; + } + // Calculate T1 & T2 if we didn't get it + if (_dhcpT1 == 0) { + // T1 should be 50% of _dhcpLeaseTime + _dhcpT1 = _dhcpLeaseTime >> 1; + } + if (_dhcpT2 == 0) { + // T2 should be 87.5% (7/8ths) of _dhcpLeaseTime + _dhcpT2 = _dhcpLeaseTime - (_dhcpLeaseTime >> 3); + } + _renewInSec = _dhcpT1; + _rebindInSec = _dhcpT2; + } else if (messageType == DHCP_NAK) { + _dhcp_state = STATE_DHCP_START; + } + } + + if (messageType == 255) { + messageType = 0; + _dhcp_state = STATE_DHCP_START; + } + + if (result != 1 && ((millis() - startTime) > _timeout)) + break; + } + + // We're done with the socket now + _dhcpUdpSocket.stop(); + _dhcpTransactionId++; + + _lastCheckLeaseMillis = millis(); + return result; +} + +void DhcpClass::presend_DHCP() +{ +} + +void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed) +{ + uint8_t buffer[32]; + memset(buffer, 0, 32); + IPAddress dest_addr(255, 255, 255, 255); // Broadcast address + + if (_dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT) == -1) { + //Serial.printf("DHCP transmit error\n"); + // FIXME Need to return errors + return; + } + + buffer[0] = DHCP_BOOTREQUEST; // op + buffer[1] = DHCP_HTYPE10MB; // htype + buffer[2] = DHCP_HLENETHERNET; // hlen + buffer[3] = DHCP_HOPS; // hops + + // xid + unsigned long xid = htonl(_dhcpTransactionId); + memcpy(buffer + 4, &(xid), 4); + + // 8, 9 - seconds elapsed + buffer[8] = ((secondsElapsed & 0xff00) >> 8); + buffer[9] = (secondsElapsed & 0x00ff); + + // flags + unsigned short flags = htons(DHCP_FLAGSBROADCAST); + memcpy(buffer + 10, &(flags), 2); + + // ciaddr: already zeroed + // yiaddr: already zeroed + // siaddr: already zeroed + // giaddr: already zeroed + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 28); + + memset(buffer, 0, 32); // clear local buffer + + memcpy(buffer, _dhcpMacAddr, 6); // chaddr + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 16); + + memset(buffer, 0, 32); // clear local buffer + + // leave zeroed out for sname && file + // put in W5100 transmit buffer x 6 (192 bytes) + + for(int i = 0; i < 6; i++) { + _dhcpUdpSocket.write(buffer, 32); + } + + // OPT - Magic Cookie + buffer[0] = (uint8_t)((MAGIC_COOKIE >> 24)& 0xFF); + buffer[1] = (uint8_t)((MAGIC_COOKIE >> 16)& 0xFF); + buffer[2] = (uint8_t)((MAGIC_COOKIE >> 8)& 0xFF); + buffer[3] = (uint8_t)(MAGIC_COOKIE& 0xFF); + + // OPT - message type + buffer[4] = dhcpMessageType; + buffer[5] = 0x01; + buffer[6] = messageType; //DHCP_REQUEST; + + // OPT - client identifier + buffer[7] = dhcpClientIdentifier; + buffer[8] = 0x07; + buffer[9] = 0x01; + memcpy(buffer + 10, _dhcpMacAddr, 6); + + // OPT - host name + buffer[16] = hostName; + buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address + strcpy((char*)&(buffer[18]), HOST_NAME); + + printByte((char*)&(buffer[24]), _dhcpMacAddr[3]); + printByte((char*)&(buffer[26]), _dhcpMacAddr[4]); + printByte((char*)&(buffer[28]), _dhcpMacAddr[5]); + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 30); + + if (messageType == DHCP_REQUEST) { + buffer[0] = dhcpRequestedIPaddr; + buffer[1] = 0x04; + buffer[2] = _dhcpLocalIp[0]; + buffer[3] = _dhcpLocalIp[1]; + buffer[4] = _dhcpLocalIp[2]; + buffer[5] = _dhcpLocalIp[3]; + + buffer[6] = dhcpServerIdentifier; + buffer[7] = 0x04; + buffer[8] = _dhcpDhcpServerIp[0]; + buffer[9] = _dhcpDhcpServerIp[1]; + buffer[10] = _dhcpDhcpServerIp[2]; + buffer[11] = _dhcpDhcpServerIp[3]; + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 12); + } + + buffer[0] = dhcpParamRequest; + buffer[1] = 0x06; + buffer[2] = subnetMask; + buffer[3] = routersOnSubnet; + buffer[4] = dns; + buffer[5] = domainName; + buffer[6] = dhcpT1value; + buffer[7] = dhcpT2value; + buffer[8] = endOption; + + //put data in W5100 transmit buffer + _dhcpUdpSocket.write(buffer, 9); + + _dhcpUdpSocket.endPacket(); +} + +uint8_t DhcpClass::parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId) +{ + uint8_t type = 0; + uint8_t opt_len = 0; + + unsigned long startTime = millis(); + + while (_dhcpUdpSocket.parsePacket() <= 0) { + if ((millis() - startTime) > responseTimeout) { + return 255; + } + delay(50); + } + // start reading in the packet + RIP_MSG_FIXED fixedMsg; + _dhcpUdpSocket.read((uint8_t*)&fixedMsg, sizeof(RIP_MSG_FIXED)); + + if (fixedMsg.op == DHCP_BOOTREPLY && _dhcpUdpSocket.remotePort() == DHCP_SERVER_PORT) { + transactionId = ntohl(fixedMsg.xid); + if (memcmp(fixedMsg.chaddr, _dhcpMacAddr, 6) != 0 || + (transactionId < _dhcpInitialTransactionId) || + (transactionId > _dhcpTransactionId)) { + // Need to read the rest of the packet here regardless + _dhcpUdpSocket.flush(); // FIXME + return 0; + } + + memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4); + + // Skip to the option part + _dhcpUdpSocket.read((uint8_t *)NULL, 240 - (int)sizeof(RIP_MSG_FIXED)); + + while (_dhcpUdpSocket.available() > 0) { + switch (_dhcpUdpSocket.read()) { + case endOption : + break; + + case padOption : + break; + + case dhcpMessageType : + opt_len = _dhcpUdpSocket.read(); + type = _dhcpUdpSocket.read(); + break; + + case subnetMask : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpSubnetMask, 4); + break; + + case routersOnSubnet : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpGatewayIp, 4); + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); + break; + + case dns : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read(_dhcpDnsServerIp, 4); + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len - 4); + break; + + case dhcpServerIdentifier : + opt_len = _dhcpUdpSocket.read(); + if ( IPAddress(_dhcpDhcpServerIp) == IPAddress((uint32_t)0) || + IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP() ) { + _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp)); + } else { + // Skip over the rest of this option + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); + } + break; + + case dhcpT1value : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpT1, sizeof(_dhcpT1)); + _dhcpT1 = ntohl(_dhcpT1); + break; + + case dhcpT2value : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpT2, sizeof(_dhcpT2)); + _dhcpT2 = ntohl(_dhcpT2); + break; + + case dhcpIPaddrLeaseTime : + opt_len = _dhcpUdpSocket.read(); + _dhcpUdpSocket.read((uint8_t*)&_dhcpLeaseTime, sizeof(_dhcpLeaseTime)); + _dhcpLeaseTime = ntohl(_dhcpLeaseTime); + _renewInSec = _dhcpLeaseTime; + break; + + default : + opt_len = _dhcpUdpSocket.read(); + // Skip over the rest of this option + _dhcpUdpSocket.read((uint8_t *)NULL, opt_len); + break; + } + } + } + + // Need to skip to end of the packet regardless here + _dhcpUdpSocket.flush(); // FIXME + + return type; +} + + +/* + returns: + 0/DHCP_CHECK_NONE: nothing happened + 1/DHCP_CHECK_RENEW_FAIL: renew failed + 2/DHCP_CHECK_RENEW_OK: renew success + 3/DHCP_CHECK_REBIND_FAIL: rebind fail + 4/DHCP_CHECK_REBIND_OK: rebind success +*/ +int DhcpClass::checkLease() +{ + int rc = DHCP_CHECK_NONE; + + unsigned long now = millis(); + unsigned long elapsed = now - _lastCheckLeaseMillis; + + // if more then one sec passed, reduce the counters accordingly + if (elapsed >= 1000) { + // set the new timestamps + _lastCheckLeaseMillis = now - (elapsed % 1000); + elapsed = elapsed / 1000; + + // decrease the counters by elapsed seconds + // we assume that the cycle time (elapsed) is fairly constant + // if the remainder is less than cycle time * 2 + // do it early instead of late + if (_renewInSec < elapsed * 2) { + _renewInSec = 0; + } else { + _renewInSec -= elapsed; + } + if (_rebindInSec < elapsed * 2) { + _rebindInSec = 0; + } else { + _rebindInSec -= elapsed; + } + } + + // if we have a lease but should renew, do it + if (_renewInSec == 0 &&_dhcp_state == STATE_DHCP_LEASED) { + _dhcp_state = STATE_DHCP_REREQUEST; + rc = 1 + request_DHCP_lease(); + } + + // if we have a lease or is renewing but should bind, do it + if (_rebindInSec == 0 && (_dhcp_state == STATE_DHCP_LEASED || + _dhcp_state == STATE_DHCP_START)) { + // this should basically restart completely + _dhcp_state = STATE_DHCP_START; + reset_DHCP_lease(); + rc = 3 + request_DHCP_lease(); + } + return rc; +} + +IPAddress DhcpClass::getLocalIp() +{ + return IPAddress(_dhcpLocalIp); +} + +IPAddress DhcpClass::getSubnetMask() +{ + return IPAddress(_dhcpSubnetMask); +} + +IPAddress DhcpClass::getGatewayIp() +{ + return IPAddress(_dhcpGatewayIp); +} + +IPAddress DhcpClass::getDhcpServerIp() +{ + return IPAddress(_dhcpDhcpServerIp); +} + +IPAddress DhcpClass::getDnsServerIp() +{ + return IPAddress(_dhcpDnsServerIp); +} + +void DhcpClass::printByte(char * buf, uint8_t n ) +{ + char *str = &buf[1]; + buf[0]='0'; + do { + unsigned long m = n; + n /= 16; + char c = m - 16 * n; + *str-- = c < 10 ? c + '0' : c + 'A' - 10; + } while(n); +} diff --git a/libs/Ethernet/src/Dhcp.h b/libs/Ethernet/src/Dhcp.h new file mode 100644 index 0000000..43ec4f8 --- /dev/null +++ b/libs/Ethernet/src/Dhcp.h @@ -0,0 +1,137 @@ +// DHCP Library v0.3 - April 25, 2009 +// Author: Jordan Terrell - blog.jordanterrell.com + +#ifndef Dhcp_h +#define Dhcp_h + +/* DHCP state machine. */ +#define STATE_DHCP_START 0 +#define STATE_DHCP_DISCOVER 1 +#define STATE_DHCP_REQUEST 2 +#define STATE_DHCP_LEASED 3 +#define STATE_DHCP_REREQUEST 4 +#define STATE_DHCP_RELEASE 5 + +#define DHCP_FLAGSBROADCAST 0x8000 + +/* UDP port numbers for DHCP */ +#define DHCP_SERVER_PORT 67 /* from server to client */ +#define DHCP_CLIENT_PORT 68 /* from client to server */ + +/* DHCP message OP code */ +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/* DHCP message type */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +#define DHCP_HTYPE10MB 1 +#define DHCP_HTYPE100MB 2 + +#define DHCP_HLENETHERNET 6 +#define DHCP_HOPS 0 +#define DHCP_SECS 0 + +#define MAGIC_COOKIE 0x63825363 +#define MAX_DHCP_OPT 16 + +#define HOST_NAME "WIZnet" +#define DEFAULT_LEASE (900) //default lease time in seconds + +#define DHCP_CHECK_NONE (0) +#define DHCP_CHECK_RENEW_FAIL (1) +#define DHCP_CHECK_RENEW_OK (2) +#define DHCP_CHECK_REBIND_FAIL (3) +#define DHCP_CHECK_REBIND_OK (4) + +enum +{ + padOption = 0, + subnetMask = 1, + timerOffset = 2, + routersOnSubnet = 3, + /* timeServer = 4, + nameServer = 5,*/ + dns = 6, + /*logServer = 7, + cookieServer = 8, + lprServer = 9, + impressServer = 10, + resourceLocationServer = 11,*/ + hostName = 12, + /*bootFileSize = 13, + meritDumpFile = 14,*/ + domainName = 15, + /*swapServer = 16, + rootPath = 17, + extentionsPath = 18, + IPforwarding = 19, + nonLocalSourceRouting = 20, + policyFilter = 21, + maxDgramReasmSize = 22, + defaultIPTTL = 23, + pathMTUagingTimeout = 24, + pathMTUplateauTable = 25, + ifMTU = 26, + allSubnetsLocal = 27, + broadcastAddr = 28, + performMaskDiscovery = 29, + maskSupplier = 30, + performRouterDiscovery = 31, + routerSolicitationAddr = 32, + staticRoute = 33, + trailerEncapsulation = 34, + arpCacheTimeout = 35, + ethernetEncapsulation = 36, + tcpDefaultTTL = 37, + tcpKeepaliveInterval = 38, + tcpKeepaliveGarbage = 39, + nisDomainName = 40, + nisServers = 41, + ntpServers = 42, + vendorSpecificInfo = 43, + netBIOSnameServer = 44, + netBIOSdgramDistServer = 45, + netBIOSnodeType = 46, + netBIOSscope = 47, + xFontServer = 48, + xDisplayManager = 49,*/ + dhcpRequestedIPaddr = 50, + dhcpIPaddrLeaseTime = 51, + /*dhcpOptionOverload = 52,*/ + dhcpMessageType = 53, + dhcpServerIdentifier = 54, + dhcpParamRequest = 55, + /*dhcpMsg = 56, + dhcpMaxMsgSize = 57,*/ + dhcpT1value = 58, + dhcpT2value = 59, + /*dhcpClassIdentifier = 60,*/ + dhcpClientIdentifier = 61, + endOption = 255 +}; + +typedef struct _RIP_MSG_FIXED +{ + uint8_t op; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint32_t xid; + uint16_t secs; + uint16_t flags; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[6]; +} RIP_MSG_FIXED; + +#endif diff --git a/libs/Ethernet/src/Dns.cpp b/libs/Ethernet/src/Dns.cpp new file mode 100644 index 0000000..dca7ce4 --- /dev/null +++ b/libs/Ethernet/src/Dns.cpp @@ -0,0 +1,353 @@ +// Arduino DNS client for WIZnet W5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + + +#define SOCKET_NONE 255 +// Various flags and header field values for a DNS message +#define UDP_HEADER_SIZE 8 +#define DNS_HEADER_SIZE 12 +#define TTL_SIZE 4 +#define QUERY_FLAG (0) +#define RESPONSE_FLAG (1<<15) +#define QUERY_RESPONSE_MASK (1<<15) +#define OPCODE_STANDARD_QUERY (0) +#define OPCODE_INVERSE_QUERY (1<<11) +#define OPCODE_STATUS_REQUEST (2<<11) +#define OPCODE_MASK (15<<11) +#define AUTHORITATIVE_FLAG (1<<10) +#define TRUNCATION_FLAG (1<<9) +#define RECURSION_DESIRED_FLAG (1<<8) +#define RECURSION_AVAILABLE_FLAG (1<<7) +#define RESP_NO_ERROR (0) +#define RESP_FORMAT_ERROR (1) +#define RESP_SERVER_FAILURE (2) +#define RESP_NAME_ERROR (3) +#define RESP_NOT_IMPLEMENTED (4) +#define RESP_REFUSED (5) +#define RESP_MASK (15) +#define TYPE_A (0x0001) +#define CLASS_IN (0x0001) +#define LABEL_COMPRESSION_MASK (0xC0) +// Port number that DNS servers listen on +#define DNS_PORT 53 + +// Possible return codes from ProcessResponse +#define SUCCESS 1 +#define TIMED_OUT -1 +#define INVALID_SERVER -2 +#define TRUNCATED -3 +#define INVALID_RESPONSE -4 + +void DNSClient::begin(const IPAddress& aDNSServer) +{ + iDNSServer = aDNSServer; + iRequestId = 0; +} + + +int DNSClient::inet_aton(const char* address, IPAddress& result) +{ + uint16_t acc = 0; // Accumulator + uint8_t dots = 0; + + while (*address) { + char c = *address++; + if (c >= '0' && c <= '9') { + acc = acc * 10 + (c - '0'); + if (acc > 255) { + // Value out of [0..255] range + return 0; + } + } else if (c == '.') { + if (dots == 3) { + // Too much dots (there must be 3 dots) + return 0; + } + result[dots++] = acc; + acc = 0; + } else { + // Invalid char + return 0; + } + } + + if (dots != 3) { + // Too few dots (there must be 3 dots) + return 0; + } + result[3] = acc; + return 1; +} + +int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout) +{ + int ret = 0; + + // See if it's a numeric IP address + if (inet_aton(aHostname, aResult)) { + // It is, our work here is done + return 1; + } + + // Check we've got a valid DNS server to use + if (iDNSServer == INADDR_NONE) { + return INVALID_SERVER; + } + + // Find a socket to use + if (iUdp.begin(1024+(millis() & 0xF)) == 1) { + // Try up to three times + int retries = 0; + // while ((retries < 3) && (ret <= 0)) { + // Send DNS request + ret = iUdp.beginPacket(iDNSServer, DNS_PORT); + if (ret != 0) { + // Now output the request data + ret = BuildRequest(aHostname); + if (ret != 0) { + // And finally send the request + ret = iUdp.endPacket(); + if (ret != 0) { + // Now wait for a response + int wait_retries = 0; + ret = TIMED_OUT; + while ((wait_retries < 3) && (ret == TIMED_OUT)) { + ret = ProcessResponse(timeout, aResult); + wait_retries++; + } + } + } + } + retries++; + //} + + // We're done with the socket now + iUdp.stop(); + } + + return ret; +} + +uint16_t DNSClient::BuildRequest(const char* aName) +{ + // Build header + // 1 1 1 1 1 1 + // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ID | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | QDCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ANCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | NSCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // | ARCOUNT | + // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + // As we only support one request at a time at present, we can simplify + // some of this header + iRequestId = millis(); // generate a random ID + uint16_t twoByteBuffer; + + // FIXME We should also check that there's enough space available to write to, rather + // FIXME than assume there's enough space (as the code does at present) + iUdp.write((uint8_t*)&iRequestId, sizeof(iRequestId)); + + twoByteBuffer = htons(QUERY_FLAG | OPCODE_STANDARD_QUERY | RECURSION_DESIRED_FLAG); + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = htons(1); // One question record + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = 0; // Zero answer records + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + // and zero additional records + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + // Build question + const char* start =aName; + const char* end =start; + uint8_t len; + // Run through the name being requested + while (*end) { + // Find out how long this section of the name is + end = start; + while (*end && (*end != '.') ) { + end++; + } + + if (end-start > 0) { + // Write out the size of this section + len = end-start; + iUdp.write(&len, sizeof(len)); + // And then write out the section + iUdp.write((uint8_t*)start, end-start); + } + start = end+1; + } + + // We've got to the end of the question name, so + // terminate it with a zero-length section + len = 0; + iUdp.write(&len, sizeof(len)); + // Finally the type and class of question + twoByteBuffer = htons(TYPE_A); + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + + twoByteBuffer = htons(CLASS_IN); // Internet class of question + iUdp.write((uint8_t*)&twoByteBuffer, sizeof(twoByteBuffer)); + // Success! Everything buffered okay + return 1; +} + + +uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) +{ + uint32_t startTime = millis(); + + // Wait for a response packet + while (iUdp.parsePacket() <= 0) { + if ((millis() - startTime) > aTimeout) { + return TIMED_OUT; + } + delay(50); + } + + // We've had a reply! + // Read the UDP header + //uint8_t header[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header + union { + uint8_t byte[DNS_HEADER_SIZE]; // Enough space to reuse for the DNS header + uint16_t word[DNS_HEADER_SIZE/2]; + } header; + + // Check that it's a response from the right server and the right port + if ( (iDNSServer != iUdp.remoteIP()) || (iUdp.remotePort() != DNS_PORT) ) { + // It's not from who we expected + return INVALID_SERVER; + } + + // Read through the rest of the response + if (iUdp.available() < DNS_HEADER_SIZE) { + return TRUNCATED; + } + iUdp.read(header.byte, DNS_HEADER_SIZE); + + uint16_t header_flags = htons(header.word[1]); + // Check that it's a response to this request + if ((iRequestId != (header.word[0])) || + ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) ) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return INVALID_RESPONSE; + } + // Check for any errors in the response (or in our request) + // although we don't do anything to get round these + if ( (header_flags & TRUNCATION_FLAG) || (header_flags & RESP_MASK) ) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -5; //INVALID_RESPONSE; + } + + // And make sure we've got (at least) one answer + uint16_t answerCount = htons(header.word[3]); + if (answerCount == 0) { + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -6; //INVALID_RESPONSE; + } + + // Skip over any questions + for (uint16_t i=0; i < htons(header.word[2]); i++) { + // Skip over the name + uint8_t len; + do { + iUdp.read(&len, sizeof(len)); + if (len > 0) { + // Don't need to actually read the data out for the string, just + // advance ptr to beyond it + iUdp.read((uint8_t *)NULL, (size_t)len); + } + } while (len != 0); + + // Now jump over the type and class + iUdp.read((uint8_t *)NULL, 4); + } + + // Now we're up to the bit we're interested in, the answer + // There might be more than one answer (although we'll just use the first + // type A answer) and some authority and additional resource records but + // we're going to ignore all of them. + + for (uint16_t i=0; i < answerCount; i++) { + // Skip the name + uint8_t len; + do { + iUdp.read(&len, sizeof(len)); + if ((len & LABEL_COMPRESSION_MASK) == 0) { + // It's just a normal label + if (len > 0) { + // And it's got a length + // Don't need to actually read the data out for the string, + // just advance ptr to beyond it + iUdp.read((uint8_t *)NULL, len); + } + } else { + // This is a pointer to a somewhere else in the message for the + // rest of the name. We don't care about the name, and RFC1035 + // says that a name is either a sequence of labels ended with a + // 0 length octet or a pointer or a sequence of labels ending in + // a pointer. Either way, when we get here we're at the end of + // the name + // Skip over the pointer + iUdp.read((uint8_t *)NULL, 1); // we don't care about the byte + // And set len so that we drop out of the name loop + len = 0; + } + } while (len != 0); + + // Check the type and class + uint16_t answerType; + uint16_t answerClass; + iUdp.read((uint8_t*)&answerType, sizeof(answerType)); + iUdp.read((uint8_t*)&answerClass, sizeof(answerClass)); + + // Ignore the Time-To-Live as we don't do any caching + iUdp.read((uint8_t *)NULL, TTL_SIZE); // don't care about the returned bytes + + // And read out the length of this answer + // Don't need header_flags anymore, so we can reuse it here + iUdp.read((uint8_t*)&header_flags, sizeof(header_flags)); + + if ( (htons(answerType) == TYPE_A) && (htons(answerClass) == CLASS_IN) ) { + if (htons(header_flags) != 4) { + // It's a weird size + // Mark the entire packet as read + iUdp.flush(); // FIXME + return -9;//INVALID_RESPONSE; + } + // FIXME: seems to lock up here on ESP8266, but why?? + iUdp.read(aAddress.raw_address(), 4); + return SUCCESS; + } else { + // This isn't an answer type we're after, move onto the next one + iUdp.read((uint8_t *)NULL, htons(header_flags)); + } + } + + // Mark the entire packet as read + iUdp.flush(); // FIXME + + // If we get here then we haven't found an answer + return -10; //INVALID_RESPONSE; +} diff --git a/libs/Ethernet/src/Dns.h b/libs/Ethernet/src/Dns.h new file mode 100644 index 0000000..58f9d2c --- /dev/null +++ b/libs/Ethernet/src/Dns.h @@ -0,0 +1,40 @@ +// Arduino DNS client for WIZnet W5100-based Ethernet shield +// (c) Copyright 2009-2010 MCQN Ltd. +// Released under Apache License, version 2.0 + +#ifndef DNSClient_h +#define DNSClient_h + +#include "Ethernet.h" + +class DNSClient +{ +public: + void begin(const IPAddress& aDNSServer); + + /** Convert a numeric IP address string into a four-byte IP address. + @param aIPAddrString IP address to convert + @param aResult IPAddress structure to store the returned IP address + @result 1 if aIPAddrString was successfully converted to an IP address, + else error code + */ + int inet_aton(const char *aIPAddrString, IPAddress& aResult); + + /** Resolve the given hostname to an IP address. + @param aHostname Name to be resolved + @param aResult IPAddress structure to store the returned IP address + @result 1 if aIPAddrString was successfully converted to an IP address, + else error code + */ + int getHostByName(const char* aHostname, IPAddress& aResult, uint16_t timeout=5000); + +protected: + uint16_t BuildRequest(const char* aName); + uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress); + + IPAddress iDNSServer; + uint16_t iRequestId; + EthernetUDP iUdp; +}; + +#endif diff --git a/libs/Ethernet/src/Ethernet.cpp b/libs/Ethernet/src/Ethernet.cpp new file mode 100644 index 0000000..8d9ce7f --- /dev/null +++ b/libs/Ethernet/src/Ethernet.cpp @@ -0,0 +1,236 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" +#include "Dhcp.h" + +IPAddress EthernetClass::_dnsServerAddress; +DhcpClass* EthernetClass::_dhcp = NULL; + +int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout) +{ + static DhcpClass s_dhcp; + _dhcp = &s_dhcp; + + // Initialise the basic info + if (W5100.init() == 0) return 0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac); + W5100.setIPAddress(IPAddress(0,0,0,0).raw_address()); + SPI.endTransaction(); + + // Now try to get our config info from a DHCP server + int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout); + if (ret == 1) { + // We've successfully found a DHCP server and got our configuration + // info, so set things accordingly + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); + W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); + W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); + SPI.endTransaction(); + _dnsServerAddress = _dhcp->getDnsServerIp(); + socketPortRand(micros()); + } + return ret; +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip) +{ + // Assume the DNS server will be the machine on the same network as the local IP + // but with last octet being '1' + IPAddress dns = ip; + dns[3] = 1; + begin(mac, ip, dns); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns) +{ + // Assume the gateway will be the machine on the same network as the local IP + // but with last octet being '1' + IPAddress gateway = ip; + gateway[3] = 1; + begin(mac, ip, dns, gateway); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway) +{ + IPAddress subnet(255, 255, 255, 0); + begin(mac, ip, dns, gateway, subnet); +} + +void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet) +{ + if (W5100.init() == 0) return; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac); + W5100.setIPAddress(ip.raw_address()); + W5100.setGatewayIp(gateway.raw_address()); + W5100.setSubnetMask(subnet.raw_address()); + SPI.endTransaction(); + _dnsServerAddress = dns; +} + +void EthernetClass::init(uint8_t sspin) +{ + W5100.setSS(sspin); +} + +EthernetLinkStatus EthernetClass::linkStatus() +{ + switch (W5100.getLinkStatus()) { + case UNKNOWN: return Unknown; + case LINK_ON: return LinkON; + case LINK_OFF: return LinkOFF; + default: return Unknown; + } +} + +EthernetHardwareStatus EthernetClass::hardwareStatus() +{ + switch (W5100.getChip()) { + case 51: return EthernetW5100; + case 52: return EthernetW5200; + case 55: return EthernetW5500; + default: return EthernetNoHardware; + } +} + +int EthernetClass::maintain() +{ + int rc = DHCP_CHECK_NONE; + if (_dhcp != NULL) { + // we have a pointer to dhcp, use it + rc = _dhcp->checkLease(); + switch (rc) { + case DHCP_CHECK_NONE: + //nothing done + break; + case DHCP_CHECK_RENEW_OK: + case DHCP_CHECK_REBIND_OK: + //we might have got a new IP. + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setIPAddress(_dhcp->getLocalIp().raw_address()); + W5100.setGatewayIp(_dhcp->getGatewayIp().raw_address()); + W5100.setSubnetMask(_dhcp->getSubnetMask().raw_address()); + SPI.endTransaction(); + _dnsServerAddress = _dhcp->getDnsServerIp(); + break; + default: + //this is actually an error, it will retry though + break; + } + } + return rc; +} + + +void EthernetClass::MACAddress(uint8_t *mac_address) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getMACAddress(mac_address); + SPI.endTransaction(); +} + +IPAddress EthernetClass::localIP() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getIPAddress(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +IPAddress EthernetClass::subnetMask() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getSubnetMask(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +IPAddress EthernetClass::gatewayIP() +{ + IPAddress ret; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.getGatewayIp(ret.raw_address()); + SPI.endTransaction(); + return ret; +} + +void EthernetClass::setMACAddress(const uint8_t *mac_address) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setMACAddress(mac_address); + SPI.endTransaction(); +} + +void EthernetClass::setLocalIP(const IPAddress local_ip) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = local_ip; + W5100.setIPAddress(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setSubnetMask(const IPAddress subnet) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = subnet; + W5100.setSubnetMask(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setGatewayIP(const IPAddress gateway) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + IPAddress ip = gateway; + W5100.setGatewayIp(ip.raw_address()); + SPI.endTransaction(); +} + +void EthernetClass::setRetransmissionTimeout(uint16_t milliseconds) +{ + if (milliseconds > 6553) milliseconds = 6553; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setRetransmissionTime(milliseconds * 10); + SPI.endTransaction(); +} + +void EthernetClass::setRetransmissionCount(uint8_t num) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.setRetransmissionCount(num); + SPI.endTransaction(); +} + + + + + + + + + + +EthernetClass Ethernet; diff --git a/libs/Ethernet/src/Ethernet.h b/libs/Ethernet/src/Ethernet.h new file mode 100644 index 0000000..0045de8 --- /dev/null +++ b/libs/Ethernet/src/Ethernet.h @@ -0,0 +1,323 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ethernet_h_ +#define ethernet_h_ + +// All symbols exposed to Arduino sketches are contained in this header file +// +// Older versions had much of this stuff in EthernetClient.h, EthernetServer.h, +// and socket.h. Including headers in different order could cause trouble, so +// these "friend" classes are now defined in the same header file. socket.h +// was removed to avoid possible conflict with the C library header files. + + +// Configure the maximum number of sockets to support. W5100 chips can have +// up to 4 sockets. W5200 & W5500 can have up to 8 sockets. Several bytes +// of RAM are used for each socket. Reducing the maximum can save RAM, but +// you are limited to fewer simultaneous connections. +#if defined(RAMEND) && defined(RAMSTART) && ((RAMEND - RAMSTART) <= 2048) +#define MAX_SOCK_NUM 4 +#else +#define MAX_SOCK_NUM 8 +#endif + +// By default, each socket uses 2K buffers inside the WIZnet chip. If +// MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting +// this will use larger buffers within the WIZnet chip. Large buffers +// can really help with UDP protocols like Artnet. In theory larger +// buffers should allow faster TCP over high-latency links, but this +// does not always seem to work in practice (maybe WIZnet bugs?) +//#define ETHERNET_LARGE_BUFFERS + + +#include +#include "Client.h" +#include "Server.h" +#include "Udp.h" + +enum EthernetLinkStatus { + Unknown, + LinkON, + LinkOFF +}; + +enum EthernetHardwareStatus { + EthernetNoHardware, + EthernetW5100, + EthernetW5200, + EthernetW5500 +}; + +class EthernetUDP; +class EthernetClient; +class EthernetServer; +class DhcpClass; + +class EthernetClass { +private: + static IPAddress _dnsServerAddress; + static DhcpClass* _dhcp; +public: + // Initialise the Ethernet shield to use the provided MAC address and + // gain the rest of the configuration through DHCP. + // Returns 0 if the DHCP configuration failed, and 1 if it succeeded + static int begin(uint8_t *mac, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); + static int maintain(); + static EthernetLinkStatus linkStatus(); + static EthernetHardwareStatus hardwareStatus(); + + // Manual configuration + static void begin(uint8_t *mac, IPAddress ip); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); + static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway, IPAddress subnet); + static void init(uint8_t sspin = 10); + + static void MACAddress(uint8_t *mac_address); + static IPAddress localIP(); + static IPAddress subnetMask(); + static IPAddress gatewayIP(); + static IPAddress dnsServerIP() { return _dnsServerAddress; } + + void setMACAddress(const uint8_t *mac_address); + void setLocalIP(const IPAddress local_ip); + void setSubnetMask(const IPAddress subnet); + void setGatewayIP(const IPAddress gateway); + void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; } + void setRetransmissionTimeout(uint16_t milliseconds); + void setRetransmissionCount(uint8_t num); + + friend class EthernetClient; + friend class EthernetServer; + friend class EthernetUDP; +private: + // Opens a socket(TCP or UDP or IP_RAW mode) + static uint8_t socketBegin(uint8_t protocol, uint16_t port); + static uint8_t socketBeginMulticast(uint8_t protocol, IPAddress ip,uint16_t port); + static uint8_t socketStatus(uint8_t s); + // Close socket + static void socketClose(uint8_t s); + // Establish TCP connection (Active connection) + static void socketConnect(uint8_t s, uint8_t * addr, uint16_t port); + // disconnect the connection + static void socketDisconnect(uint8_t s); + // Establish TCP connection (Passive connection) + static uint8_t socketListen(uint8_t s); + // Send data (TCP) + static uint16_t socketSend(uint8_t s, const uint8_t * buf, uint16_t len); + static uint16_t socketSendAvailable(uint8_t s); + // Receive data (TCP) + static int socketRecv(uint8_t s, uint8_t * buf, int16_t len); + static uint16_t socketRecvAvailable(uint8_t s); + static uint8_t socketPeek(uint8_t s); + // sets up a UDP datagram, the data for which will be provided by one + // or more calls to bufferData and then finally sent with sendUDP. + // return true if the datagram was successfully set up, or false if there was an error + static bool socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port); + // copy up to len bytes of data from buf into a UDP datagram to be + // sent later by sendUDP. Allows datagrams to be built up from a series of bufferData calls. + // return Number of bytes successfully buffered + static uint16_t socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len); + // Send a UDP datagram built up from a sequence of startUDP followed by one or more + // calls to bufferData. + // return true if the datagram was successfully sent, or false if there was an error + static bool socketSendUDP(uint8_t s); + // Initialize the "random" source port number + static void socketPortRand(uint16_t n); +}; + +extern EthernetClass Ethernet; + + +#define UDP_TX_PACKET_MAX_SIZE 24 + +class EthernetUDP : public UDP { +private: + uint16_t _port; // local port to listen on + IPAddress _remoteIP; // remote IP address for the incoming packet whilst it's being processed + uint16_t _remotePort; // remote port for the incoming packet whilst it's being processed + uint16_t _offset; // offset into the packet being sent + +protected: + uint8_t sockindex; + uint16_t _remaining; // remaining bytes of incoming packet yet to be processed + +public: + EthernetUDP() : sockindex(MAX_SOCK_NUM) {} // Constructor + 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 + 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 + virtual void stop(); // Finish with the UDP socket + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port); + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port); + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket(); + // Write a single byte into the packet + virtual size_t write(uint8_t); + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + // Start processing the next available incoming packet + // Returns the size of the packet in bytes, or 0 if no packets are available + virtual int parsePacket(); + // Number of bytes remaining in the current packet + virtual int available(); + // Read a single byte from the current packet + virtual int read(); + // Read up to len bytes from the current packet and place them into buffer + // Returns the number of bytes read, or 0 if none are available + virtual int read(unsigned char* buffer, size_t len); + // Read up to len characters from the current packet and place them into buffer + // Returns the number of characters read, or 0 if none are available + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + // Return the next byte from the current packet without moving on to the next byte + virtual int peek(); + virtual void flush(); // Finish reading the current packet + + // Return the IP address of the host who sent the current incoming packet + virtual IPAddress remoteIP() { return _remoteIP; }; + // Return the port of the host who sent the current incoming packet + virtual uint16_t remotePort() { return _remotePort; }; + virtual uint16_t localPort() { return _port; } +}; + + + + +class EthernetClient : public Client { +public: + EthernetClient() : _sockindex(MAX_SOCK_NUM), _timeout(1000) { } + EthernetClient(uint8_t s) : _sockindex(s), _timeout(1000) { } + virtual ~EthernetClient() {}; + + uint8_t status(); + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); + virtual int availableForWrite(void); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + virtual void flush(); + virtual void stop(); + virtual uint8_t connected(); + virtual operator bool() { return _sockindex < MAX_SOCK_NUM; } + virtual bool operator==(const bool value) { return bool() == value; } + virtual bool operator!=(const bool value) { return bool() != value; } + virtual bool operator==(const EthernetClient&); + virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } + uint8_t getSocketNumber() const { return _sockindex; } + virtual uint16_t localPort(); + virtual IPAddress remoteIP(); + virtual uint16_t remotePort(); + virtual void setConnectionTimeout(uint16_t timeout) { _timeout = timeout; } + + friend class EthernetServer; + + using Print::write; + +private: + uint8_t _sockindex; // MAX_SOCK_NUM means client not in use + uint16_t _timeout; +}; + + +class EthernetServer : public Server { +private: + uint16_t _port; +public: + EthernetServer(uint16_t port) : _port(port) { } + EthernetClient available(); + EthernetClient accept(); + virtual void begin(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual operator bool(); + using Print::write; + //void statusreport(); + + // TODO: make private when socket allocation moves to EthernetClass + static uint16_t server_port[MAX_SOCK_NUM]; +}; + + +class DhcpClass { +private: + uint32_t _dhcpInitialTransactionId; + uint32_t _dhcpTransactionId; + uint8_t _dhcpMacAddr[6]; +#ifdef __arm__ + uint8_t _dhcpLocalIp[4] __attribute__((aligned(4))); + uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4))); + uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4))); + uint8_t _dhcpDhcpServerIp[4] __attribute__((aligned(4))); + uint8_t _dhcpDnsServerIp[4] __attribute__((aligned(4))); +#else + uint8_t _dhcpLocalIp[4]; + uint8_t _dhcpSubnetMask[4]; + uint8_t _dhcpGatewayIp[4]; + uint8_t _dhcpDhcpServerIp[4]; + uint8_t _dhcpDnsServerIp[4]; +#endif + uint32_t _dhcpLeaseTime; + uint32_t _dhcpT1, _dhcpT2; + uint32_t _renewInSec; + uint32_t _rebindInSec; + unsigned long _timeout; + unsigned long _responseTimeout; + unsigned long _lastCheckLeaseMillis; + uint8_t _dhcp_state; + EthernetUDP _dhcpUdpSocket; + + int request_DHCP_lease(); + void reset_DHCP_lease(); + void presend_DHCP(); + void send_DHCP_MESSAGE(uint8_t, uint16_t); + void printByte(char *, uint8_t); + + uint8_t parseDHCPResponse(unsigned long responseTimeout, uint32_t& transactionId); +public: + IPAddress getLocalIp(); + IPAddress getSubnetMask(); + IPAddress getGatewayIp(); + IPAddress getDhcpServerIp(); + IPAddress getDnsServerIp(); + + int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000); + int checkLease(); +}; + + + + + +#endif diff --git a/libs/Ethernet/src/EthernetClient.cpp b/libs/Ethernet/src/EthernetClient.cpp new file mode 100644 index 0000000..5a20c74 --- /dev/null +++ b/libs/Ethernet/src/EthernetClient.cpp @@ -0,0 +1,213 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + +int EthernetClient::connect(const char * host, uint16_t port) +{ + DNSClient dns; // Look up the host first + IPAddress remote_addr; + + if (_sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? + } + _sockindex = MAX_SOCK_NUM; + } + dns.begin(Ethernet.dnsServerIP()); + if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout + return connect(remote_addr, port); +} + +int EthernetClient::connect(IPAddress ip, uint16_t port) +{ + if (_sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? + } + _sockindex = MAX_SOCK_NUM; + } +#if defined(ESP8266) || defined(ESP32) + if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; +#else + if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; +#endif + _sockindex = Ethernet.socketBegin(SnMR::TCP, 0); + if (_sockindex >= MAX_SOCK_NUM) return 0; + Ethernet.socketConnect(_sockindex, rawIPAddress(ip), port); + uint32_t start = millis(); + while (1) { + uint8_t stat = Ethernet.socketStatus(_sockindex); + if (stat == SnSR::ESTABLISHED) return 1; + if (stat == SnSR::CLOSE_WAIT) return 1; + if (stat == SnSR::CLOSED) return 0; + if (millis() - start > _timeout) break; + delay(1); + } + Ethernet.socketClose(_sockindex); + _sockindex = MAX_SOCK_NUM; + return 0; +} + +int EthernetClient::availableForWrite(void) +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketSendAvailable(_sockindex); +} + +size_t EthernetClient::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t EthernetClient::write(const uint8_t *buf, size_t size) +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + if (Ethernet.socketSend(_sockindex, buf, size)) return size; + setWriteError(); + return 0; +} + +int EthernetClient::available() +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecvAvailable(_sockindex); + // TODO: do the WIZnet chips automatically retransmit TCP ACK + // packets if they are lost by the network? Someday this should + // be checked by a man-in-the-middle test which discards certain + // packets. If ACKs aren't resent, we would need to check for + // returning 0 here and after a timeout do another Sock_RECV + // command to cause the WIZnet chip to resend the ACK packet. +} + +int EthernetClient::read(uint8_t *buf, size_t size) +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecv(_sockindex, buf, size); +} + +int EthernetClient::peek() +{ + if (_sockindex >= MAX_SOCK_NUM) return -1; + if (!available()) return -1; + return Ethernet.socketPeek(_sockindex); +} + +int EthernetClient::read() +{ + uint8_t b; + if (Ethernet.socketRecv(_sockindex, &b, 1) > 0) return b; + return -1; +} + +void EthernetClient::flush() +{ + while (_sockindex < MAX_SOCK_NUM) { + uint8_t stat = Ethernet.socketStatus(_sockindex); + if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; + if (Ethernet.socketSendAvailable(_sockindex) >= W5100.SSIZE) return; + } +} + +void EthernetClient::stop() +{ + if (_sockindex >= MAX_SOCK_NUM) return; + + // attempt to close the connection gracefully (send a FIN to other side) + Ethernet.socketDisconnect(_sockindex); + unsigned long start = millis(); + + // wait up to a second for the connection to close + do { + if (Ethernet.socketStatus(_sockindex) == SnSR::CLOSED) { + _sockindex = MAX_SOCK_NUM; + return; // exit the loop + } + delay(1); + } while (millis() - start < _timeout); + + // if it hasn't closed, close it forcefully + Ethernet.socketClose(_sockindex); + _sockindex = MAX_SOCK_NUM; +} + +uint8_t EthernetClient::connected() +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + + uint8_t s = Ethernet.socketStatus(_sockindex); + return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || + (s == SnSR::CLOSE_WAIT && !available())); +} + +uint8_t EthernetClient::status() +{ + if (_sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; + return Ethernet.socketStatus(_sockindex); +} + +// the next function allows us to use the client returned by +// EthernetServer::available() as the condition in an if-statement. +bool EthernetClient::operator==(const EthernetClient& rhs) +{ + if (_sockindex != rhs._sockindex) return false; + if (_sockindex >= MAX_SOCK_NUM) return false; + if (rhs._sockindex >= MAX_SOCK_NUM) return false; + return true; +} + +// https://github.com/per1234/EthernetMod +// from: https://github.com/ntruchsess/Arduino-1/commit/937bce1a0bb2567f6d03b15df79525569377dabd +uint16_t EthernetClient::localPort() +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + uint16_t port; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + port = W5100.readSnPORT(_sockindex); + SPI.endTransaction(); + return port; +} + +// https://github.com/per1234/EthernetMod +// returns the remote IP address: https://forum.arduino.cc/index.php?topic=82416.0 +IPAddress EthernetClient::remoteIP() +{ + if (_sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); + uint8_t remoteIParray[4]; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.readSnDIPR(_sockindex, remoteIParray); + SPI.endTransaction(); + return IPAddress(remoteIParray); +} + +// https://github.com/per1234/EthernetMod +// from: https://github.com/ntruchsess/Arduino-1/commit/ca37de4ba4ecbdb941f14ac1fe7dd40f3008af75 +uint16_t EthernetClient::remotePort() +{ + if (_sockindex >= MAX_SOCK_NUM) return 0; + uint16_t port; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + port = W5100.readSnDPORT(_sockindex); + SPI.endTransaction(); + return port; +} diff --git a/libs/Ethernet/src/EthernetClient.h b/libs/Ethernet/src/EthernetClient.h new file mode 100644 index 0000000..b5aef96 --- /dev/null +++ b/libs/Ethernet/src/EthernetClient.h @@ -0,0 +1,3 @@ +// This file is in the public domain. No copyright is claimed. + +#include "Ethernet.h" diff --git a/libs/Ethernet/src/EthernetServer.cpp b/libs/Ethernet/src/EthernetServer.cpp new file mode 100644 index 0000000..ddebd15 --- /dev/null +++ b/libs/Ethernet/src/EthernetServer.cpp @@ -0,0 +1,179 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" + +uint16_t EthernetServer::server_port[MAX_SOCK_NUM]; + + +void EthernetServer::begin() +{ + uint8_t sockindex = Ethernet.socketBegin(SnMR::TCP, _port); + if (sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketListen(sockindex)) { + server_port[sockindex] = _port; + } else { + Ethernet.socketDisconnect(sockindex); + } + } +} + +EthernetClient EthernetServer::available() +{ + bool listening = false; + uint8_t sockindex = MAX_SOCK_NUM; + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return EthernetClient(MAX_SOCK_NUM); +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + uint8_t stat = Ethernet.socketStatus(i); + if (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT) { + if (Ethernet.socketRecvAvailable(i) > 0) { + sockindex = i; + } else { + // remote host closed connection, our end still open + if (stat == SnSR::CLOSE_WAIT) { + Ethernet.socketDisconnect(i); + // status becomes LAST_ACK for short time + } + } + } else if (stat == SnSR::LISTEN) { + listening = true; + } else if (stat == SnSR::CLOSED) { + server_port[i] = 0; + } + } + } + if (!listening) begin(); + return EthernetClient(sockindex); +} + +EthernetClient EthernetServer::accept() +{ + bool listening = false; + uint8_t sockindex = MAX_SOCK_NUM; + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return EthernetClient(MAX_SOCK_NUM); +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + uint8_t stat = Ethernet.socketStatus(i); + if (sockindex == MAX_SOCK_NUM && + (stat == SnSR::ESTABLISHED || stat == SnSR::CLOSE_WAIT)) { + // Return the connected client even if no data received. + // Some protocols like FTP expect the server to send the + // first data. + sockindex = i; + server_port[i] = 0; // only return the client once + } else if (stat == SnSR::LISTEN) { + listening = true; + } else if (stat == SnSR::CLOSED) { + server_port[i] = 0; + } + } + } + if (!listening) begin(); + return EthernetClient(sockindex); +} + +EthernetServer::operator bool() +{ + uint8_t maxindex=MAX_SOCK_NUM; +#if MAX_SOCK_NUM > 4 + if (W5100.getChip() == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + if (Ethernet.socketStatus(i) == SnSR::LISTEN) { + return true; // server is listening for incoming clients + } + } + } + return false; +} + +#if 0 +void EthernetServer::statusreport() +{ + Serial.printf("EthernetServer, port=%d\n", _port); + for (uint8_t i=0; i < MAX_SOCK_NUM; i++) { + uint16_t port = server_port[i]; + uint8_t stat = Ethernet.socketStatus(i); + const char *name; + switch (stat) { + case 0x00: name = "CLOSED"; break; + case 0x13: name = "INIT"; break; + case 0x14: name = "LISTEN"; break; + case 0x15: name = "SYNSENT"; break; + case 0x16: name = "SYNRECV"; break; + case 0x17: name = "ESTABLISHED"; break; + case 0x18: name = "FIN_WAIT"; break; + case 0x1A: name = "CLOSING"; break; + case 0x1B: name = "TIME_WAIT"; break; + case 0x1C: name = "CLOSE_WAIT"; break; + case 0x1D: name = "LAST_ACK"; break; + case 0x22: name = "UDP"; break; + case 0x32: name = "IPRAW"; break; + case 0x42: name = "MACRAW"; break; + case 0x5F: name = "PPPOE"; break; + default: name = "???"; + } + int avail = Ethernet.socketRecvAvailable(i); + Serial.printf(" %d: port=%d, status=%s (0x%02X), avail=%d\n", + i, port, name, stat, avail); + } +} +#endif + +size_t EthernetServer::write(uint8_t b) +{ + return write(&b, 1); +} + +size_t EthernetServer::write(const uint8_t *buffer, size_t size) +{ + uint8_t chip, maxindex=MAX_SOCK_NUM; + + chip = W5100.getChip(); + if (!chip) return 0; +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + available(); + for (uint8_t i=0; i < maxindex; i++) { + if (server_port[i] == _port) { + if (Ethernet.socketStatus(i) == SnSR::ESTABLISHED) { + Ethernet.socketSend(i, buffer, size); + } + } + } + return size; +} diff --git a/libs/Ethernet/src/EthernetServer.h b/libs/Ethernet/src/EthernetServer.h new file mode 100644 index 0000000..b5aef96 --- /dev/null +++ b/libs/Ethernet/src/EthernetServer.h @@ -0,0 +1,3 @@ +// This file is in the public domain. No copyright is claimed. + +#include "Ethernet.h" diff --git a/libs/Ethernet/src/EthernetUdp.cpp b/libs/Ethernet/src/EthernetUdp.cpp new file mode 100644 index 0000000..e28791f --- /dev/null +++ b/libs/Ethernet/src/EthernetUdp.cpp @@ -0,0 +1,190 @@ +/* + * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. + * This version only offers minimal wrapping of socket.cpp + * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ + * + * MIT License: + * Copyright (c) 2008 Bjoern Hartmann + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * bjoern@cs.stanford.edu 12/30/2008 + */ + +#include +#include "Ethernet.h" +#include "Dns.h" +#include "utility/w5100.h" + +/* Start EthernetUDP socket, listening at local port PORT */ +uint8_t EthernetUDP::begin(uint16_t port) +{ + if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); + sockindex = Ethernet.socketBegin(SnMR::UDP, port); + if (sockindex >= MAX_SOCK_NUM) return 0; + _port = port; + _remaining = 0; + return 1; +} + +/* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ +int EthernetUDP::available() +{ + return _remaining; +} + +/* Release any resources being used by this EthernetUDP instance */ +void EthernetUDP::stop() +{ + if (sockindex < MAX_SOCK_NUM) { + Ethernet.socketClose(sockindex); + sockindex = MAX_SOCK_NUM; + } +} + +int EthernetUDP::beginPacket(const char *host, uint16_t port) +{ + // Look up the host first + int ret = 0; + DNSClient dns; + IPAddress remote_addr; + + dns.begin(Ethernet.dnsServerIP()); + ret = dns.getHostByName(host, remote_addr); + if (ret != 1) return ret; + return beginPacket(remote_addr, port); +} + +int EthernetUDP::beginPacket(IPAddress ip, uint16_t port) +{ + _offset = 0; + //Serial.printf("UDP beginPacket\n"); + return Ethernet.socketStartUDP(sockindex, rawIPAddress(ip), port); +} + +int EthernetUDP::endPacket() +{ + return Ethernet.socketSendUDP(sockindex); +} + +size_t EthernetUDP::write(uint8_t byte) +{ + return write(&byte, 1); +} + +size_t EthernetUDP::write(const uint8_t *buffer, size_t size) +{ + //Serial.printf("UDP write %d\n", size); + uint16_t bytes_written = Ethernet.socketBufferData(sockindex, _offset, buffer, size); + _offset += bytes_written; + return bytes_written; +} + +int EthernetUDP::parsePacket() +{ + // discard any remaining bytes in the last packet + while (_remaining) { + // could this fail (loop endlessly) if _remaining > 0 and recv in read fails? + // should only occur if recv fails after telling us the data is there, lets + // hope the w5100 always behaves :) + read((uint8_t *)NULL, _remaining); + } + + if (Ethernet.socketRecvAvailable(sockindex) > 0) { + //HACK - hand-parse the UDP packet using TCP recv method + uint8_t tmpBuf[8]; + int ret=0; + //read 8 header bytes and get IP and port from it + ret = Ethernet.socketRecv(sockindex, tmpBuf, 8); + if (ret > 0) { + _remoteIP = tmpBuf; + _remotePort = tmpBuf[4]; + _remotePort = (_remotePort << 8) + tmpBuf[5]; + _remaining = tmpBuf[6]; + _remaining = (_remaining << 8) + tmpBuf[7]; + + // When we get here, any remaining bytes are the data + ret = _remaining; + } + return ret; + } + // There aren't any packets available + return 0; +} + +int EthernetUDP::read() +{ + uint8_t byte; + + if ((_remaining > 0) && (Ethernet.socketRecv(sockindex, &byte, 1) > 0)) { + // We read things without any problems + _remaining--; + return byte; + } + + // If we get here, there's no data available + return -1; +} + +int EthernetUDP::read(unsigned char *buffer, size_t len) +{ + if (_remaining > 0) { + int got; + if (_remaining <= len) { + // data should fit in the buffer + got = Ethernet.socketRecv(sockindex, buffer, _remaining); + } else { + // too much data for the buffer, + // grab as much as will fit + got = Ethernet.socketRecv(sockindex, buffer, len); + } + if (got > 0) { + _remaining -= got; + //Serial.printf("UDP read %d\n", got); + return got; + } + } + // If we get here, there's no data available or recv failed + return -1; +} + +int EthernetUDP::peek() +{ + // Unlike recv, peek doesn't check to see if there's any data available, so we must. + // If the user hasn't called parsePacket yet then return nothing otherwise they + // may get the UDP header + if (sockindex >= MAX_SOCK_NUM || _remaining == 0) return -1; + return Ethernet.socketPeek(sockindex); +} + +void EthernetUDP::flush() +{ + // TODO: we should wait for TX buffer to be emptied +} + +/* Start EthernetUDP socket, listening at local port PORT */ +uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port) +{ + if (sockindex < MAX_SOCK_NUM) Ethernet.socketClose(sockindex); + sockindex = Ethernet.socketBeginMulticast(SnMR::UDP | SnMR::MULTI, ip, port); + if (sockindex >= MAX_SOCK_NUM) return 0; + _port = port; + _remaining = 0; + return 1; +} diff --git a/libs/Ethernet/src/EthernetUdp.h b/libs/Ethernet/src/EthernetUdp.h new file mode 100644 index 0000000..16bb062 --- /dev/null +++ b/libs/Ethernet/src/EthernetUdp.h @@ -0,0 +1,38 @@ +/* + * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. + * This version only offers minimal wrapping of socket.cpp + * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ + * + * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) + * 1) UDP does not guarantee the order in which assembled UDP packets are received. This + * might not happen often in practice, but in larger network topologies, a UDP + * packet can be received out of sequence. + * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being + * aware of it. Again, this may not be a concern in practice on small local networks. + * For more information, see http://www.cafeaulait.org/course/week12/35.html + * + * MIT License: + * Copyright (c) 2008 Bjoern Hartmann + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * bjoern@cs.stanford.edu 12/30/2008 + */ + +#include "Ethernet.h" + diff --git a/libs/Ethernet/src/socket.cpp b/libs/Ethernet/src/socket.cpp new file mode 100644 index 0000000..7dc83fe --- /dev/null +++ b/libs/Ethernet/src/socket.cpp @@ -0,0 +1,538 @@ +/* Copyright 2018 Paul Stoffregen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this + * software and associated documentation files (the "Software"), to deal in the Software + * without restriction, including without limitation the rights to use, copy, modify, + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include "Ethernet.h" +#include "utility/w5100.h" + +#if ARDUINO >= 156 && !defined(ARDUINO_ARCH_PIC32) +extern void yield(void); +#else +#define yield() +#endif + +// TODO: randomize this when not using DHCP, but how? +static uint16_t local_port = 49152; // 49152 to 65535 + +typedef struct { + uint16_t RX_RSR; // Number of bytes received + uint16_t RX_RD; // Address to read + uint16_t TX_FSR; // Free space ready for transmit + uint8_t RX_inc; // how much have we advanced RX_RD +} socketstate_t; + +static socketstate_t state[MAX_SOCK_NUM]; + + +static uint16_t getSnTX_FSR(uint8_t s); +static uint16_t getSnRX_RSR(uint8_t s); +static void write_data(uint8_t s, uint16_t offset, const uint8_t *data, uint16_t len); +static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len); + + + +/*****************************************/ +/* Socket management */ +/*****************************************/ + + +void EthernetClass::socketPortRand(uint16_t n) +{ + n &= 0x3FFF; + local_port ^= n; + //Serial.printf("socketPortRand %d, srcport=%d\n", n, local_port); +} + +uint8_t EthernetClass::socketBegin(uint8_t protocol, uint16_t port) +{ + uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; + + // first check hardware compatibility + chip = W5100.getChip(); + if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + // look at all the hardware sockets, use any that are closed (unused) + for (s=0; s < maxindex; s++) { + status[s] = W5100.readSnSR(s); + if (status[s] == SnSR::CLOSED) goto makesocket; + } + //Serial.printf("W5000socket step2\n"); + // as a last resort, forcibly close any already closing + for (s=0; s < maxindex; s++) { + uint8_t stat = status[s]; + if (stat == SnSR::LAST_ACK) goto closemakesocket; + if (stat == SnSR::TIME_WAIT) goto closemakesocket; + if (stat == SnSR::FIN_WAIT) goto closemakesocket; + if (stat == SnSR::CLOSING) goto closemakesocket; + } +#if 0 + Serial.printf("W5000socket step3\n"); + // next, use any that are effectively closed + for (s=0; s < MAX_SOCK_NUM; s++) { + uint8_t stat = status[s]; + // TODO: this also needs to check if no more data + if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; + } +#endif + SPI.endTransaction(); + return MAX_SOCK_NUM; // all sockets are in use +closemakesocket: + //Serial.printf("W5000socket close\n"); + W5100.execCmdSn(s, Sock_CLOSE); +makesocket: + //Serial.printf("W5000socket %d\n", s); + EthernetServer::server_port[s] = 0; + delayMicroseconds(250); // TODO: is this needed?? + W5100.writeSnMR(s, protocol); + W5100.writeSnIR(s, 0xFF); + if (port > 0) { + W5100.writeSnPORT(s, port); + } else { + // if don't set the source port, set local_port number. + if (++local_port < 49152) local_port = 49152; + W5100.writeSnPORT(s, local_port); + } + W5100.execCmdSn(s, Sock_OPEN); + state[s].RX_RSR = 0; + state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? + state[s].RX_inc = 0; + state[s].TX_FSR = 0; + //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); + SPI.endTransaction(); + return s; +} + +// multicast version to set fields before open thd +uint8_t EthernetClass::socketBeginMulticast(uint8_t protocol, IPAddress ip, uint16_t port) +{ + uint8_t s, status[MAX_SOCK_NUM], chip, maxindex=MAX_SOCK_NUM; + + // first check hardware compatibility + chip = W5100.getChip(); + if (!chip) return MAX_SOCK_NUM; // immediate error if no hardware detected +#if MAX_SOCK_NUM > 4 + if (chip == 51) maxindex = 4; // W5100 chip never supports more than 4 sockets +#endif + //Serial.printf("W5000socket begin, protocol=%d, port=%d\n", protocol, port); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + // look at all the hardware sockets, use any that are closed (unused) + for (s=0; s < maxindex; s++) { + status[s] = W5100.readSnSR(s); + if (status[s] == SnSR::CLOSED) goto makesocket; + } + //Serial.printf("W5000socket step2\n"); + // as a last resort, forcibly close any already closing + for (s=0; s < maxindex; s++) { + uint8_t stat = status[s]; + if (stat == SnSR::LAST_ACK) goto closemakesocket; + if (stat == SnSR::TIME_WAIT) goto closemakesocket; + if (stat == SnSR::FIN_WAIT) goto closemakesocket; + if (stat == SnSR::CLOSING) goto closemakesocket; + } +#if 0 + Serial.printf("W5000socket step3\n"); + // next, use any that are effectively closed + for (s=0; s < MAX_SOCK_NUM; s++) { + uint8_t stat = status[s]; + // TODO: this also needs to check if no more data + if (stat == SnSR::CLOSE_WAIT) goto closemakesocket; + } +#endif + SPI.endTransaction(); + return MAX_SOCK_NUM; // all sockets are in use +closemakesocket: + //Serial.printf("W5000socket close\n"); + W5100.execCmdSn(s, Sock_CLOSE); +makesocket: + //Serial.printf("W5000socket %d\n", s); + EthernetServer::server_port[s] = 0; + delayMicroseconds(250); // TODO: is this needed?? + W5100.writeSnMR(s, protocol); + W5100.writeSnIR(s, 0xFF); + if (port > 0) { + W5100.writeSnPORT(s, port); + } else { + // if don't set the source port, set local_port number. + if (++local_port < 49152) local_port = 49152; + W5100.writeSnPORT(s, local_port); + } + // Calculate MAC address from Multicast IP Address + byte mac[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00 }; + mac[3] = ip[1] & 0x7F; + mac[4] = ip[2]; + mac[5] = ip[3]; + W5100.writeSnDIPR(s, ip.raw_address()); //239.255.0.1 + W5100.writeSnDPORT(s, port); + W5100.writeSnDHAR(s, mac); + W5100.execCmdSn(s, Sock_OPEN); + state[s].RX_RSR = 0; + state[s].RX_RD = W5100.readSnRX_RD(s); // always zero? + state[s].RX_inc = 0; + state[s].TX_FSR = 0; + //Serial.printf("W5000socket prot=%d, RX_RD=%d\n", W5100.readSnMR(s), state[s].RX_RD); + SPI.endTransaction(); + return s; +} +// Return the socket's status +// +uint8_t EthernetClass::socketStatus(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint8_t status = W5100.readSnSR(s); + SPI.endTransaction(); + return status; +} + +// Immediately close. If a TCP connection is established, the +// remote host is left unaware we closed. +// +void EthernetClass::socketClose(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_CLOSE); + SPI.endTransaction(); +} + + +// Place the socket in listening (server) mode +// +uint8_t EthernetClass::socketListen(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + if (W5100.readSnSR(s) != SnSR::INIT) { + SPI.endTransaction(); + return 0; + } + W5100.execCmdSn(s, Sock_LISTEN); + SPI.endTransaction(); + return 1; +} + + +// establish a TCP connection in Active (client) mode. +// +void EthernetClass::socketConnect(uint8_t s, uint8_t * addr, uint16_t port) +{ + // set destination IP + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.writeSnDIPR(s, addr); + W5100.writeSnDPORT(s, port); + W5100.execCmdSn(s, Sock_CONNECT); + SPI.endTransaction(); +} + + + +// Gracefully disconnect a TCP connection. +// +void EthernetClass::socketDisconnect(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_DISCON); + SPI.endTransaction(); +} + + + +/*****************************************/ +/* Socket Data Receive Functions */ +/*****************************************/ + + +static uint16_t getSnRX_RSR(uint8_t s) +{ +#if 1 + uint16_t val, prev; + + prev = W5100.readSnRX_RSR(s); + while (1) { + val = W5100.readSnRX_RSR(s); + if (val == prev) { + return val; + } + prev = val; + } +#else + uint16_t val = W5100.readSnRX_RSR(s); + return val; +#endif +} + +static void read_data(uint8_t s, uint16_t src, uint8_t *dst, uint16_t len) +{ + uint16_t size; + uint16_t src_mask; + uint16_t src_ptr; + + //Serial.printf("read_data, len=%d, at:%d\n", len, src); + src_mask = (uint16_t)src & W5100.SMASK; + src_ptr = W5100.RBASE(s) + src_mask; + + if (W5100.hasOffsetAddressMapping() || src_mask + len <= W5100.SSIZE) { + W5100.read(src_ptr, dst, len); + } else { + size = W5100.SSIZE - src_mask; + W5100.read(src_ptr, dst, size); + dst += size; + W5100.read(W5100.RBASE(s), dst, len - size); + } +} + +// Receive data. Returns size, or -1 for no data, or 0 if connection closed +// +int EthernetClass::socketRecv(uint8_t s, uint8_t *buf, int16_t len) +{ + // Check how much data is available + int ret = state[s].RX_RSR; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + if (ret < len) { + uint16_t rsr = getSnRX_RSR(s); + ret = rsr - state[s].RX_inc; + state[s].RX_RSR = ret; + //Serial.printf("Sock_RECV, RX_RSR=%d, RX_inc=%d\n", ret, state[s].RX_inc); + } + if (ret == 0) { + // No data available. + uint8_t status = W5100.readSnSR(s); + if ( status == SnSR::LISTEN || status == SnSR::CLOSED || + status == SnSR::CLOSE_WAIT ) { + // The remote end has closed its side of the connection, + // so this is the eof state + ret = 0; + } else { + // The connection is still up, but there's no data waiting to be read + ret = -1; + } + } else { + if (ret > len) ret = len; // more data available than buffer length + uint16_t ptr = state[s].RX_RD; + if (buf) read_data(s, ptr, buf, ret); + ptr += ret; + state[s].RX_RD = ptr; + state[s].RX_RSR -= ret; + uint16_t inc = state[s].RX_inc + ret; + if (inc >= 250 || state[s].RX_RSR == 0) { + state[s].RX_inc = 0; + W5100.writeSnRX_RD(s, ptr); + W5100.execCmdSn(s, Sock_RECV); + //Serial.printf("Sock_RECV cmd, RX_RD=%d, RX_RSR=%d\n", + // state[s].RX_RD, state[s].RX_RSR); + } else { + state[s].RX_inc = inc; + } + } + SPI.endTransaction(); + //Serial.printf("socketRecv, ret=%d\n", ret); + return ret; +} + +uint16_t EthernetClass::socketRecvAvailable(uint8_t s) +{ + uint16_t ret = state[s].RX_RSR; + if (ret == 0) { + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t rsr = getSnRX_RSR(s); + SPI.endTransaction(); + ret = rsr - state[s].RX_inc; + state[s].RX_RSR = ret; + //Serial.printf("sockRecvAvailable s=%d, RX_RSR=%d\n", s, ret); + } + return ret; +} + +// get the first byte in the receive queue (no checking) +// +uint8_t EthernetClass::socketPeek(uint8_t s) +{ + uint8_t b; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t ptr = state[s].RX_RD; + W5100.read((ptr & W5100.SMASK) + W5100.RBASE(s), &b, 1); + SPI.endTransaction(); + return b; +} + + + +/*****************************************/ +/* Socket Data Transmit Functions */ +/*****************************************/ + +static uint16_t getSnTX_FSR(uint8_t s) +{ + uint16_t val, prev; + + prev = W5100.readSnTX_FSR(s); + while (1) { + val = W5100.readSnTX_FSR(s); + if (val == prev) { + state[s].TX_FSR = val; + return val; + } + prev = val; + } +} + + +static void write_data(uint8_t s, uint16_t data_offset, const uint8_t *data, uint16_t len) +{ + uint16_t ptr = W5100.readSnTX_WR(s); + ptr += data_offset; + uint16_t offset = ptr & W5100.SMASK; + uint16_t dstAddr = offset + W5100.SBASE(s); + + if (W5100.hasOffsetAddressMapping() || offset + len <= W5100.SSIZE) { + W5100.write(dstAddr, data, len); + } else { + // Wrap around circular buffer + uint16_t size = W5100.SSIZE - offset; + W5100.write(dstAddr, data, size); + W5100.write(W5100.SBASE(s), data + size, len - size); + } + ptr += len; + W5100.writeSnTX_WR(s, ptr); +} + + +/** + * @brief This function used to send the data in TCP mode + * @return 1 for success else 0. + */ +uint16_t EthernetClass::socketSend(uint8_t s, const uint8_t * buf, uint16_t len) +{ + uint8_t status=0; + uint16_t ret=0; + uint16_t freesize=0; + + if (len > W5100.SSIZE) { + ret = W5100.SSIZE; // check size not to exceed MAX size. + } else { + ret = len; + } + + // if freebuf is available, start. + do { + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + freesize = getSnTX_FSR(s); + status = W5100.readSnSR(s); + SPI.endTransaction(); + if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT)) { + ret = 0; + break; + } + yield(); + } while (freesize < ret); + + // copy data + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + write_data(s, 0, (uint8_t *)buf, ret); + W5100.execCmdSn(s, Sock_SEND); + + /* +2008.01 bj */ + while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { + /* m2008.01 [bj] : reduce code */ + if ( W5100.readSnSR(s) == SnSR::CLOSED ) { + SPI.endTransaction(); + return 0; + } + SPI.endTransaction(); + yield(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + } + /* +2008.01 bj */ + W5100.writeSnIR(s, SnIR::SEND_OK); + SPI.endTransaction(); + return ret; +} + +uint16_t EthernetClass::socketSendAvailable(uint8_t s) +{ + uint8_t status=0; + uint16_t freesize=0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + freesize = getSnTX_FSR(s); + status = W5100.readSnSR(s); + SPI.endTransaction(); + if ((status == SnSR::ESTABLISHED) || (status == SnSR::CLOSE_WAIT)) { + return freesize; + } + return 0; +} + +uint16_t EthernetClass::socketBufferData(uint8_t s, uint16_t offset, const uint8_t* buf, uint16_t len) +{ + //Serial.printf(" bufferData, offset=%d, len=%d\n", offset, len); + uint16_t ret =0; + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + uint16_t txfree = getSnTX_FSR(s); + if (len > txfree) { + ret = txfree; // check size not to exceed MAX size. + } else { + ret = len; + } + write_data(s, offset, buf, ret); + SPI.endTransaction(); + return ret; +} + +bool EthernetClass::socketStartUDP(uint8_t s, uint8_t* addr, uint16_t port) +{ + if ( ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) || + ((port == 0x00)) ) { + return false; + } + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.writeSnDIPR(s, addr); + W5100.writeSnDPORT(s, port); + SPI.endTransaction(); + return true; +} + +bool EthernetClass::socketSendUDP(uint8_t s) +{ + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + W5100.execCmdSn(s, Sock_SEND); + + /* +2008.01 bj */ + while ( (W5100.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) { + if (W5100.readSnIR(s) & SnIR::TIMEOUT) { + /* +2008.01 [bj]: clear interrupt */ + W5100.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT)); + SPI.endTransaction(); + //Serial.printf("sendUDP timeout\n"); + return false; + } + SPI.endTransaction(); + yield(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + } + + /* +2008.01 bj */ + W5100.writeSnIR(s, SnIR::SEND_OK); + SPI.endTransaction(); + + //Serial.printf("sendUDP ok\n"); + /* Sent ok */ + return true; +} diff --git a/libs/Ethernet/src/utility/w5100.cpp b/libs/Ethernet/src/utility/w5100.cpp new file mode 100644 index 0000000..6e7dbd2 --- /dev/null +++ b/libs/Ethernet/src/utility/w5100.cpp @@ -0,0 +1,474 @@ +/* + * Copyright 2018 Paul Stoffregen + * Copyright (c) 2010 by Cristian Maglie + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +#include +#include "Ethernet.h" +#include "w5100.h" + + +/***************************************************/ +/** Default SS pin setting **/ +/***************************************************/ + +// If variant.h or other headers specifically define the +// default SS pin for Ethernet, use it. +#if defined(PIN_SPI_SS_ETHERNET_LIB) +#define SS_PIN_DEFAULT PIN_SPI_SS_ETHERNET_LIB + +// MKR boards default to pin 5 for MKR ETH +// Pins 8-10 are MOSI/SCK/MISO on MRK, so don't use pin 10 +#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) +#define SS_PIN_DEFAULT 5 + +// For boards using AVR, assume shields with SS on pin 10 +// will be used. This allows for Arduino Mega (where +// SS is pin 53) and Arduino Leonardo (where SS is pin 17) +// to work by default with Arduino Ethernet Shield R2 & R3. +#elif defined(__AVR__) +#define SS_PIN_DEFAULT 10 + +// If variant.h or other headers define these names +// use them if none of the other cases match +#elif defined(PIN_SPI_SS) +#define SS_PIN_DEFAULT PIN_SPI_SS +#elif defined(CORE_SS0_PIN) +#define SS_PIN_DEFAULT CORE_SS0_PIN + +// As a final fallback, use pin 10 +#else +#define SS_PIN_DEFAULT 10 +#endif + + + + +// W5100 controller instance +uint8_t W5100Class::chip = 0; +uint8_t W5100Class::CH_BASE_MSB; +uint8_t W5100Class::ss_pin = SS_PIN_DEFAULT; +#ifdef ETHERNET_LARGE_BUFFERS +uint16_t W5100Class::SSIZE = 2048; +uint16_t W5100Class::SMASK = 0x07FF; +#endif +W5100Class W5100; + +// pointers and bitmasks for optimized SS pin +#if defined(__AVR__) + volatile uint8_t * W5100Class::ss_pin_reg; + uint8_t W5100Class::ss_pin_mask; +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) + volatile uint8_t * W5100Class::ss_pin_reg; +#elif defined(__MKL26Z64__) + volatile uint8_t * W5100Class::ss_pin_reg; + uint8_t W5100Class::ss_pin_mask; +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(__PIC32MX__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(ARDUINO_ARCH_ESP8266) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#elif defined(__SAMD21G18A__) + volatile uint32_t * W5100Class::ss_pin_reg; + uint32_t W5100Class::ss_pin_mask; +#endif + + +uint8_t W5100Class::init(void) +{ + static bool initialized = false; + uint8_t i; + + if (initialized) return 1; + + // Many Ethernet shields have a CAT811 or similar reset chip + // connected to W5100 or W5200 chips. The W5200 will not work at + // all, and may even drive its MISO pin, until given an active low + // reset pulse! The CAT811 has a 240 ms typical pulse length, and + // a 400 ms worst case maximum pulse length. MAX811 has a worst + // case maximum 560 ms pulse length. This delay is meant to wait + // until the reset pulse is ended. If your hardware has a shorter + // reset time, this can be edited or removed. + delay(560); + //Serial.println("w5100 init"); + + SPI.begin(); + initSS(); + resetSS(); + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + + // Attempt W5200 detection first, because W5200 does not properly + // reset its SPI state when CS goes high (inactive). Communication + // from detecting the other chips can leave the W5200 in a state + // where it won't recover, unless given a reset pulse. + if (isW5200()) { + CH_BASE_MSB = 0x40; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 16384; +#elif MAX_SOCK_NUM <= 2 + SSIZE = 8192; +#elif MAX_SOCK_NUM <= 4 + SSIZE = 4096; +#else + SSIZE = 2048; +#endif + SMASK = SSIZE - 1; +#endif + for (i=0; i> 10); + writeSnTX_SIZE(i, SSIZE >> 10); + } + for (; i<8; i++) { + writeSnRX_SIZE(i, 0); + writeSnTX_SIZE(i, 0); + } + // Try W5500 next. WIZnet finally seems to have implemented + // SPI well with this chip. It appears to be very resilient, + // so try it after the fragile W5200 + } else if (isW5500()) { + CH_BASE_MSB = 0x10; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 16384; +#elif MAX_SOCK_NUM <= 2 + SSIZE = 8192; +#elif MAX_SOCK_NUM <= 4 + SSIZE = 4096; +#else + SSIZE = 2048; +#endif + SMASK = SSIZE - 1; + for (i=0; i> 10); + writeSnTX_SIZE(i, SSIZE >> 10); + } + for (; i<8; i++) { + writeSnRX_SIZE(i, 0); + writeSnTX_SIZE(i, 0); + } +#endif + // Try W5100 last. This simple chip uses fixed 4 byte frames + // for every 8 bit access. Terribly inefficient, but so simple + // it recovers from "hearing" unsuccessful W5100 or W5200 + // communication. W5100 is also the only chip without a VERSIONR + // register for identification, so we check this last. + } else if (isW5100()) { + CH_BASE_MSB = 0x04; +#ifdef ETHERNET_LARGE_BUFFERS +#if MAX_SOCK_NUM <= 1 + SSIZE = 8192; + writeTMSR(0x03); + writeRMSR(0x03); +#elif MAX_SOCK_NUM <= 2 + SSIZE = 4096; + writeTMSR(0x0A); + writeRMSR(0x0A); +#else + SSIZE = 2048; + writeTMSR(0x55); + writeRMSR(0x55); +#endif + SMASK = SSIZE - 1; +#else + writeTMSR(0x55); + writeRMSR(0x55); +#endif + // No hardware seems to be present. Or it could be a W5200 + // that's heard other SPI communication if its chip select + // pin wasn't high when a SD card or other SPI chip was used. + } else { + //Serial.println("no chip :-("); + chip = 0; + SPI.endTransaction(); + return 0; // no known chip is responding :-( + } + SPI.endTransaction(); + initialized = true; + return 1; // successful init +} + +// Soft reset the WIZnet chip, by writing to its MR register reset bit +uint8_t W5100Class::softReset(void) +{ + uint16_t count=0; + + //Serial.println("WIZnet soft reset"); + // write to reset bit + writeMR(0x80); + // then wait for soft reset to complete + do { + uint8_t mr = readMR(); + //Serial.print("mr="); + //Serial.println(mr, HEX); + if (mr == 0) return 1; + delay(1); + } while (++count < 20); + return 0; +} + +uint8_t W5100Class::isW5100(void) +{ + chip = 51; + //Serial.println("w5100.cpp: detect W5100 chip"); + if (!softReset()) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x12); + if (readMR() != 0x12) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + //Serial.println("chip is W5100"); + return 1; +} + +uint8_t W5100Class::isW5200(void) +{ + chip = 52; + //Serial.println("w5100.cpp: detect W5200 chip"); + if (!softReset()) return 0; + writeMR(0x08); + if (readMR() != 0x08) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + int ver = readVERSIONR_W5200(); + //Serial.print("version="); + //Serial.println(ver); + if (ver != 3) return 0; + //Serial.println("chip is W5200"); + return 1; +} + +uint8_t W5100Class::isW5500(void) +{ + chip = 55; + //Serial.println("w5100.cpp: detect W5500 chip"); + if (!softReset()) return 0; + writeMR(0x08); + if (readMR() != 0x08) return 0; + writeMR(0x10); + if (readMR() != 0x10) return 0; + writeMR(0x00); + if (readMR() != 0x00) return 0; + int ver = readVERSIONR_W5500(); + //Serial.print("version="); + //Serial.println(ver); + if (ver != 4) return 0; + //Serial.println("chip is W5500"); + return 1; +} + +W5100Linkstatus W5100Class::getLinkStatus() +{ + uint8_t phystatus; + + if (!init()) return UNKNOWN; + switch (chip) { + case 52: + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + phystatus = readPSTATUS_W5200(); + SPI.endTransaction(); + if (phystatus & 0x20) return LINK_ON; + return LINK_OFF; + case 55: + SPI.beginTransaction(SPI_ETHERNET_SETTINGS); + phystatus = readPHYCFGR_W5500(); + SPI.endTransaction(); + if (phystatus & 0x01) return LINK_ON; + return LINK_OFF; + default: + return UNKNOWN; + } +} + +uint16_t W5100Class::write(uint16_t addr, const uint8_t *buf, uint16_t len) +{ + uint8_t cmd[8]; + + if (chip == 51) { + for (uint16_t i=0; i> 8); + SPI.transfer(addr & 0xFF); + addr++; + SPI.transfer(buf[i]); + resetSS(); + } + } else if (chip == 52) { + setSS(); + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + cmd[2] = ((len >> 8) & 0x7F) | 0x80; + cmd[3] = len & 0xFF; + SPI.transfer(cmd, 4); +#ifdef SPI_HAS_TRANSFER_BUF + SPI.transfer(buf, NULL, len); +#else + // TODO: copy 8 bytes at a time to cmd[] and block transfer + for (uint16_t i=0; i < len; i++) { + SPI.transfer(buf[i]); + } +#endif + resetSS(); + } else { // chip == 55 + setSS(); + if (addr < 0x100) { + // common registers 00nn + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = 0x04; + } else if (addr < 0x8000) { + // socket registers 10nn, 11nn, 12nn, 13nn, etc + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = ((addr >> 3) & 0xE0) | 0x0C; + } else if (addr < 0xC000) { + // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc + // 10## #nnn nnnn nnnn + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x14; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x14; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x14; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x14; // 2K buffers + #endif + } else { + // receive buffers + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x1C; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x1C; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x1C; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x1C; // 2K buffers + #endif + } + if (len <= 5) { + for (uint8_t i=0; i < len; i++) { + cmd[i + 3] = buf[i]; + } + SPI.transfer(cmd, len + 3); + } else { + SPI.transfer(cmd, 3); +#ifdef SPI_HAS_TRANSFER_BUF + SPI.transfer(buf, NULL, len); +#else + // TODO: copy 8 bytes at a time to cmd[] and block transfer + for (uint16_t i=0; i < len; i++) { + SPI.transfer(buf[i]); + } +#endif + } + resetSS(); + } + return len; +} + +uint16_t W5100Class::read(uint16_t addr, uint8_t *buf, uint16_t len) +{ + uint8_t cmd[4]; + + if (chip == 51) { + for (uint16_t i=0; i < len; i++) { + setSS(); + #if 1 + SPI.transfer(0x0F); + SPI.transfer(addr >> 8); + SPI.transfer(addr & 0xFF); + addr++; + buf[i] = SPI.transfer(0); + #else + cmd[0] = 0x0F; + cmd[1] = addr >> 8; + cmd[2] = addr & 0xFF; + cmd[3] = 0; + SPI.transfer(cmd, 4); // TODO: why doesn't this work? + buf[i] = cmd[3]; + addr++; + #endif + resetSS(); + } + } else if (chip == 52) { + setSS(); + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + cmd[2] = (len >> 8) & 0x7F; + cmd[3] = len & 0xFF; + SPI.transfer(cmd, 4); + memset(buf, 0, len); + SPI.transfer(buf, len); + resetSS(); + } else { // chip == 55 + setSS(); + if (addr < 0x100) { + // common registers 00nn + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = 0x00; + } else if (addr < 0x8000) { + // socket registers 10nn, 11nn, 12nn, 13nn, etc + cmd[0] = 0; + cmd[1] = addr & 0xFF; + cmd[2] = ((addr >> 3) & 0xE0) | 0x08; + } else if (addr < 0xC000) { + // transmit buffers 8000-87FF, 8800-8FFF, 9000-97FF, etc + // 10## #nnn nnnn nnnn + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x10; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x10; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x10; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x10; // 2K buffers + #endif + } else { + // receive buffers + cmd[0] = addr >> 8; + cmd[1] = addr & 0xFF; + #if defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 1 + cmd[2] = 0x18; // 16K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 2 + cmd[2] = ((addr >> 8) & 0x20) | 0x18; // 8K buffers + #elif defined(ETHERNET_LARGE_BUFFERS) && MAX_SOCK_NUM <= 4 + cmd[2] = ((addr >> 7) & 0x60) | 0x18; // 4K buffers + #else + cmd[2] = ((addr >> 6) & 0xE0) | 0x18; // 2K buffers + #endif + } + SPI.transfer(cmd, 3); + memset(buf, 0, len); + SPI.transfer(buf, len); + resetSS(); + } + return len; +} + +void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) +{ + // Send command to socket + writeSnCR(s, _cmd); + // Wait for command to complete + while (readSnCR(s)) ; +} diff --git a/libs/Ethernet/src/utility/w5100.h b/libs/Ethernet/src/utility/w5100.h new file mode 100644 index 0000000..b2e8ec8 --- /dev/null +++ b/libs/Ethernet/src/utility/w5100.h @@ -0,0 +1,479 @@ +/* + * Copyright 2018 Paul Stoffregen + * Copyright (c) 2010 by Cristian Maglie + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ + +// w5100.h contains private W5x00 hardware "driver" level definitions +// which are not meant to be exposed to other libraries or Arduino users + +#ifndef W5100_H_INCLUDED +#define W5100_H_INCLUDED + +#include +#include + +// Safe for all chips +#define SPI_ETHERNET_SETTINGS SPISettings(14000000, MSBFIRST, SPI_MODE0) + +// Safe for W5200 and W5500, but too fast for W5100 +// Uncomment this if you know you'll never need W5100 support. +// Higher SPI clock only results in faster transfer to hosts on a LAN +// or with very low packet latency. With ordinary internet latency, +// the TCP window size & packet loss determine your overall speed. +//#define SPI_ETHERNET_SETTINGS SPISettings(30000000, MSBFIRST, SPI_MODE0) + + +// Require Ethernet.h, because we need MAX_SOCK_NUM +#ifndef ethernet_h_ +#error "Ethernet.h must be included before w5100.h" +#endif + + +// Arduino 101's SPI can not run faster than 8 MHz. +#if defined(ARDUINO_ARCH_ARC32) +#undef SPI_ETHERNET_SETTINGS +#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) +#endif + +// Arduino Zero can't use W5100-based shields faster than 8 MHz +// https://github.com/arduino-libraries/Ethernet/issues/37#issuecomment-408036848 +// W5500 does seem to work at 12 MHz. Delete this if only using W5500 +#if defined(__SAMD21G18A__) +#undef SPI_ETHERNET_SETTINGS +#define SPI_ETHERNET_SETTINGS SPISettings(8000000, MSBFIRST, SPI_MODE0) +#endif + + +typedef uint8_t SOCKET; + +class SnMR { +public: + static const uint8_t CLOSE = 0x00; + static const uint8_t TCP = 0x21; + static const uint8_t UDP = 0x02; + static const uint8_t IPRAW = 0x03; + static const uint8_t MACRAW = 0x04; + static const uint8_t PPPOE = 0x05; + static const uint8_t ND = 0x20; + static const uint8_t MULTI = 0x80; +}; + +enum SockCMD { + Sock_OPEN = 0x01, + Sock_LISTEN = 0x02, + Sock_CONNECT = 0x04, + Sock_DISCON = 0x08, + Sock_CLOSE = 0x10, + Sock_SEND = 0x20, + Sock_SEND_MAC = 0x21, + Sock_SEND_KEEP = 0x22, + Sock_RECV = 0x40 +}; + +class SnIR { +public: + static const uint8_t SEND_OK = 0x10; + static const uint8_t TIMEOUT = 0x08; + static const uint8_t RECV = 0x04; + static const uint8_t DISCON = 0x02; + static const uint8_t CON = 0x01; +}; + +class SnSR { +public: + static const uint8_t CLOSED = 0x00; + static const uint8_t INIT = 0x13; + static const uint8_t LISTEN = 0x14; + static const uint8_t SYNSENT = 0x15; + static const uint8_t SYNRECV = 0x16; + static const uint8_t ESTABLISHED = 0x17; + static const uint8_t FIN_WAIT = 0x18; + static const uint8_t CLOSING = 0x1A; + static const uint8_t TIME_WAIT = 0x1B; + static const uint8_t CLOSE_WAIT = 0x1C; + static const uint8_t LAST_ACK = 0x1D; + static const uint8_t UDP = 0x22; + static const uint8_t IPRAW = 0x32; + static const uint8_t MACRAW = 0x42; + static const uint8_t PPPOE = 0x5F; +}; + +class IPPROTO { +public: + static const uint8_t IP = 0; + static const uint8_t ICMP = 1; + static const uint8_t IGMP = 2; + static const uint8_t GGP = 3; + static const uint8_t TCP = 6; + static const uint8_t PUP = 12; + static const uint8_t UDP = 17; + static const uint8_t IDP = 22; + static const uint8_t ND = 77; + static const uint8_t RAW = 255; +}; + +enum W5100Linkstatus { + UNKNOWN, + LINK_ON, + LINK_OFF +}; + +class W5100Class { + +public: + static uint8_t init(void); + + inline void setGatewayIp(const uint8_t * addr) { writeGAR(addr); } + inline void getGatewayIp(uint8_t * addr) { readGAR(addr); } + + inline void setSubnetMask(const uint8_t * addr) { writeSUBR(addr); } + inline void getSubnetMask(uint8_t * addr) { readSUBR(addr); } + + inline void setMACAddress(const uint8_t * addr) { writeSHAR(addr); } + inline void getMACAddress(uint8_t * addr) { readSHAR(addr); } + + inline void setIPAddress(const uint8_t * addr) { writeSIPR(addr); } + inline void getIPAddress(uint8_t * addr) { readSIPR(addr); } + + inline void setRetransmissionTime(uint16_t timeout) { writeRTR(timeout); } + inline void setRetransmissionCount(uint8_t retry) { writeRCR(retry); } + + static void execCmdSn(SOCKET s, SockCMD _cmd); + + + // W5100 Registers + // --------------- +//private: +public: + static uint16_t write(uint16_t addr, const uint8_t *buf, uint16_t len); + static uint8_t write(uint16_t addr, uint8_t data) { + return write(addr, &data, 1); + } + static uint16_t read(uint16_t addr, uint8_t *buf, uint16_t len); + static uint8_t read(uint16_t addr) { + uint8_t data; + read(addr, &data, 1); + return data; + } + +#define __GP_REGISTER8(name, address) \ + static inline void write##name(uint8_t _data) { \ + write(address, _data); \ + } \ + static inline uint8_t read##name() { \ + return read(address); \ + } +#define __GP_REGISTER16(name, address) \ + static void write##name(uint16_t _data) { \ + uint8_t buf[2]; \ + buf[0] = _data >> 8; \ + buf[1] = _data & 0xFF; \ + write(address, buf, 2); \ + } \ + static uint16_t read##name() { \ + uint8_t buf[2]; \ + read(address, buf, 2); \ + return (buf[0] << 8) | buf[1]; \ + } +#define __GP_REGISTER_N(name, address, size) \ + static uint16_t write##name(const uint8_t *_buff) { \ + return write(address, _buff, size); \ + } \ + static uint16_t read##name(uint8_t *_buff) { \ + return read(address, _buff, size); \ + } + static W5100Linkstatus getLinkStatus(); + +public: + __GP_REGISTER8 (MR, 0x0000); // Mode + __GP_REGISTER_N(GAR, 0x0001, 4); // Gateway IP address + __GP_REGISTER_N(SUBR, 0x0005, 4); // Subnet mask address + __GP_REGISTER_N(SHAR, 0x0009, 6); // Source MAC address + __GP_REGISTER_N(SIPR, 0x000F, 4); // Source IP address + __GP_REGISTER8 (IR, 0x0015); // Interrupt + __GP_REGISTER8 (IMR, 0x0016); // Interrupt Mask + __GP_REGISTER16(RTR, 0x0017); // Timeout address + __GP_REGISTER8 (RCR, 0x0019); // Retry count + __GP_REGISTER8 (RMSR, 0x001A); // Receive memory size (W5100 only) + __GP_REGISTER8 (TMSR, 0x001B); // Transmit memory size (W5100 only) + __GP_REGISTER8 (PATR, 0x001C); // Authentication type address in PPPoE mode + __GP_REGISTER8 (PTIMER, 0x0028); // PPP LCP Request Timer + __GP_REGISTER8 (PMAGIC, 0x0029); // PPP LCP Magic Number + __GP_REGISTER_N(UIPR, 0x002A, 4); // Unreachable IP address in UDP mode (W5100 only) + __GP_REGISTER16(UPORT, 0x002E); // Unreachable Port address in UDP mode (W5100 only) + __GP_REGISTER8 (VERSIONR_W5200,0x001F); // Chip Version Register (W5200 only) + __GP_REGISTER8 (VERSIONR_W5500,0x0039); // Chip Version Register (W5500 only) + __GP_REGISTER8 (PSTATUS_W5200, 0x0035); // PHY Status + __GP_REGISTER8 (PHYCFGR_W5500, 0x002E); // PHY Configuration register, default: 10111xxx + + +#undef __GP_REGISTER8 +#undef __GP_REGISTER16 +#undef __GP_REGISTER_N + + // W5100 Socket registers + // ---------------------- +private: + static uint16_t CH_BASE(void) { + //if (chip == 55) return 0x1000; + //if (chip == 52) return 0x4000; + //return 0x0400; + return CH_BASE_MSB << 8; + } + static uint8_t CH_BASE_MSB; // 1 redundant byte, saves ~80 bytes code on AVR + static const uint16_t CH_SIZE = 0x0100; + + static inline uint8_t readSn(SOCKET s, uint16_t addr) { + return read(CH_BASE() + s * CH_SIZE + addr); + } + static inline uint8_t writeSn(SOCKET s, uint16_t addr, uint8_t data) { + return write(CH_BASE() + s * CH_SIZE + addr, data); + } + static inline uint16_t readSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { + return read(CH_BASE() + s * CH_SIZE + addr, buf, len); + } + static inline uint16_t writeSn(SOCKET s, uint16_t addr, uint8_t *buf, uint16_t len) { + return write(CH_BASE() + s * CH_SIZE + addr, buf, len); + } + +#define __SOCKET_REGISTER8(name, address) \ + static inline void write##name(SOCKET _s, uint8_t _data) { \ + writeSn(_s, address, _data); \ + } \ + static inline uint8_t read##name(SOCKET _s) { \ + return readSn(_s, address); \ + } +#define __SOCKET_REGISTER16(name, address) \ + static void write##name(SOCKET _s, uint16_t _data) { \ + uint8_t buf[2]; \ + buf[0] = _data >> 8; \ + buf[1] = _data & 0xFF; \ + writeSn(_s, address, buf, 2); \ + } \ + static uint16_t read##name(SOCKET _s) { \ + uint8_t buf[2]; \ + readSn(_s, address, buf, 2); \ + return (buf[0] << 8) | buf[1]; \ + } +#define __SOCKET_REGISTER_N(name, address, size) \ + static uint16_t write##name(SOCKET _s, uint8_t *_buff) { \ + return writeSn(_s, address, _buff, size); \ + } \ + static uint16_t read##name(SOCKET _s, uint8_t *_buff) { \ + return readSn(_s, address, _buff, size); \ + } + +public: + __SOCKET_REGISTER8(SnMR, 0x0000) // Mode + __SOCKET_REGISTER8(SnCR, 0x0001) // Command + __SOCKET_REGISTER8(SnIR, 0x0002) // Interrupt + __SOCKET_REGISTER8(SnSR, 0x0003) // Status + __SOCKET_REGISTER16(SnPORT, 0x0004) // Source Port + __SOCKET_REGISTER_N(SnDHAR, 0x0006, 6) // Destination Hardw Addr + __SOCKET_REGISTER_N(SnDIPR, 0x000C, 4) // Destination IP Addr + __SOCKET_REGISTER16(SnDPORT, 0x0010) // Destination Port + __SOCKET_REGISTER16(SnMSSR, 0x0012) // Max Segment Size + __SOCKET_REGISTER8(SnPROTO, 0x0014) // Protocol in IP RAW Mode + __SOCKET_REGISTER8(SnTOS, 0x0015) // IP TOS + __SOCKET_REGISTER8(SnTTL, 0x0016) // IP TTL + __SOCKET_REGISTER8(SnRX_SIZE, 0x001E) // RX Memory Size (W5200 only) + __SOCKET_REGISTER8(SnTX_SIZE, 0x001F) // RX Memory Size (W5200 only) + __SOCKET_REGISTER16(SnTX_FSR, 0x0020) // TX Free Size + __SOCKET_REGISTER16(SnTX_RD, 0x0022) // TX Read Pointer + __SOCKET_REGISTER16(SnTX_WR, 0x0024) // TX Write Pointer + __SOCKET_REGISTER16(SnRX_RSR, 0x0026) // RX Free Size + __SOCKET_REGISTER16(SnRX_RD, 0x0028) // RX Read Pointer + __SOCKET_REGISTER16(SnRX_WR, 0x002A) // RX Write Pointer (supported?) + +#undef __SOCKET_REGISTER8 +#undef __SOCKET_REGISTER16 +#undef __SOCKET_REGISTER_N + + +private: + static uint8_t chip; + static uint8_t ss_pin; + static uint8_t softReset(void); + static uint8_t isW5100(void); + static uint8_t isW5200(void); + static uint8_t isW5500(void); + +public: + static uint8_t getChip(void) { return chip; } +#ifdef ETHERNET_LARGE_BUFFERS + static uint16_t SSIZE; + static uint16_t SMASK; +#else + static const uint16_t SSIZE = 2048; + static const uint16_t SMASK = 0x07FF; +#endif + static uint16_t SBASE(uint8_t socknum) { + if (chip == 51) { + return socknum * SSIZE + 0x4000; + } else { + return socknum * SSIZE + 0x8000; + } + } + static uint16_t RBASE(uint8_t socknum) { + if (chip == 51) { + return socknum * SSIZE + 0x6000; + } else { + return socknum * SSIZE + 0xC000; + } + } + + static bool hasOffsetAddressMapping(void) { + if (chip == 55) return true; + return false; + } + static void setSS(uint8_t pin) { ss_pin = pin; } + +private: +#if defined(__AVR__) + static volatile uint8_t *ss_pin_reg; + static uint8_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg) &= ~ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg) |= ss_pin_mask; + } +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) + static volatile uint8_t *ss_pin_reg; + inline static void initSS() { + ss_pin_reg = portOutputRegister(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+256) = 1; + } + inline static void resetSS() { + *(ss_pin_reg+128) = 1; + } +#elif defined(__MKL26Z64__) + static volatile uint8_t *ss_pin_reg; + static uint8_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portOutputRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+8) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+4) = ss_pin_mask; + } +#elif defined(__SAM3X8E__) || defined(__SAM3A8C__) || defined(__SAM3A4C__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = &(digitalPinToPort(ss_pin)->PIO_PER); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+13) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+12) = ss_pin_mask; + } +#elif defined(__PIC32MX__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+8+1) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+8+2) = ss_pin_mask; + } + +#elif defined(ARDUINO_ARCH_ESP8266) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = (volatile uint32_t*)GPO; + ss_pin_mask = 1 << ss_pin; + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + GPOC = ss_pin_mask; + } + inline static void resetSS() { + GPOS = ss_pin_mask; + } + +#elif defined(__SAMD21G18A__) + static volatile uint32_t *ss_pin_reg; + static uint32_t ss_pin_mask; + inline static void initSS() { + ss_pin_reg = portModeRegister(digitalPinToPort(ss_pin)); + ss_pin_mask = digitalPinToBitMask(ss_pin); + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + *(ss_pin_reg+5) = ss_pin_mask; + } + inline static void resetSS() { + *(ss_pin_reg+6) = ss_pin_mask; + } +#else + inline static void initSS() { + pinMode(ss_pin, OUTPUT); + } + inline static void setSS() { + digitalWrite(ss_pin, LOW); + } + inline static void resetSS() { + digitalWrite(ss_pin, HIGH); + } +#endif +}; + +extern W5100Class W5100; + + + +#endif + +#ifndef UTIL_H +#define UTIL_H + +#ifndef htons +// The host order of the Arduino platform is little endian. +// Sometimes it is desired to convert to big endian (or +// network order) + +// Host to Network short +#define htons(x) ( (((x)&0xFF)<<8) | (((x)>>8)&0xFF) ) + +// Network to Host short +#define ntohs(x) htons(x) + +// Host to Network long +#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ + ((x)<< 8 & 0x00FF0000UL) | \ + ((x)>> 8 & 0x0000FF00UL) | \ + ((x)>>24 & 0x000000FFUL) ) + +// Network to Host long +#define ntohl(x) htonl(x) + +#endif // !defined(htons) + +#endif diff --git a/libs/Firmata/Boards.h b/libs/Firmata/Boards.h new file mode 100644 index 0000000..211404c --- /dev/null +++ b/libs/Firmata/Boards.h @@ -0,0 +1,1203 @@ +/* + Boards.h - Hardware Abstraction Layer for Firmata library + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated April 15th, 2018 +*/ + +#ifndef Firmata_Boards_h +#define Firmata_Boards_h + +#include + +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" // for digitalRead, digitalWrite, etc +#else +#include "WProgram.h" +#endif + +// Normally Servo.h must be included before Firmata.h (which then includes +// this file). If Servo.h wasn't included, this allows the code to still +// compile, but without support for any Servos. Hopefully that's what the +// user intended by not including Servo.h +#ifndef MAX_SERVOS +#define MAX_SERVOS 0 +#endif + +/* + Firmata Hardware Abstraction Layer + +Firmata is built on top of the hardware abstraction functions of Arduino, +specifically digitalWrite, digitalRead, analogWrite, analogRead, and +pinMode. While these functions offer simple integer pin numbers, Firmata +needs more information than is provided by Arduino. This file provides +all other hardware specific details. To make Firmata support a new board, +only this file should require editing. + +The key concept is every "pin" implemented by Firmata may be mapped to +any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is +best, but such mapping should not be assumed. This hardware abstraction +layer allows Firmata to implement any number of pins which map onto the +Arduino implemented pins in almost any arbitrary way. + + +General Constants: + +These constants provide basic information Firmata requires. + +TOTAL_PINS: The total number of pins Firmata implemented by Firmata. + Usually this will match the number of pins the Arduino functions + implement, including any pins pins capable of analog or digital. + However, Firmata may implement any number of pins. For example, + on Arduino Mini with 8 analog inputs, 6 of these may be used + for digital functions, and 2 are analog only. On such boards, + Firmata can implement more pins than Arduino's pinMode() + function, in order to accommodate those special pins. The + Firmata protocol supports a maximum of 128 pins, so this + constant must not exceed 128. + +TOTAL_ANALOG_PINS: The total number of analog input pins implemented. + The Firmata protocol allows up to 16 analog inputs, accessed + using offsets 0 to 15. Because Firmata presents the analog + inputs using different offsets than the actual pin numbers + (a legacy of Arduino's analogRead function, and the way the + analog input capable pins are physically labeled on all + Arduino boards), the total number of analog input signals + must be specified. 16 is the maximum. + +VERSION_BLINK_PIN: When Firmata starts up, it will blink the version + number. This constant is the Arduino pin number where a + LED is connected. + + +Pin Mapping Macros: + +These macros provide the mapping between pins as implemented by +Firmata protocol and the actual pin numbers used by the Arduino +functions. Even though such mappings are often simple, pin +numbers received by Firmata protocol should always be used as +input to these macros, and the result of the macro should be +used with with any Arduino function. + +When Firmata is extended to support a new pin mode or feature, +a pair of macros should be added and used for all hardware +access. For simple 1:1 mapping, these macros add no actual +overhead, yet their consistent use allows source code which +uses them consistently to be easily adapted to all other boards +with different requirements. + +IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero + if a pin as implemented by Firmata corresponds to a pin + that actually implements the named feature. + +PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as + implemented by Firmata to the pin numbers needed as inputs + to the Arduino functions. The corresponding IS_PIN macro + should always be tested before using a PIN_TO macro, so + these macros only need to handle valid Firmata pin + numbers for the named feature. + + +Port Access Inline Funtions: + +For efficiency, Firmata protocol provides access to digital +input and output pins grouped by 8 bit ports. When these +groups of 8 correspond to actual 8 bit ports as implemented +by the hardware, these inline functions can provide high +speed direct port access. Otherwise, a default implementation +using 8 calls to digitalWrite or digitalRead is used. + +When porting Firmata to a new board, it is recommended to +use the default functions first and focus only on the constants +and macros above. When those are working, if optimized port +access is desired, these inline functions may be extended. +The recommended approach defines a symbol indicating which +optimization to use, and then conditional complication is +used within these functions. + +readPort(port, bitmask): Read an 8 bit port, returning the value. + port: The port number, Firmata pins port*8 to port*8+7 + bitmask: The actual pins to read, indicated by 1 bits. + +writePort(port, value, bitmask): Write an 8 bit port. + port: The port number, Firmata pins port*8 to port*8+7 + value: The 8 bit value to write + bitmask: The actual pins to write, indicated by 1 bits. +*/ + +/*============================================================================== + * Board Specific Configuration + *============================================================================*/ + +#ifndef digitalPinHasPWM +#define digitalPinHasPWM(p) IS_PIN_DIGITAL(p) +#endif + +// Arduino Duemilanove, Diecimila, and NG +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) +#if defined(NUM_ANALOG_INPUTS) && NUM_ANALOG_INPUTS == 6 +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#else +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 22 // 14 digital + 8 analog +#endif +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Wiring (and board) +#elif defined(WIRING) +#define VERSION_BLINK_PIN WLED +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= FIRST_ANALOG_PIN && (p) < (FIRST_ANALOG_PIN+TOTAL_ANALOG_PINS)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - FIRST_ANALOG_PIN) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// old Arduinos +#elif defined(__AVR_ATmega8__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Arduino Mega +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS 70 // 54 digital + 16 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + +// Arduino UNO WiFi rev2 (ATMega 4809) +#elif defined(__AVR_ATmega4809__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog + /* 3 SPI (unexported, on ISP header) */ +#define VERSION_BLINK_PIN 25 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (p) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) - 14 +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + +#elif defined(AVR_NANO_EVERY) || defined(ARDUINO_NANO_EVERY) || defined(ARDUINO_AVR_NANO_EVERY) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 24 // 14 digital + 8 analog + 2 i2c +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 21) // TBD if pins 0 and 1 are usable +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) // SDA = 22, SCL = 23 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino DUE +#elif defined(__SAM3X8E__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 66 // 54 digital + 12 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // 70 71 +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Arduino Nano 33 IoT +#elif defined(ARDUINO_SAMD_NANO_33_IOT) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 22 // 14 Digital + 8 Analog +#define IS_PIN_DIGITAL(p) ((p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) > 13 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) +#define IS_PIN_SPI(p) ((p) == PIN_SPI_SS || (p) == PIN_SPI_MOSI || (p) == PIN_SPI_MISO || (p) == PIN_SPI_SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 0 TX = 1 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino Nano 33 BLE +#elif defined(ARDUINO_ARDUINO_NANO33BLE) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 22 // 14 Digital + 8 Analog +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) // SDA = 18, SCL = 19 +#define IS_PIN_SPI(p) ((p) == PIN_SPI_SS || (p) == PIN_SPI_MOSI || (p) == PIN_SPI_MISO || (p) == PIN_SPI_SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL_RX || (p) == PIN_SERIAL_TX) //defined in pins_arduino.h RX = 1 TX = 0 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino/Genuino MKR1000 or MKR1010 +#elif defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 22 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 21) +#define IS_PIN_ANALOG(p) ((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino MKRZero +#elif defined(ARDUINO_SAMD_MKRZERO) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 34 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog + 3 usb + 1 aref + 5 sd + 1 bottom pad + 1 led + 1 battery adc +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21) || (p) == 32) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 33) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKRFox1200 +#elif defined(ARDUINO_SAMD_MKRFox1200) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog + 3 usb + 1 aref + 5 sd + 1 bottom pad + 1 battery adc +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKR WAN 1300 +#elif defined(ARDUINO_SAMD_MKRWAN1300) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino MKR GSM 1400 +#elif defined(ARDUINO_SAMD_MKRGSM1400) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 33 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21)) +#define IS_PIN_ANALOG(p) (((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) || (p) == 32) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino Zero +// Note this will work with an Arduino Zero Pro, but not with an Arduino M0 Pro +// Arduino M0 Pro does not properly map pins to the board labeled pin numbers +#elif defined(_VARIANT_ARDUINO_ZERO_) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 25 // 14 digital + 6 analog + 2 i2c + 3 spi +#define TOTAL_PORTS 3 // set when TOTAL_PINS > num digitial I/O pins +#define VERSION_BLINK_PIN LED_BUILTIN +//#define PIN_SERIAL1_RX 0 // already defined in zero core variant.h +//#define PIN_SERIAL1_TX 1 // already defined in zero core variant.h +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // SDA = 20, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) // SS = A2 +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +// Arduino Primo +#elif defined(ARDUINO_PRIMO) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 22 //14 digital + 6 analog + 2 i2c +#define VERSION_BLINK_PIN LED_BUILTIN +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < 20) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 20) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS+2) +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) // SDA = 20, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p)== MOSI || (p) == MISO || (p == SCK)) // 10, 11, 12, 13 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + +// Arduino 101 +#elif defined(_VARIANT_ARDUINO_101_X_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS // 15 digital (including ATN pin) + 6 analog +#define VERSION_BLINK_PIN LED_BUILTIN +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 20) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) // 3, 5, 6, 9 +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) // SDA = 18, SCL = 19 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Teensy 1.0 +#elif defined(__AVR_AT90USB162__) +#define TOTAL_ANALOG_PINS 0 +#define TOTAL_PINS 21 // 21 digital + no analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) (0) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) (0) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (0) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 2.0 +#elif defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 25 // 11 digital + 12 analog +#define VERSION_BLINK_PIN 11 +#define PIN_SERIAL1_RX 7 +#define PIN_SERIAL1_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 5 || (p) == 6) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 7 || (p) == 8) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) < 22) ? 21 - (p) : 11) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 3.5 and 3.6 +// reference: https://github.com/PaulStoffregen/cores/blob/master/teensy3/pins_arduino.h +#elif defined(__MK64FX512__) || defined(__MK66FX1M0__) +#define TOTAL_ANALOG_PINS 27 // 3.5 has 27 and 3.6 has 25 +#define TOTAL_PINS 70 // 43 digital + 21 analog-digital + 6 analog (64-69) +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define PIN_SERIAL4_RX 31 +#define PIN_SERIAL4_TX 32 +#define PIN_SERIAL5_RX 34 +#define PIN_SERIAL5_TX 33 +#define PIN_SERIAL6_RX 47 +#define PIN_SERIAL6_TX 48 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 63) +#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 31 && (p) <= 39) || ((p) >= 49 && (p) <= 50) || ((p) >= 64 && (p) <= 69)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1) || ((p) > 30 && (p) < 35) || ((p) == 47 || (p) == 48)) +#define PIN_TO_DIGITAL(p) (p) +// A0-A9 = D14-D23; A12-A20 = D31-D39; A23-A24 = D49-D50; A10-A11 = D64-D65; A21-A22 = D66-D67; A25-A26 = D68-D69 +#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (((p) <= 39) ? (p) - 19 : (((p) <= 50) ? (p) - 26 : (((p) <= 65) ? (p) - 55 : (((p) <= 67) ? (p) - 45 : (p) - 43))))) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 3.0, 3.1 and 3.2 +#elif defined(__MK20DX128__) || defined(__MK20DX256__) +#define TOTAL_ANALOG_PINS 14 +#define TOTAL_PINS 38 // 24 digital + 10 analog-digital + 4 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 33) +#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 34 && (p) <= 38)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy-LC +#elif defined(__MKL26Z64__) +#define TOTAL_ANALOG_PINS 13 +#define TOTAL_PINS 27 // 27 digital + 13 analog-digital +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 26) +#define IS_PIN_ANALOG(p) ((p) >= 14) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy++ 1.0 and 2.0 +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 46 // 38 digital + 8 analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 0 || (p) == 1) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 38) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + +// Teensy 4.0 and Teensy 4.1 +#elif defined(__IMXRT1062__) +#if !defined(TEENSY40) && !defined(TEENSY41) + #warning Assuming TEENSY40. Please #define TEENSY40 or TEENSY41. + #define TEENSY40 +#endif +#if defined(TEENSY40) + #define TOTAL_PINS 40 + #define TOTAL_ANALOG_PINS 14 + #define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 27) + #define PIN_TO_ANALOG(p) ((p) - 14) +#elif defined(TEENSY41) + #define TOTAL_PINS 55 + #define TOTAL_ANALOG_PINS 18 + #define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 27) || ((p) >= 38 && (p) <= 41)) + #define PIN_TO_ANALOG(p) (((p) <= 27) ? ((p) - 14 ) : ((p) - 24)) +#endif +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 7 +#define PIN_SERIAL2_TX 8 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define PIN_SERIAL4_RX 16 +#define PIN_SERIAL4_TX 17 +#define PIN_SERIAL5_RX 21 +#define PIN_SERIAL5_TX 20 +#define PIN_SERIAL6_RX 25 +#define PIN_SERIAL6_TX 24 +#define PIN_SERIAL7_RX 28 +#define PIN_SERIAL7_TX 29 +#if defined(TEENSY40) + #define IS_PIN_SERIAL(p) (((p) == PIN_SERIAL1_RX) || \ + ((p) == PIN_SERIAL1_TX) || \ + ((p) == PIN_SERIAL2_RX) || \ + ((p) == PIN_SERIAL2_TX) || \ + ((p) == PIN_SERIAL3_RX) || \ + ((p) == PIN_SERIAL3_TX) || \ + ((p) == PIN_SERIAL4_RX) || \ + ((p) == PIN_SERIAL4_TX) || \ + ((p) == PIN_SERIAL5_RX) || \ + ((p) == PIN_SERIAL5_TX) || \ + ((p) == PIN_SERIAL6_RX) || \ + ((p) == PIN_SERIAL6_TX) || \ + ((p) == PIN_SERIAL7_RX) || \ + ((p) == PIN_SERIAL7_TX)) + #define IS_PIN_PWM(p) (((p) >= 0 && (p) <= 16) || \ + ((p) == 18) || \ + ((p) == 19) || \ + ((p) >= 22 && (p) <= 25) || \ + ((p) == 28) || \ + ((p) == 29) || \ + ((p) >= 33 && (p) <= 39)) +#elif defined(TEENSY41) + #define PIN_SERIAL8_RX 34 + #define PIN_SERIAL8_TX 35 + #define IS_PIN_SERIAL(p) (((p) == PIN_SERIAL1_RX) || \ + ((p) == PIN_SERIAL1_TX) || \ + ((p) == PIN_SERIAL2_RX) || \ + ((p) == PIN_SERIAL2_TX) || \ + ((p) == PIN_SERIAL3_RX) || \ + ((p) == PIN_SERIAL3_TX) || \ + ((p) == PIN_SERIAL4_RX) || \ + ((p) == PIN_SERIAL4_TX) || \ + ((p) == PIN_SERIAL5_RX) || \ + ((p) == PIN_SERIAL5_TX) || \ + ((p) == PIN_SERIAL6_RX) || \ + ((p) == PIN_SERIAL6_TX) || \ + ((p) == PIN_SERIAL7_RX) || \ + ((p) == PIN_SERIAL7_TX) ||\ + ((p) == PIN_SERIAL8_RX) || \ + ((p) == PIN_SERIAL8_TX)) + #define IS_PIN_PWM(p) (((p) >= 0 && (p) <= 15) || \ + ((p) == 18) || \ + ((p) == 19) || \ + ((p) >= 22 && (p) <= 25) || \ + ((p) == 28) || \ + ((p) == 29) || \ + ((p) == 33) || \ + ((p) == 36) || \ + ((p) == 37) || \ + ((p) >= 42 && (p) <= 47) || \ + ((p) == 51) || \ + ((p) == 54)) +#endif +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Leonardo +#elif defined(__AVR_ATmega32U4__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 30 // 14 digital + 12 analog + 4 SPI (D14-D17 on ISP header) +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 18 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) - 18 +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Intel Galileo Board (gen 1 and 2) and Intel Edison +#elif defined(ARDUINO_LINUX) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// RedBearLab BLE Nano with factory switch settings (S1 - S10) +#elif defined(BLE_NANO) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 15 // 9 digital + 3 analog +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 14) +#define IS_PIN_ANALOG(p) ((p) == 8 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 12 || (p) == 14) //A0~A5 +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) <= 7) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == CS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 8) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Sanguino +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 32 // 24 digital + 8 analog +#define VERSION_BLINK_PIN 0 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + +// Sanguino/Melzi, e.g. Creality Ender-3 +#elif defined(__AVR_ATmega1284P__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 32 +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 8 //PD0 +#define PIN_SERIAL1_TX 9 //PD1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 4 || (p) == 6 || (p) == 7 || (p) == 12 || (p) == 13 || (p) == 14 || (p) == 15) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 8 || (p) == 9) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) - 24 +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Illuminato +#elif defined(__AVR_ATmega645__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 42 // 36 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 36) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Pic32 chipKIT FubarinoSD +#elif defined(_BOARD_FUBARINO_SD_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 15 +#define TOTAL_PINS NUM_DIGITAL_PINS // 45, All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) 1 +#define IS_PIN_ANALOG(p) ((p) >= 30 && (p) <= 44) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 1 || (p) == 2) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (14 - (p - 30)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT FubarinoMini +// Note, FubarinoMini analog pin 20 will not function in Firmata as analog input due to limitation in analog mapping +#elif defined(_BOARD_FUBARINO_MINI_) +#define TOTAL_ANALOG_PINS 14 // We have to fake this because of the poor analog pin mapping planning in FubarinoMini +#define TOTAL_PINS NUM_DIGITAL_PINS // 33 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) != 14 && (p) != 15 && (p) != 31 && (p) != 32) +#define IS_PIN_ANALOG(p) ((p) == 0 || ((p) >= 3 && (p) <= 13)) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 25 || (p) == 26) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT UNO32 +#elif defined(_BOARD_UNO_) && defined(__PIC32) // NOTE: no _BOARD_UNO32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT DP32 +#elif defined(_BOARD_DP32_) +#define TOTAL_ANALOG_PINS 15 // Really only has 9, but have to override because of mistake in variant file +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) != 1) && ((p) != 4) && ((p) != 5) && ((p) != 15) && ((p) != 16)) +#define IS_PIN_ANALOG(p) ((p) >= 6 && (p) <= 14) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT uC32 +#elif defined(_BOARD_UC32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WF32 +#elif defined(_BOARD_WF32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 49) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WiFire +#elif defined(_BOARD_WIFIRE_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 14 +#define TOTAL_PINS NUM_DIGITAL_PINS // 71 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 47) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 25 ? ((p) - 14) : (p) - 36) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT MAX32 +#elif defined(_BOARD_MEGA_) && defined(__PIC32) // NOTE: no _BOARD_MAX32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 87 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) <= 69) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT Pi +#elif defined(_BOARD_CHIPKIT_PI_) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 3) || (((p) >= 8) && ((p) <= 13)) || (((p) >= 14) && ((p) <= 17))) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 17) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 15 ? (p) - 14 : (p) - 12) +//#define PIN_TO_ANALOG(p) (((p) <= 16) ? ((p) - 14) : ((p) - 16)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + +// Pinoccio Scout +// Note: digital pins 9-16 are usable but not labeled on the board numerically. +// SS=9, MOSI=10, MISO=11, SCK=12, RX1=13, TX1=14, SCL=15, SDA=16 +#elif defined(ARDUINO_PINOCCIO) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS NUM_DIGITAL_PINS // 32 +#define VERSION_BLINK_PIN 23 +#define PIN_SERIAL1_RX 13 +#define PIN_SERIAL1_TX 14 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 16)) || (((p) >= 24) && ((p) <= 31)) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) <= 31) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == SCL || (p) == SDA) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 13 || (p) == 14) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + +// ESP8266 +// note: boot mode GPIOs 0, 2 and 15 can be used as outputs, GPIOs 6-11 are in use for flash IO +#elif defined(ESP8266) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS A0 + NUM_ANALOG_INPUTS +#define PIN_SERIAL_RX 3 +#define PIN_SERIAL_TX 1 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 5) || ((p) >= 12 && (p) < A0)) +#define IS_PIN_ANALOG(p) ((p) >= A0 && (p) < A0 + NUM_ANALOG_INPUTS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_INTERRUPT(p) (digitalPinToInterrupt(p) > NOT_AN_INTERRUPT) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL_RX || (p) == PIN_SERIAL_TX) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - A0) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) +#define DEFAULT_PWM_RESOLUTION 10 + +// STM32 based boards +#elif defined(ARDUINO_ARCH_STM32) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define TOTAL_PORTS MAX_NB_PORT +#ifdef LED_BUILTIN +#define VERSION_BLINK_PIN LED_BUILTIN +#endif +// PIN_SERIALY_RX/TX defined in the variant.h +#define IS_PIN_DIGITAL(p) (digitalPinIsValid(p) && !pinIsSerial(p)) +#if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x01080000) +#define IS_PIN_ANALOG(p) ((p >= A0) && (p < (A0 + TOTAL_ANALOG_PINS)) && !pinIsSerial(p)) +#else +#define IS_PIN_ANALOG(p) (pinIsAnalogInput(p) && !pinIsSerial(p)) +#endif +#define IS_PIN_PWM(p) (IS_PIN_DIGITAL(p) && digitalPinHasPWM(p)) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p)) +#define IS_PIN_I2C(p) (IS_PIN_DIGITAL(p) && digitalPinHasI2C(p)) +#define IS_PIN_SPI(p) (IS_PIN_DIGITAL(p) && digitalPinHasSPI(p)) +#define IS_PIN_INTERRUPT(p) (IS_PIN_DIGITAL(p) && (digitalPinToInterrupt(p) > NOT_AN_INTERRUPT))) +#define IS_PIN_SERIAL(p) (digitalPinHasSerial(p) && !pinIsSerial(p)) +#define PIN_TO_DIGITAL(p) (p) +#if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x01080000) +#define PIN_TO_ANALOG(p) (p-A0) +#else +#define PIN_TO_ANALOG(p) (digitalPinToAnalogInput(p)) +#endif +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) +#define DEFAULT_PWM_RESOLUTION PWM_RESOLUTION + +// Adafruit Bluefruit nRF52 boards +#elif defined(ARDUINO_NRF52_ADAFRUIT) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN LED_BUILTIN +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) == PIN_A0 || (p) == PIN_A1 || (p) == PIN_A2 || (p) == PIN_A3 || \ + (p) == PIN_A4 || (p) == PIN_A5 || (p) == PIN_A6 || (p) == PIN_A7) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == PIN_WIRE_SDA || (p) == PIN_WIRE_SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p)== MOSI || (p) == MISO || (p == SCK)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ( ((p) == PIN_A0) ? 0 : ((p) == PIN_A1) ? 1 : ((p) == PIN_A2) ? 2 : ((p) == PIN_A3) ? 3 : \ + ((p) == PIN_A4) ? 4 : ((p) == PIN_A5) ? 5 : ((p) == PIN_A6) ? 6 : ((p) == PIN_A7) ? 7 : (127)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + +// SPRESENSE +#elif defined(ARDUINO_ARCH_SPRESENSE) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS + 4 + NUM_ANALOG_INPUTS // + 4 built-in led +#define VERSION_BLINK_PIN LED_BUILTIN +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < (NUM_DIGITAL_PINS + 4)) +#define IS_PIN_ANALOG(p) ((p) >= (TOTAL_PINS - NUM_ANALOG_INPUTS) && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) ((p) == 6 || (p) == 5 || (p) == 9 || (p) == 3) +#define IS_PIN_SERVO(p) ((p) < NUM_DIGITAL_PINS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == 10 || (p) == 11 || (p) == 12 || (p) == 13) +#define PIN_TO_DIGITAL(p) (((p) < NUM_DIGITAL_PINS) ? (p) : (_LED_PIN((p) - NUM_DIGITAL_PINS))) +#define PIN_TO_ANALOG(p) ((p) - (TOTAL_PINS - NUM_ANALOG_INPUTS)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) +#define analogRead(p) analogRead(_ANALOG_PIN(p)) // wrap function for analogRead() + +// Robo HAT MM1 +#elif defined(ROBOTICSMASTERS_ROBOHATMM1_M4) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 46 // 14 digital + 7 analog + 4 i2c + 6 spi + 4 serial +#define TOTAL_PORTS 3 // set when TOTAL_PINS > num digitial I/O pins +#define VERSION_BLINK_PIN LED_BUILTIN +//#define PIN_SERIAL1_RX 0 // already defined in zero core variant.h +//#define PIN_SERIAL1_TX 1 // already defined in zero core variant.h +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 13) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 21 || (p) == 22) // SDA = 21, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) // SS = A2 +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + +//Arduino Uno Wifi Rev2 +#elif defined(__AVR_ATmega4809__) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS //6 +#define TOTAL_PINS 41 // 14 digital + 6 analog + 6 reserved + 10 internal used + 2 I2C + 3 SPI +#define TOTAL_PORTS 3 +#define VERSION_BLINK_PIN LED_BUILTIN //25 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 23 +#define PIN_SERIAL2_TX 24 +#define PIN_SERIAL0_RX 26 +#define PIN_SERIAL0_TX 27 +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) < 20) || (p) == 25) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 23 || (p) == 24 || (p) == 26 || (p) == 27) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// anything else +#else +#error "Please edit Boards.h with a hardware abstraction for this board" +#endif + +// as long this is not defined for all boards: +#ifndef IS_PIN_SPI +#define IS_PIN_SPI(p) 0 +#endif + +#ifndef IS_PIN_SERIAL +#define IS_PIN_SERIAL(p) 0 +#endif + +#ifndef DEFAULT_PWM_RESOLUTION +#define DEFAULT_PWM_RESOLUTION 8 +#endif + +/*============================================================================== + * readPort() - Read an 8 bit port + *============================================================================*/ + +static inline unsigned char readPort(byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char readPort(byte port, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) return (PIND & 0xFC) & bitmask; // ignore Rx/Tx 0/1 + if (port == 1) return ((PINB & 0x3F) | ((PINC & 0x03) << 6)) & bitmask; + if (port == 2) return ((PINC & 0x3C) >> 2) & bitmask; + return 0; +#else + unsigned char out = 0, pin = port * 8; + if (IS_PIN_DIGITAL(pin + 0) && (bitmask & 0x01) && digitalRead(PIN_TO_DIGITAL(pin + 0))) out |= 0x01; + if (IS_PIN_DIGITAL(pin + 1) && (bitmask & 0x02) && digitalRead(PIN_TO_DIGITAL(pin + 1))) out |= 0x02; + if (IS_PIN_DIGITAL(pin + 2) && (bitmask & 0x04) && digitalRead(PIN_TO_DIGITAL(pin + 2))) out |= 0x04; + if (IS_PIN_DIGITAL(pin + 3) && (bitmask & 0x08) && digitalRead(PIN_TO_DIGITAL(pin + 3))) out |= 0x08; + if (IS_PIN_DIGITAL(pin + 4) && (bitmask & 0x10) && digitalRead(PIN_TO_DIGITAL(pin + 4))) out |= 0x10; + if (IS_PIN_DIGITAL(pin + 5) && (bitmask & 0x20) && digitalRead(PIN_TO_DIGITAL(pin + 5))) out |= 0x20; + if (IS_PIN_DIGITAL(pin + 6) && (bitmask & 0x40) && digitalRead(PIN_TO_DIGITAL(pin + 6))) out |= 0x40; + if (IS_PIN_DIGITAL(pin + 7) && (bitmask & 0x80) && digitalRead(PIN_TO_DIGITAL(pin + 7))) out |= 0x80; + return out; +#endif +} + +/*============================================================================== + * writePort() - Write an 8 bit port, only touch pins specified by a bitmask + *============================================================================*/ + +static inline unsigned char writePort(byte, byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char writePort(byte port, byte value, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) { + bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins + byte valD = value & bitmask; + byte maskD = ~bitmask; + cli(); + PORTD = (PORTD & maskD) | valD; + sei(); + } else if (port == 1) { + byte valB = (value & bitmask) & 0x3F; + byte valC = (value & bitmask) >> 6; + byte maskB = ~(bitmask & 0x3F); + byte maskC = ~((bitmask & 0xC0) >> 6); + cli(); + PORTB = (PORTB & maskB) | valB; + PORTC = (PORTC & maskC) | valC; + sei(); + } else if (port == 2) { + bitmask = bitmask & 0x0F; + byte valC = (value & bitmask) << 2; + byte maskC = ~(bitmask << 2); + cli(); + PORTC = (PORTC & maskC) | valC; + sei(); + } + return 1; +#else + byte pin = port * 8; + if ((bitmask & 0x01)) digitalWrite(PIN_TO_DIGITAL(pin + 0), (value & 0x01)); + if ((bitmask & 0x02)) digitalWrite(PIN_TO_DIGITAL(pin + 1), (value & 0x02)); + if ((bitmask & 0x04)) digitalWrite(PIN_TO_DIGITAL(pin + 2), (value & 0x04)); + if ((bitmask & 0x08)) digitalWrite(PIN_TO_DIGITAL(pin + 3), (value & 0x08)); + if ((bitmask & 0x10)) digitalWrite(PIN_TO_DIGITAL(pin + 4), (value & 0x10)); + if ((bitmask & 0x20)) digitalWrite(PIN_TO_DIGITAL(pin + 5), (value & 0x20)); + if ((bitmask & 0x40)) digitalWrite(PIN_TO_DIGITAL(pin + 6), (value & 0x40)); + if ((bitmask & 0x80)) digitalWrite(PIN_TO_DIGITAL(pin + 7), (value & 0x80)); + return 1; +#endif +} + + + + +#ifndef TOTAL_PORTS +#define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) +#endif + + +#endif /* Firmata_Boards_h */ diff --git a/libs/Firmata/Firmata.cpp b/libs/Firmata/Firmata.cpp new file mode 100644 index 0000000..ee01f8f --- /dev/null +++ b/libs/Firmata/Firmata.cpp @@ -0,0 +1,554 @@ +/* + Firmata.cpp - Firmata library v2.5.8 - 2018-04-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "Firmata.h" +#include "HardwareSerial.h" + +#include +#include + +using namespace firmata; + +//****************************************************************************** +//* Static Members +//****************************************************************************** +// make one instance for the user to use +FirmataClass Firmata; + +/* callback functions */ +callbackFunction FirmataClass::currentAnalogCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentDigitalCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentPinModeCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentPinValueCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentReportAnalogCallback = (callbackFunction)NULL; +callbackFunction FirmataClass::currentReportDigitalCallback = (callbackFunction)NULL; +stringCallbackFunction FirmataClass::currentStringCallback = (stringCallbackFunction)NULL; +sysexCallbackFunction FirmataClass::currentSysexCallback = (sysexCallbackFunction)NULL; +systemCallbackFunction FirmataClass::currentSystemResetCallback = (systemCallbackFunction)NULL; + +//****************************************************************************** +//* Support Functions +//****************************************************************************** + +/** + * Split a 16-bit byte into two 7-bit values and write each value. + * @param value The 16-bit value to be split and written separately. + */ +void FirmataClass::sendValueAsTwo7bitBytes(int value) +{ + marshaller.encodeByteStream(sizeof(value), reinterpret_cast(&value), sizeof(value)); +} + +/** + * A helper method to write the beginning of a Sysex message transmission. + */ +void FirmataClass::startSysex(void) +{ + FirmataStream->write(START_SYSEX); +} + +/** + * A helper method to write the end of a Sysex message transmission. + */ +void FirmataClass::endSysex(void) +{ + FirmataStream->write(END_SYSEX); +} + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The Firmata class. + * An instance named "Firmata" is created automatically for the user. + */ +FirmataClass::FirmataClass() +: + parser(FirmataParser(parserBuffer, MAX_DATA_BYTES)) +{ + firmwareVersionCount = 0; + firmwareVersionVector = 0; + blinkVersionDisabled = false; + + // Establish callback translation to parser callbacks + parser.attach(ANALOG_MESSAGE, (FirmataParser::callbackFunction)staticAnalogCallback, (void *)NULL); + parser.attach(DIGITAL_MESSAGE, (FirmataParser::callbackFunction)staticDigitalCallback, (void *)NULL); + parser.attach(REPORT_ANALOG, (FirmataParser::callbackFunction)staticReportAnalogCallback, (void *)NULL); + parser.attach(REPORT_DIGITAL, (FirmataParser::callbackFunction)staticReportDigitalCallback, (void *)NULL); + parser.attach(SET_PIN_MODE, (FirmataParser::callbackFunction)staticPinModeCallback, (void *)NULL); + parser.attach(SET_DIGITAL_PIN_VALUE, (FirmataParser::callbackFunction)staticPinValueCallback, (void *)NULL); + parser.attach(STRING_DATA, (FirmataParser::stringCallbackFunction)staticStringCallback, (void *)NULL); + parser.attach(START_SYSEX, (FirmataParser::sysexCallbackFunction)staticSysexCallback, (void *)NULL); + parser.attach(REPORT_FIRMWARE, (FirmataParser::versionCallbackFunction)staticReportFirmwareCallback, this); + parser.attach(REPORT_VERSION, (FirmataParser::systemCallbackFunction)staticReportVersionCallback, this); + parser.attach(SYSTEM_RESET, (FirmataParser::systemCallbackFunction)staticSystemResetCallback, (void *)NULL); +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +/** + * Initialize the default Serial transport at the default baud of 57600. + */ +void FirmataClass::begin(void) +{ + begin(57600); +} + +/** + * Initialize the default Serial transport and override the default baud. + * Sends the protocol version to the host application followed by the firmware version and name. + * blinkVersion is also called. To skip the call to blinkVersion, call Firmata.disableBlinkVersion() + * before calling Firmata.begin(baud). + * @param speed The baud to use. 57600 baud is the default value. + */ +void FirmataClass::begin(long speed) +{ + Serial.begin(speed); + blinkVersion(); + begin(Serial); +} + +/** + * Reassign the Firmata stream transport. + * @param s A reference to the Stream transport object. This can be any type of + * transport that implements the Stream interface. Some examples include Ethernet, WiFi + * and other UARTs on the board (Serial1, Serial2, etc). + */ +void FirmataClass::begin(Stream &s) +{ + FirmataStream = &s; + marshaller.begin(s); + // do not call blinkVersion() here because some hardware such as the + // Ethernet shield use pin 13 + printVersion(); // send the protocol version + printFirmwareVersion(); // send the firmware name and version +} + +/** + * Send the Firmata protocol version to the Firmata host application. + */ +void FirmataClass::printVersion(void) +{ + marshaller.sendVersion(FIRMATA_PROTOCOL_MAJOR_VERSION, FIRMATA_PROTOCOL_MINOR_VERSION); +} + +/** + * Blink the Firmata protocol version to the onboard LEDs (if the board has an onboard LED). + * If VERSION_BLINK_PIN is not defined in Boards.h for a particular board, then this method + * does nothing. + * The first series of flashes indicates the firmware major version (2 flashes = 2). + * The second series of flashes indicates the firmware minor version (5 flashes = 5). + */ +void FirmataClass::blinkVersion(void) +{ +#if defined(VERSION_BLINK_PIN) + if (blinkVersionDisabled) return; + // flash the pin with the protocol version + pinMode(VERSION_BLINK_PIN, OUTPUT); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MAJOR_VERSION, 40, 210); + delay(250); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MINOR_VERSION, 40, 210); + delay(125); +#endif +} + +/** + * Provides a means to disable the version blink sequence on the onboard LED, trimming startup + * time by a couple of seconds. + * Call this before Firmata.begin(). It only applies when using the default Serial transport. + */ +void FirmataClass::disableBlinkVersion() +{ + blinkVersionDisabled = true; +} + +/** + * Sends the firmware name and version to the Firmata host application. The major and minor version + * numbers are the first 2 bytes in the message. The following bytes are the characters of the + * firmware name. + */ +void FirmataClass::printFirmwareVersion(void) +{ + if (firmwareVersionCount) { // make sure that the name has been set before reporting + marshaller.sendFirmwareVersion(static_cast(firmwareVersionVector[0]), static_cast(firmwareVersionVector[1]), (firmwareVersionCount - 2), reinterpret_cast(&firmwareVersionVector[2])); + } +} + +/** + * Sets the name and version of the firmware. This is not the same version as the Firmata protocol + * (although at times the firmware version and protocol version may be the same number). + * @param name A pointer to the name char array + * @param major The major version number + * @param minor The minor version number + */ +void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor) +{ + const char *firmwareName; + const char *extension; + + // parse out ".cpp" and "applet/" that comes from using __FILE__ + extension = strstr(name, ".cpp"); + firmwareName = strrchr(name, '/'); + + if (!firmwareName) { + // windows + firmwareName = strrchr(name, '\\'); + } + if (!firmwareName) { + // user passed firmware name + firmwareName = name; + } else { + firmwareName ++; + } + + if (!extension) { + firmwareVersionCount = strlen(firmwareName) + 2; + } else { + firmwareVersionCount = extension - firmwareName + 2; + } + + // in case anyone calls setFirmwareNameAndVersion more than once + free(firmwareVersionVector); + + firmwareVersionVector = (byte *) malloc(firmwareVersionCount + 1); + firmwareVersionVector[firmwareVersionCount] = 0; + firmwareVersionVector[0] = major; + firmwareVersionVector[1] = minor; + strncpy((char *)firmwareVersionVector + 2, firmwareName, firmwareVersionCount - 2); +} + +//------------------------------------------------------------------------------ +// Serial Receive Handling + +/** + * A wrapper for Stream::available() + * @return The number of bytes remaining in the input stream buffer. + */ +int FirmataClass::available(void) +{ + return FirmataStream->available(); +} + +/** + * Read a single int from the input stream. If the value is not = -1, pass it on to parse(byte) + */ +void FirmataClass::processInput(void) +{ + int inputData = FirmataStream->read(); // this is 'int' to handle -1 when no data + if (inputData != -1) { + parser.parse(inputData); + } +} + +/** + * Parse data from the input stream. + * @param inputData A single byte to be added to the parser. + */ +void FirmataClass::parse(byte inputData) +{ + parser.parse(inputData); +} + +/** + * @return Returns true if the parser is actively parsing data. + */ +boolean FirmataClass::isParsingMessage(void) +{ + return parser.isParsingMessage(); +} + +//------------------------------------------------------------------------------ +// Output Stream Handling + +/** + * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] + * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin to send the value of (limited to pins 0 - 15). + * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). + * The maximum value is 14-bits (16384). + */ +void FirmataClass::sendAnalog(byte pin, int value) +{ + marshaller.sendAnalog(pin, value); +} + +/* (intentionally left out asterix here) + * STUB - NOT IMPLEMENTED + * Send a single digital pin value to the Firmata host application. + * @param pin The digital pin to send the value of. + * @param value The value of the pin. + */ +void FirmataClass::sendDigital(byte pin, int value) +{ + (void)pin; + (void)value; + /* TODO add single pin digital messages to the protocol, this needs to + * track the last digital data sent so that it can be sure to change just + * one bit in the packet. This is complicated by the fact that the + * numbering of the pins will probably differ on Arduino, Wiring, and + * other boards. + */ + + // TODO: the digital message should not be sent on the serial port every + // time sendDigital() is called. Instead, it should add it to an int + // which will be sent on a schedule. If a pin changes more than once + // before the digital message is sent on the serial port, it should send a + // digital message for each change. + + // if(value == 0) + // sendDigitalPortPair(); +} + + +/** + * Send an 8-bit port in a single digital message (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number to send. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param portData The value of the port. The value of each pin in the port is represented by a bit. + */ +void FirmataClass::sendDigitalPort(byte portNumber, int portData) +{ + marshaller.sendDigitalPort(portNumber, portData); +} + +/** + * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes + * (this is not always the case so this function is not always used to send sysex messages). + * @param command The sysex command byte. + * @param bytec The number of data bytes in the message (excludes start, command and end bytes). + * @param bytev A pointer to the array of data bytes to send in the message. + */ +void FirmataClass::sendSysex(byte command, byte bytec, byte *bytev) +{ + marshaller.sendSysex(command, bytec, bytev); +} + +/** + * Send a string to the Firmata host application. + * @param command Must be STRING_DATA + * @param string A pointer to the char string + */ +void FirmataClass::sendString(byte command, const char *string) +{ + if (command == STRING_DATA) { + marshaller.sendString(string); + } +} + +/** + * Send a string to the Firmata host application. + * @param string A pointer to the char string + */ +void FirmataClass::sendString(const char *string) +{ + marshaller.sendString(string); +} + +/** + * A wrapper for Stream::available(). + * Write a single byte to the output stream. + * @param c The byte to be written. + */ +void FirmataClass::write(byte c) +{ + FirmataStream->write(c); +} + +/** + * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, + * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + */ +void FirmataClass::attach(uint8_t command, ::callbackFunction newFunction) +{ + switch (command) { + case ANALOG_MESSAGE: + currentAnalogCallback = newFunction; + break; + case DIGITAL_MESSAGE: + currentDigitalCallback = newFunction; + break; + case REPORT_ANALOG: + currentReportAnalogCallback = newFunction; + break; + case REPORT_DIGITAL: + currentReportDigitalCallback = newFunction; + break; + case SET_PIN_MODE: + currentPinModeCallback = newFunction; + break; + case SET_DIGITAL_PIN_VALUE: + currentPinValueCallback = newFunction; + break; + } +} + +/** + * Attach a callback function for the SYSTEM_RESET command. + * @param command Must be set to SYSTEM_RESET or it will be ignored. + * @param newFunction A reference to the system reset callback function to attach. + */ +void FirmataClass::attach(uint8_t command, systemCallbackFunction newFunction) +{ + switch (command) { + case SYSTEM_RESET: + currentSystemResetCallback = newFunction; + break; + } +} + +/** + * Attach a callback function for the STRING_DATA command. + * @param command Must be set to STRING_DATA or it will be ignored. + * @param newFunction A reference to the string callback function to attach. + */ +void FirmataClass::attach(uint8_t command, stringCallbackFunction newFunction) +{ + switch (command) { + case STRING_DATA: + currentStringCallback = newFunction; + break; + } +} + +/** + * Attach a generic sysex callback function to sysex command. + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the sysex callback function to attach. + */ +void FirmataClass::attach(uint8_t command, sysexCallbackFunction newFunction) +{ + (void)command; + currentSysexCallback = newFunction; +} + +/** + * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, + * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). + * @param command The ID of the command to detatch the callback function from. + */ +void FirmataClass::detach(uint8_t command) +{ + switch (command) { + case SYSTEM_RESET: + attach(command, (systemCallbackFunction)NULL); + break; + case STRING_DATA: + attach(command, (stringCallbackFunction)NULL); + break; + case START_SYSEX: + attach(command, (sysexCallbackFunction)NULL); + break; + default: + attach(command, (callbackFunction)NULL); + break; + } +} + +/** + * @param pin The pin to get the configuration of. + * @return The configuration of the specified pin. + */ +byte FirmataClass::getPinMode(byte pin) +{ + return pinConfig[pin]; +} + +/** + * Set the pin mode/configuration. The pin configuration (or mode) in Firmata represents the + * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, + * serial (uart), etc. + * @param pin The pin to configure. + * @param config The configuration value for the specified pin. + */ +void FirmataClass::setPinMode(byte pin, byte config) +{ + if (pinConfig[pin] == PIN_MODE_IGNORE) + return; + + pinConfig[pin] = config; +} + +/** + * @param pin The pin to get the state of. + * @return The state of the specified pin. + */ +int FirmataClass::getPinState(byte pin) +{ + return pinState[pin]; +} + +/** + * Set the pin state. The pin state of an output pin is the pin value. The state of an + * input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1. + * @param pin The pin to set the state of + * @param state Set the state of the specified pin + */ +void FirmataClass::setPinState(byte pin, int state) +{ + pinState[pin] = state; +} + +// sysex callbacks +/* + * this is too complicated for analogReceive, but maybe for Sysex? + void FirmataClass::attachSysex(sysexFunction newFunction) + { + byte i; + byte tmpCount = analogReceiveFunctionCount; + analogReceiveFunction* tmpArray = analogReceiveFunctionArray; + analogReceiveFunctionCount++; + analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction)); + for(i = 0; i < tmpCount; i++) { + analogReceiveFunctionArray[i] = tmpArray[i]; + } + analogReceiveFunctionArray[tmpCount] = newFunction; + free(tmpArray); + } +*/ + +//****************************************************************************** +//* Private Methods +//****************************************************************************** + +/** + * Flashing the pin for the version number + * @private + * @param pin The pin the LED is attached to. + * @param count The number of times to flash the LED. + * @param onInterval The number of milliseconds for the LED to be ON during each interval. + * @param offInterval The number of milliseconds for the LED to be OFF during each interval. + */ +void FirmataClass::strobeBlinkPin(byte pin, int count, int onInterval, int offInterval) +{ + byte i; + for (i = 0; i < count; i++) { + delay(offInterval); + digitalWrite(pin, HIGH); + delay(onInterval); + digitalWrite(pin, LOW); + } +} + diff --git a/libs/Firmata/Firmata.h b/libs/Firmata/Firmata.h new file mode 100644 index 0000000..fb993d7 --- /dev/null +++ b/libs/Firmata/Firmata.h @@ -0,0 +1,180 @@ +/* + Firmata.h - Firmata library v2.5.8 - 2018-04-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef Firmata_h +#define Firmata_h + +#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ +#include "FirmataDefines.h" +#include "FirmataMarshaller.h" +#include "FirmataParser.h" + +/* DEPRECATED as of Firmata v2.5.1. As of 2.5.1 there are separate version numbers for + * the protocol version and the firmware version. + */ +#define FIRMATA_MAJOR_VERSION 2 // same as FIRMATA_PROTOCOL_MAJOR_VERSION +#define FIRMATA_MINOR_VERSION 5 // same as FIRMATA_PROTOCOL_MINOR_VERSION +#define FIRMATA_BUGFIX_VERSION 1 // same as FIRMATA_PROTOCOL_BUGFIX_VERSION + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ +// these are DEPRECATED to make the naming more consistent +#define FIRMATA_STRING 0x71 // same as STRING_DATA +#define SYSEX_I2C_REQUEST 0x76 // same as I2C_REQUEST +#define SYSEX_I2C_REPLY 0x77 // same as I2C_REPLY +#define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL + +// pin modes +//#define INPUT 0x00 // defined in Arduino.h +//#define OUTPUT 0x01 // defined in Arduino.h +// DEPRECATED as of Firmata v2.5 +#define ANALOG 0x02 // same as PIN_MODE_ANALOG +#define PWM 0x03 // same as PIN_MODE_PWM +#define SERVO 0x04 // same as PIN_MODE_SERVO +#define SHIFT 0x05 // same as PIN_MODE_SHIFT +#define I2C 0x06 // same as PIN_MODE_I2C +#define ONEWIRE 0x07 // same as PIN_MODE_ONEWIRE +#define STEPPER 0x08 // same as PIN_MODE_STEPPER +#define ENCODER 0x09 // same as PIN_MODE_ENCODER +#define IGNORE 0x7F // same as PIN_MODE_IGNORE + +namespace firmata { + +// TODO make it a subclass of a generic Serial/Stream base class +class FirmataClass +{ + public: + typedef void (*callbackFunction)(uint8_t, int); + typedef void (*systemCallbackFunction)(void); + typedef void (*stringCallbackFunction)(char *); + typedef void (*sysexCallbackFunction)(uint8_t command, uint8_t argc, uint8_t *argv); + + FirmataClass(); + + /* Arduino constructors */ + void begin(); + void begin(long); + void begin(Stream &s); + + /* querying functions */ + void printVersion(void); + void blinkVersion(void); + void printFirmwareVersion(void); + + //void setFirmwareVersion(byte major, byte minor); // see macro below + void setFirmwareNameAndVersion(const char *name, byte major, byte minor); + void disableBlinkVersion(); + + /* serial receive handling */ + int available(void); + void processInput(void); + void parse(unsigned char value); + boolean isParsingMessage(void); + + /* serial send handling */ + void sendAnalog(byte pin, int value); + void sendDigital(byte pin, int value); // TODO implement this + void sendDigitalPort(byte portNumber, int portData); + void sendString(const char *string); + void sendString(byte command, const char *string); + void sendSysex(byte command, byte bytec, byte *bytev); + void write(byte c); + + /* attach & detach callback functions to messages */ + void attach(uint8_t command, callbackFunction newFunction); + void attach(uint8_t command, systemCallbackFunction newFunction); + void attach(uint8_t command, stringCallbackFunction newFunction); + void attach(uint8_t command, sysexCallbackFunction newFunction); + void detach(uint8_t command); + + /* access pin state and config */ + byte getPinMode(byte pin); + void setPinMode(byte pin, byte config); + + /* access pin state */ + int getPinState(byte pin); + void setPinState(byte pin, int state); + + /* utility methods */ + void sendValueAsTwo7bitBytes(int value); + void startSysex(void); + void endSysex(void); + + private: + uint8_t parserBuffer[MAX_DATA_BYTES]; + FirmataMarshaller marshaller; + FirmataParser parser; + Stream *FirmataStream; + + /* firmware name and version */ + byte firmwareVersionCount; + byte *firmwareVersionVector; + + /* pin configuration */ + byte pinConfig[TOTAL_PINS]; + int pinState[TOTAL_PINS]; + + boolean blinkVersionDisabled; + + /* private methods ------------------------------ */ + void strobeBlinkPin(byte pin, int count, int onInterval, int offInterval); + friend void FirmataMarshaller::encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes) const; + + /* callback functions */ + static callbackFunction currentAnalogCallback; + static callbackFunction currentDigitalCallback; + static callbackFunction currentPinModeCallback; + static callbackFunction currentPinValueCallback; + static callbackFunction currentReportAnalogCallback; + static callbackFunction currentReportDigitalCallback; + static stringCallbackFunction currentStringCallback; + static sysexCallbackFunction currentSysexCallback; + static systemCallbackFunction currentSystemResetCallback; + + /* static callbacks */ + inline static void staticAnalogCallback (void *, uint8_t command, uint16_t value) { if ( currentAnalogCallback ) { currentAnalogCallback(command,(int)value); } } + inline static void staticDigitalCallback (void *, uint8_t command, uint16_t value) { if ( currentDigitalCallback ) { currentDigitalCallback(command, (int)value); } } + inline static void staticPinModeCallback (void *, uint8_t command, uint16_t value) { if ( currentPinModeCallback ) { currentPinModeCallback(command, (int)value); } } + inline static void staticPinValueCallback (void *, uint8_t command, uint16_t value) { if ( currentPinValueCallback ) { currentPinValueCallback(command, (int)value); } } + inline static void staticReportAnalogCallback (void *, uint8_t command, uint16_t value) { if ( currentReportAnalogCallback ) { currentReportAnalogCallback(command, (int)value); } } + inline static void staticReportDigitalCallback (void *, uint8_t command, uint16_t value) { if ( currentReportDigitalCallback ) { currentReportDigitalCallback(command, (int)value); } } + inline static void staticStringCallback (void *, const char * c_str) { if ( currentStringCallback ) { currentStringCallback((char *)c_str); } } + inline static void staticSysexCallback (void *, uint8_t command, size_t argc, uint8_t *argv) { if ( currentSysexCallback ) { currentSysexCallback(command, (uint8_t)argc, argv); } } + inline static void staticReportFirmwareCallback (void * context, size_t, size_t, const char *) { if ( context ) { ((FirmataClass *)context)->printFirmwareVersion(); } } + inline static void staticReportVersionCallback (void * context) { if ( context ) { ((FirmataClass *)context)->printVersion(); } } + inline static void staticSystemResetCallback (void *) { if ( currentSystemResetCallback ) { currentSystemResetCallback(); } } +}; + +} // namespace firmata + +extern "C" { + // callback function types + typedef firmata::FirmataClass::callbackFunction callbackFunction; + typedef firmata::FirmataClass::systemCallbackFunction systemCallbackFunction; + typedef firmata::FirmataClass::stringCallbackFunction stringCallbackFunction; + typedef firmata::FirmataClass::sysexCallbackFunction sysexCallbackFunction; +} + +extern firmata::FirmataClass Firmata; + +/*============================================================================== + * MACROS + *============================================================================*/ + +/* shortcut for setFirmwareNameAndVersion() that uses __FILE__ to set the + * firmware name. It needs to be a macro so that __FILE__ is included in the + * firmware source file rather than the library source file. + */ +#define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) + +#endif /* Firmata_h */ diff --git a/libs/Firmata/FirmataConstants.h b/libs/Firmata/FirmataConstants.h new file mode 100644 index 0000000..dee8407 --- /dev/null +++ b/libs/Firmata/FirmataConstants.h @@ -0,0 +1,97 @@ +/* + FirmataConstants.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2017 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataConstants_h +#define FirmataConstants_h + +namespace firmata { +/* Version numbers for the Firmata library. + * The firmware version will not always equal the protocol version going forward. + * Query using the REPORT_FIRMWARE message. + */ +static const int FIRMWARE_MAJOR_VERSION = 2; +static const int FIRMWARE_MINOR_VERSION = 5; +static const int FIRMWARE_BUGFIX_VERSION = 7; + +/* Version numbers for the protocol. The protocol is still changing, so these + * version numbers are important. + * Query using the REPORT_VERSION message. + */ +static const int PROTOCOL_MAJOR_VERSION = 2; // for non-compatible changes +static const int PROTOCOL_MINOR_VERSION = 5; // for backwards compatible changes +static const int PROTOCOL_BUGFIX_VERSION = 1; // for bugfix releases + +static const int MAX_DATA_BYTES = 64; // max number of data bytes in incoming messages + +// message command bytes (128-255/0x80-0xFF) + +static const int DIGITAL_MESSAGE = 0x90; // send data for a digital port (collection of 8 pins) +static const int ANALOG_MESSAGE = 0xE0; // send data for an analog pin (or PWM) +static const int REPORT_ANALOG = 0xC0; // enable analog input by pin # +static const int REPORT_DIGITAL = 0xD0; // enable digital input by port pair +// +static const int SET_PIN_MODE = 0xF4; // set a pin to INPUT/OUTPUT/PWM/etc +static const int SET_DIGITAL_PIN_VALUE = 0xF5; // set value of an individual digital pin +// +static const int REPORT_VERSION = 0xF9; // report protocol version +static const int SYSTEM_RESET = 0xFF; // reset from MIDI +// +static const int START_SYSEX = 0xF0; // start a MIDI Sysex message +static const int END_SYSEX = 0xF7; // end a MIDI Sysex message + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ + +static const int SERIAL_DATA = 0x60; // communicate with serial devices, including other boards +static const int ENCODER_DATA = 0x61; // reply with encoders current positions +static const int SERVO_CONFIG = 0x70; // set max angle, minPulse, maxPulse, freq +static const int STRING_DATA = 0x71; // a string message with 14-bits per char +static const int STEPPER_DATA = 0x72; // control a stepper motor +static const int ONEWIRE_DATA = 0x73; // send an OneWire read/write/reset/select/skip/search request +static const int SHIFT_DATA = 0x75; // a bitstream to/from a shift register +static const int I2C_REQUEST = 0x76; // send an I2C read/write request +static const int I2C_REPLY = 0x77; // a reply to an I2C read request +static const int I2C_CONFIG = 0x78; // config I2C settings such as delay times and power pins +static const int REPORT_FIRMWARE = 0x79; // report name and version of the firmware +static const int EXTENDED_ANALOG = 0x6F; // analog write (PWM, Servo, etc) to any pin +static const int PIN_STATE_QUERY = 0x6D; // ask for a pin's current mode and value +static const int PIN_STATE_RESPONSE = 0x6E; // reply with pin's current mode and value +static const int CAPABILITY_QUERY = 0x6B; // ask for supported modes and resolution of all pins +static const int CAPABILITY_RESPONSE = 0x6C; // reply with supported modes and resolution +static const int ANALOG_MAPPING_QUERY = 0x69; // ask for mapping of analog to pin numbers +static const int ANALOG_MAPPING_RESPONSE = 0x6A; // reply with mapping info +static const int SAMPLING_INTERVAL = 0x7A; // set the poll rate of the main loop +static const int SCHEDULER_DATA = 0x7B; // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler +static const int SYSEX_NON_REALTIME = 0x7E; // MIDI Reserved for non-realtime messages +static const int SYSEX_REALTIME = 0x7F; // MIDI Reserved for realtime messages + +// pin modes +static const int PIN_MODE_INPUT = 0x00; // same as INPUT defined in Arduino.h +static const int PIN_MODE_OUTPUT = 0x01; // same as OUTPUT defined in Arduino.h +static const int PIN_MODE_ANALOG = 0x02; // analog pin in analogInput mode +static const int PIN_MODE_PWM = 0x03; // digital pin in PWM output mode +static const int PIN_MODE_SERVO = 0x04; // digital pin in Servo output mode +static const int PIN_MODE_SHIFT = 0x05; // shiftIn/shiftOut mode +static const int PIN_MODE_I2C = 0x06; // pin included in I2C setup +static const int PIN_MODE_ONEWIRE = 0x07; // pin configured for 1-wire +static const int PIN_MODE_STEPPER = 0x08; // pin configured for stepper motor +static const int PIN_MODE_ENCODER = 0x09; // pin configured for rotary encoders +static const int PIN_MODE_SERIAL = 0x0A; // pin configured for serial communication +static const int PIN_MODE_PULLUP = 0x0B; // enable internal pull-up resistor for pin +static const int PIN_MODE_IGNORE = 0x7F; // pin configured to be ignored by digitalWrite and capabilityResponse + +static const int TOTAL_PIN_MODES = 13; + +} // namespace firmata + +#endif // FirmataConstants_h diff --git a/libs/Firmata/FirmataDefines.h b/libs/Firmata/FirmataDefines.h new file mode 100644 index 0000000..fb95fb5 --- /dev/null +++ b/libs/Firmata/FirmataDefines.h @@ -0,0 +1,283 @@ +/* + FirmataDefines.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataDefines_h +#define FirmataDefines_h + +#include "FirmataConstants.h" + +/* Version numbers for the Firmata library. + * The firmware version will not always equal the protocol version going forward. + * Query using the REPORT_FIRMWARE message. + */ +#define FIRMATA_FIRMWARE_MAJOR_VERSION firmata::FIRMWARE_MAJOR_VERSION +#define FIRMATA_FIRMWARE_MINOR_VERSION firmata::FIRMWARE_MINOR_VERSION +#define FIRMATA_FIRMWARE_BUGFIX_VERSION firmata::FIRMWARE_BUGFIX_VERSION + +/* Version numbers for the protocol. The protocol is still changing, so these + * version numbers are important. + * Query using the REPORT_VERSION message. + */ +#define FIRMATA_PROTOCOL_MAJOR_VERSION firmata::PROTOCOL_MAJOR_VERSION // for non-compatible changes +#define FIRMATA_PROTOCOL_MINOR_VERSION firmata::PROTOCOL_MINOR_VERSION // for backwards compatible changes +#define FIRMATA_PROTOCOL_BUGFIX_VERSION firmata::PROTOCOL_BUGFIX_VERSION // for bugfix releases + +#ifdef MAX_DATA_BYTES +#undef MAX_DATA_BYTES +#endif +#define MAX_DATA_BYTES firmata::MAX_DATA_BYTES // max number of data bytes in incoming messages + +// message command bytes (128-255/0x80-0xFF) + +#ifdef DIGITAL_MESSAGE +#undef DIGITAL_MESSAGE +#endif +#define DIGITAL_MESSAGE firmata::DIGITAL_MESSAGE // send data for a digital port (collection of 8 pins) + +#ifdef ANALOG_MESSAGE +#undef ANALOG_MESSAGE +#endif +#define ANALOG_MESSAGE firmata::ANALOG_MESSAGE // send data for an analog pin (or PWM) + +#ifdef REPORT_ANALOG +#undef REPORT_ANALOG +#endif +#define REPORT_ANALOG firmata::REPORT_ANALOG // enable analog input by pin # + +#ifdef REPORT_DIGITAL +#undef REPORT_DIGITAL +#endif +#define REPORT_DIGITAL firmata::REPORT_DIGITAL // enable digital input by port pair + +// + +#ifdef SET_PIN_MODE +#undef SET_PIN_MODE +#endif +#define SET_PIN_MODE firmata::SET_PIN_MODE // set a pin to INPUT/OUTPUT/PWM/etc + +#ifdef SET_DIGITAL_PIN_VALUE +#undef SET_DIGITAL_PIN_VALUE +#endif +#define SET_DIGITAL_PIN_VALUE firmata::SET_DIGITAL_PIN_VALUE // set value of an individual digital pin + +// + +#ifdef REPORT_VERSION +#undef REPORT_VERSION +#endif +#define REPORT_VERSION firmata::REPORT_VERSION // report protocol version + +#ifdef SYSTEM_RESET +#undef SYSTEM_RESET +#endif +#define SYSTEM_RESET firmata::SYSTEM_RESET // reset from MIDI + +// + +#ifdef START_SYSEX +#undef START_SYSEX +#endif +#define START_SYSEX firmata::START_SYSEX // start a MIDI Sysex message + +#ifdef END_SYSEX +#undef END_SYSEX +#endif +#define END_SYSEX firmata::END_SYSEX // end a MIDI Sysex message + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ + +#ifdef SERIAL_MESSAGE +#undef SERIAL_MESSAGE +#endif +#define SERIAL_MESSAGE firmata::SERIAL_DATA // communicate with serial devices, including other boards + +#ifdef ENCODER_DATA +#undef ENCODER_DATA +#endif +#define ENCODER_DATA firmata::ENCODER_DATA // reply with encoders current positions + +#ifdef SERVO_CONFIG +#undef SERVO_CONFIG +#endif +#define SERVO_CONFIG firmata::SERVO_CONFIG // set max angle, minPulse, maxPulse, freq + +#ifdef STRING_DATA +#undef STRING_DATA +#endif +#define STRING_DATA firmata::STRING_DATA // a string message with 14-bits per char + +#ifdef STEPPER_DATA +#undef STEPPER_DATA +#endif +#define STEPPER_DATA firmata::STEPPER_DATA // control a stepper motor + +#ifdef ONEWIRE_DATA +#undef ONEWIRE_DATA +#endif +#define ONEWIRE_DATA firmata::ONEWIRE_DATA // send an OneWire read/write/reset/select/skip/search request + +#ifdef SHIFT_DATA +#undef SHIFT_DATA +#endif +#define SHIFT_DATA firmata::SHIFT_DATA // a bitstream to/from a shift register + +#ifdef I2C_REQUEST +#undef I2C_REQUEST +#endif +#define I2C_REQUEST firmata::I2C_REQUEST // send an I2C read/write request + +#ifdef I2C_REPLY +#undef I2C_REPLY +#endif +#define I2C_REPLY firmata::I2C_REPLY // a reply to an I2C read request + +#ifdef I2C_CONFIG +#undef I2C_CONFIG +#endif +#define I2C_CONFIG firmata::I2C_CONFIG // config I2C settings such as delay times and power pins + +#ifdef REPORT_FIRMWARE +#undef REPORT_FIRMWARE +#endif +#define REPORT_FIRMWARE firmata::REPORT_FIRMWARE // report name and version of the firmware + +#ifdef EXTENDED_ANALOG +#undef EXTENDED_ANALOG +#endif +#define EXTENDED_ANALOG firmata::EXTENDED_ANALOG // analog write (PWM, Servo, etc) to any pin + +#ifdef PIN_STATE_QUERY +#undef PIN_STATE_QUERY +#endif +#define PIN_STATE_QUERY firmata::PIN_STATE_QUERY // ask for a pin's current mode and value + +#ifdef PIN_STATE_RESPONSE +#undef PIN_STATE_RESPONSE +#endif +#define PIN_STATE_RESPONSE firmata::PIN_STATE_RESPONSE // reply with pin's current mode and value + +#ifdef CAPABILITY_QUERY +#undef CAPABILITY_QUERY +#endif +#define CAPABILITY_QUERY firmata::CAPABILITY_QUERY // ask for supported modes and resolution of all pins + +#ifdef CAPABILITY_RESPONSE +#undef CAPABILITY_RESPONSE +#endif +#define CAPABILITY_RESPONSE firmata::CAPABILITY_RESPONSE // reply with supported modes and resolution + +#ifdef ANALOG_MAPPING_QUERY +#undef ANALOG_MAPPING_QUERY +#endif +#define ANALOG_MAPPING_QUERY firmata::ANALOG_MAPPING_QUERY // ask for mapping of analog to pin numbers + +#ifdef ANALOG_MAPPING_RESPONSE +#undef ANALOG_MAPPING_RESPONSE +#endif +#define ANALOG_MAPPING_RESPONSE firmata::ANALOG_MAPPING_RESPONSE // reply with mapping info + +#ifdef SAMPLING_INTERVAL +#undef SAMPLING_INTERVAL +#endif +#define SAMPLING_INTERVAL firmata::SAMPLING_INTERVAL // set the poll rate of the main loop + +#ifdef SCHEDULER_DATA +#undef SCHEDULER_DATA +#endif +#define SCHEDULER_DATA firmata::SCHEDULER_DATA // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler + +#ifdef SYSEX_NON_REALTIME +#undef SYSEX_NON_REALTIME +#endif +#define SYSEX_NON_REALTIME firmata::SYSEX_NON_REALTIME // MIDI Reserved for non-realtime messages + +#ifdef SYSEX_REALTIME +#undef SYSEX_REALTIME +#endif +#define SYSEX_REALTIME firmata::SYSEX_REALTIME // MIDI Reserved for realtime messages + +// pin modes + +#ifdef PIN_MODE_INPUT +#undef PIN_MODE_INPUT +#endif +#define PIN_MODE_INPUT firmata::PIN_MODE_INPUT // same as INPUT defined in Arduino.h + +#ifdef PIN_MODE_OUTPUT +#undef PIN_MODE_OUTPUT +#endif +#define PIN_MODE_OUTPUT firmata::PIN_MODE_OUTPUT // same as OUTPUT defined in Arduino.h + +#ifdef PIN_MODE_ANALOG +#undef PIN_MODE_ANALOG +#endif +#define PIN_MODE_ANALOG firmata::PIN_MODE_ANALOG // analog pin in analogInput mode + +#ifdef PIN_MODE_PWM +#undef PIN_MODE_PWM +#endif +#define PIN_MODE_PWM firmata::PIN_MODE_PWM // digital pin in PWM output mode + +#ifdef PIN_MODE_SERVO +#undef PIN_MODE_SERVO +#endif +#define PIN_MODE_SERVO firmata::PIN_MODE_SERVO // digital pin in Servo output mode + +#ifdef PIN_MODE_SHIFT +#undef PIN_MODE_SHIFT +#endif +#define PIN_MODE_SHIFT firmata::PIN_MODE_SHIFT // shiftIn/shiftOut mode + +#ifdef PIN_MODE_I2C +#undef PIN_MODE_I2C +#endif +#define PIN_MODE_I2C firmata::PIN_MODE_I2C // pin included in I2C setup + +#ifdef PIN_MODE_ONEWIRE +#undef PIN_MODE_ONEWIRE +#endif +#define PIN_MODE_ONEWIRE firmata::PIN_MODE_ONEWIRE // pin configured for 1-wire + +#ifdef PIN_MODE_STEPPER +#undef PIN_MODE_STEPPER +#endif +#define PIN_MODE_STEPPER firmata::PIN_MODE_STEPPER // pin configured for stepper motor + +#ifdef PIN_MODE_ENCODER +#undef PIN_MODE_ENCODER +#endif +#define PIN_MODE_ENCODER firmata::PIN_MODE_ENCODER // pin configured for rotary encoders + +#ifdef PIN_MODE_SERIAL +#undef PIN_MODE_SERIAL +#endif +#define PIN_MODE_SERIAL firmata::PIN_MODE_SERIAL // pin configured for serial communication + +#ifdef PIN_MODE_PULLUP +#undef PIN_MODE_PULLUP +#endif +#define PIN_MODE_PULLUP firmata::PIN_MODE_PULLUP // enable internal pull-up resistor for pin + +#ifdef PIN_MODE_IGNORE +#undef PIN_MODE_IGNORE +#endif +#define PIN_MODE_IGNORE firmata::PIN_MODE_IGNORE // pin configured to be ignored by digitalWrite and capabilityResponse + +#ifdef TOTAL_PIN_MODES +#undef TOTAL_PIN_MODES +#endif +#define TOTAL_PIN_MODES firmata::TOTAL_PIN_MODES + +#endif // FirmataConstants_h diff --git a/libs/Firmata/FirmataMarshaller.cpp b/libs/Firmata/FirmataMarshaller.cpp new file mode 100644 index 0000000..6cb5200 --- /dev/null +++ b/libs/Firmata/FirmataMarshaller.cpp @@ -0,0 +1,431 @@ +/* + FirmataMarshaller.cpp + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "FirmataMarshaller.h" + +#if defined(__cplusplus) && !defined(ARDUINO) + #include +#else + #include +#endif + +#include "FirmataConstants.h" + +using namespace firmata; + +//****************************************************************************** +//* Support Functions +//****************************************************************************** + +/** + * Request or halt a stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream + * @note The maximum resulting value is 14-bits (16384). + */ +void FirmataMarshaller::reportAnalog(uint8_t pin, bool stream_enable) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + // pin can only be 0-15, so chop higher bits + FirmataStream->write(REPORT_ANALOG | (pin & 0xF)); + FirmataStream->write(stream_enable); +} + +/** + * Request or halt an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param stream_enable A zero value will disable the stream, a non-zero will enable the stream + */ +void FirmataMarshaller::reportDigitalPort(uint8_t portNumber, bool stream_enable) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_DIGITAL | (portNumber & 0xF)); + FirmataStream->write(stream_enable); +} + +/** + * An alternative to the normal analog message, this extended version allows addressing beyond + * pin 15 and supports sending analog values with any number of bits. + * @param pin The analog pin to which the value is sent. + * @param bytec The size of the storage for the analog value + * @param bytev The pointer to the location of the analog value + */ +void FirmataMarshaller::sendExtendedAnalog(uint8_t pin, size_t bytec, uint8_t * bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(EXTENDED_ANALOG); + FirmataStream->write(pin); + encodeByteStream(bytec, bytev, bytec); + FirmataStream->write(END_SYSEX); +} + +/** + * Transform 8-bit stream into 7-bit message + * @param bytec The number of data bytes in the message. + * @param bytev A pointer to the array of data bytes to send in the message. + * @param max_bytes Force message to be n bytes, regardless of data bits. + */ +void FirmataMarshaller::encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes) +const +{ + static const size_t transmit_bits = 7; + static const uint8_t transmit_mask = ((1 << transmit_bits) - 1); + + size_t bytes_sent = 0; + size_t outstanding_bits = 0; + uint8_t outstanding_bit_cache = *bytev; + + if ( !max_bytes ) { max_bytes = static_cast(-1); } + for (size_t i = 0 ; (i < bytec) && (bytes_sent < max_bytes) ; ++i) { + uint8_t transmit_byte = (outstanding_bit_cache|(bytev[i] << outstanding_bits)); + FirmataStream->write(transmit_mask & transmit_byte); + ++bytes_sent; + outstanding_bit_cache = (bytev[i] >> (transmit_bits - outstanding_bits)); + outstanding_bits = (outstanding_bits + (8 - transmit_bits)); + for ( ; (outstanding_bits >= transmit_bits) && (bytes_sent < max_bytes) ; ) { + transmit_byte = outstanding_bit_cache; + FirmataStream->write(transmit_mask & transmit_byte); + ++bytes_sent; + outstanding_bit_cache >>= transmit_bits; + outstanding_bits -= transmit_bits; + } + } + if ( outstanding_bits && (bytes_sent < max_bytes) ) { + FirmataStream->write(static_cast((1 << outstanding_bits) - 1) & outstanding_bit_cache); + } +} + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The FirmataMarshaller class. + */ +FirmataMarshaller::FirmataMarshaller() +: + FirmataStream((Stream *)NULL) +{ +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +/** + * Reassign the Firmata stream transport. + * @param s A reference to the Stream transport object. This can be any type of + * transport that implements the Stream interface. Some examples include Ethernet, WiFi + * and other UARTs on the board (Serial1, Serial2, etc). + */ +void FirmataMarshaller::begin(Stream &s) +{ + FirmataStream = &s; +} + +/** + * Closes the FirmataMarshaller stream by setting its stream reference to `(Stream *)NULL` + */ +void FirmataMarshaller::end(void) +{ + FirmataStream = (Stream *)NULL; +} + +//****************************************************************************** +//* Output Stream Handling +//****************************************************************************** + +/** + * Query the target's firmware name and version + */ +void FirmataMarshaller::queryFirmwareVersion(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(REPORT_FIRMWARE); + FirmataStream->write(END_SYSEX); +} + +/** + * Query the target's Firmata protocol version + */ +void FirmataMarshaller::queryVersion(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_VERSION); +} + +/** + * Halt the stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + */ +void FirmataMarshaller::reportAnalogDisable(uint8_t pin) +const +{ + reportAnalog(pin, false); +} + +/** + * Request a stream of analog readings from the Firmata host application. The range of pins is + * limited to [0..15] when using the REPORT_ANALOG. The maximum result of the REPORT_ANALOG is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin for which to request the value (limited to pins 0 - 15). + */ +void FirmataMarshaller::reportAnalogEnable(uint8_t pin) +const +{ + reportAnalog(pin, true); +} + +/** + * Halt an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + */ +void FirmataMarshaller::reportDigitalPortDisable(uint8_t portNumber) +const +{ + reportDigitalPort(portNumber, false); +} + +/** + * Request an 8-bit port stream from the Firmata host application (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number for which to request the value. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + */ +void FirmataMarshaller::reportDigitalPortEnable(uint8_t portNumber) +const +{ + reportDigitalPort(portNumber, true); +} + +/** + * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] + * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin to which the value is sent. + * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). + * @note The maximum value is 14-bits (16384). + */ +void FirmataMarshaller::sendAnalog(uint8_t pin, uint16_t value) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + if ( (0xF >= pin) && (0x3FFF >= value) ) { + FirmataStream->write(ANALOG_MESSAGE|pin); + encodeByteStream(sizeof(value), reinterpret_cast(&value), sizeof(value)); + } else { + sendExtendedAnalog(pin, sizeof(value), reinterpret_cast(&value)); + } +} + +/** + * Send an analog mapping query to the Firmata host application. The resulting sysex message will + * have an ANALOG_MAPPING_RESPONSE command byte, followed by a list of pins [0-n]; where each + * pin will specify its corresponding analog pin number or 0x7F (127) if not applicable. + */ +void FirmataMarshaller::sendAnalogMappingQuery(void) +const +{ + sendSysex(ANALOG_MAPPING_QUERY, 0, NULL); +} + +/** + * Send a capability query to the Firmata host application. The resulting sysex message will have + * a CAPABILITY_RESPONSE command byte, followed by a list of byte tuples (mode and mode resolution) + * for each pin; where each pin list is terminated by 0x7F (127). + */ +void FirmataMarshaller::sendCapabilityQuery(void) +const +{ + sendSysex(CAPABILITY_QUERY, 0, NULL); +} + +/** + * Send a single digital pin value to the Firmata host application. + * @param pin The digital pin to send the value of. + * @param value The value of the pin. + */ +void FirmataMarshaller::sendDigital(uint8_t pin, uint8_t value) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SET_DIGITAL_PIN_VALUE); + FirmataStream->write(pin & 0x7F); + FirmataStream->write(value != 0); +} + + +/** + * Send an 8-bit port in a single digital message (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number to send. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param portData The value of the port. The value of each pin in the port is represented by a bit. + */ +void FirmataMarshaller::sendDigitalPort(uint8_t portNumber, uint16_t portData) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(DIGITAL_MESSAGE | (portNumber & 0xF)); + // Tx bits 0-6 (protocol v1 and higher) + // Tx bits 7-13 (bit 7 only for protocol v2 and higher) + encodeByteStream(sizeof(portData), reinterpret_cast(&portData), sizeof(portData)); +} + +/** + * Sends the firmware name and version to the Firmata host application. + * @param major The major verison number + * @param minor The minor version number + * @param bytec The length of the firmware name + * @param bytev The firmware name array + */ +void FirmataMarshaller::sendFirmwareVersion(uint8_t major, uint8_t minor, size_t bytec, uint8_t *bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + size_t i; + FirmataStream->write(START_SYSEX); + FirmataStream->write(REPORT_FIRMWARE); + FirmataStream->write(major); + FirmataStream->write(minor); + for (i = 0; i < bytec; ++i) { + encodeByteStream(sizeof(bytev[i]), reinterpret_cast(&bytev[i])); + } + FirmataStream->write(END_SYSEX); +} + +/** + * Send the Firmata protocol version to the Firmata host application. + * @param major The major verison number + * @param minor The minor version number + */ +void FirmataMarshaller::sendVersion(uint8_t major, uint8_t minor) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(REPORT_VERSION); + FirmataStream->write(major); + FirmataStream->write(minor); +} + +/** + * Send the pin mode/configuration. The pin configuration (or mode) in Firmata represents the + * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, + * serial (uart), etc. + * @param pin The pin to configure. + * @param config The configuration value for the specified pin. + */ +void FirmataMarshaller::sendPinMode(uint8_t pin, uint8_t config) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SET_PIN_MODE); + FirmataStream->write(pin); + FirmataStream->write(config); +} + +/** + * Send a pin state query to the Firmata host application. The resulting sysex message will have + * a PIN_STATE_RESPONSE command byte, followed by the pin number, the pin mode and a stream of + * bits to indicate any *data* written to the pin (pin state). + * @param pin The pin to query + * @note The pin state is any data written to the pin (i.e. pin state != pin value) + */ +void FirmataMarshaller::sendPinStateQuery(uint8_t pin) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(START_SYSEX); + FirmataStream->write(PIN_STATE_QUERY); + FirmataStream->write(pin); + FirmataStream->write(END_SYSEX); +} + +/** + * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes + * (this is not always the case so this function is not always used to send sysex messages). + * @param command The sysex command byte. + * @param bytec The number of data bytes in the message (excludes start, command and end bytes). + * @param bytev A pointer to the array of data bytes to send in the message. + */ +void FirmataMarshaller::sendSysex(uint8_t command, size_t bytec, uint8_t *bytev) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + size_t i; + FirmataStream->write(START_SYSEX); + FirmataStream->write(command); + for (i = 0; i < bytec; ++i) { + encodeByteStream(sizeof(bytev[i]), reinterpret_cast(&bytev[i])); + } + FirmataStream->write(END_SYSEX); +} + +/** + * Send a string to the Firmata host application. + * @param string A pointer to the char string + */ +void FirmataMarshaller::sendString(const char *string) +const +{ + sendSysex(STRING_DATA, strlen(string), reinterpret_cast(const_cast(string))); +} + +/** + * The sampling interval sets how often analog data and i2c data is reported to the client. + * @param interval_ms The interval (in milliseconds) at which to sample + * @note The default sampling interval is 19ms + */ +void FirmataMarshaller::setSamplingInterval(uint16_t interval_ms) +const +{ + sendSysex(SAMPLING_INTERVAL, sizeof(interval_ms), reinterpret_cast(&interval_ms)); +} + +/** + * Perform a software reset on the target. For example, StandardFirmata.ino will initialize + * everything to a known state and reset the parsing buffer. + */ +void FirmataMarshaller::systemReset(void) +const +{ + if ( (Stream *)NULL == FirmataStream ) { return; } + FirmataStream->write(SYSTEM_RESET); +} diff --git a/libs/Firmata/FirmataMarshaller.h b/libs/Firmata/FirmataMarshaller.h new file mode 100644 index 0000000..3fa83f6 --- /dev/null +++ b/libs/Firmata/FirmataMarshaller.h @@ -0,0 +1,75 @@ +/* + FirmataMarshaller.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataMarshaller_h +#define FirmataMarshaller_h + +#if defined(__cplusplus) && !defined(ARDUINO) + #include + #include +#else + #include + #include +#endif + +#include + +namespace firmata { + +class FirmataMarshaller +{ + friend class FirmataClass; + + public: + /* constructors */ + FirmataMarshaller(); + + /* public methods */ + void begin(Stream &s); + void end(); + + /* serial send handling */ + void queryFirmwareVersion(void) const; + void queryVersion(void) const; + void reportAnalogDisable(uint8_t pin) const; + void reportAnalogEnable(uint8_t pin) const; + void reportDigitalPortDisable(uint8_t portNumber) const; + void reportDigitalPortEnable(uint8_t portNumber) const; + void sendAnalog(uint8_t pin, uint16_t value) const; + void sendAnalogMappingQuery(void) const; + void sendCapabilityQuery(void) const; + void sendDigital(uint8_t pin, uint8_t value) const; + void sendDigitalPort(uint8_t portNumber, uint16_t portData) const; + void sendFirmwareVersion(uint8_t major, uint8_t minor, size_t bytec, uint8_t *bytev) const; + void sendVersion(uint8_t major, uint8_t minor) const; + void sendPinMode(uint8_t pin, uint8_t config) const; + void sendPinStateQuery(uint8_t pin) const; + void sendString(const char *string) const; + void sendSysex(uint8_t command, size_t bytec, uint8_t *bytev) const; + void setSamplingInterval(uint16_t interval_ms) const; + void systemReset(void) const; + + private: + /* utility methods */ + void reportAnalog(uint8_t pin, bool stream_enable) const; + void reportDigitalPort(uint8_t portNumber, bool stream_enable) const; + void sendExtendedAnalog(uint8_t pin, size_t bytec, uint8_t * bytev) const; + void encodeByteStream (size_t bytec, uint8_t * bytev, size_t max_bytes = 0) const; + + Stream * FirmataStream; +}; + +} // namespace firmata + +#endif /* FirmataMarshaller_h */ + diff --git a/libs/Firmata/FirmataParser.cpp b/libs/Firmata/FirmataParser.cpp new file mode 100644 index 0000000..d402fdf --- /dev/null +++ b/libs/Firmata/FirmataParser.cpp @@ -0,0 +1,480 @@ +/* + FirmataParser.cpp + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "FirmataParser.h" + +#include "FirmataConstants.h" + +using namespace firmata; + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The FirmataParser class. + * @param dataBuffer A pointer to an external buffer used to store parsed data + * @param dataBufferSize The size of the external buffer + */ +FirmataParser::FirmataParser(uint8_t * const dataBuffer, size_t dataBufferSize) +: + dataBuffer(dataBuffer), + dataBufferSize(dataBufferSize), + executeMultiByteCommand(0), + multiByteChannel(0), + waitForData(0), + parsingSysex(false), + sysexBytesRead(0), + currentAnalogCallbackContext((void *)NULL), + currentDigitalCallbackContext((void *)NULL), + currentReportAnalogCallbackContext((void *)NULL), + currentReportDigitalCallbackContext((void *)NULL), + currentPinModeCallbackContext((void *)NULL), + currentPinValueCallbackContext((void *)NULL), + currentReportFirmwareCallbackContext((void *)NULL), + currentReportVersionCallbackContext((void *)NULL), + currentDataBufferOverflowCallbackContext((void *)NULL), + currentStringCallbackContext((void *)NULL), + currentSysexCallbackContext((void *)NULL), + currentSystemResetCallbackContext((void *)NULL), + currentAnalogCallback((callbackFunction)NULL), + currentDigitalCallback((callbackFunction)NULL), + currentReportAnalogCallback((callbackFunction)NULL), + currentReportDigitalCallback((callbackFunction)NULL), + currentPinModeCallback((callbackFunction)NULL), + currentPinValueCallback((callbackFunction)NULL), + currentDataBufferOverflowCallback((dataBufferOverflowCallbackFunction)NULL), + currentStringCallback((stringCallbackFunction)NULL), + currentSysexCallback((sysexCallbackFunction)NULL), + currentReportFirmwareCallback((versionCallbackFunction)NULL), + currentReportVersionCallback((systemCallbackFunction)NULL), + currentSystemResetCallback((systemCallbackFunction)NULL) +{ + allowBufferUpdate = ((uint8_t *)NULL == dataBuffer); +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +//------------------------------------------------------------------------------ +// Serial Receive Handling + +/** + * Parse data from the input stream. + * @param inputData A single byte to be added to the parser. + */ +void FirmataParser::parse(uint8_t inputData) +{ + uint8_t command; + + if (parsingSysex) { + if (inputData == END_SYSEX) { + //stop sysex byte + parsingSysex = false; + //fire off handler function + processSysexMessage(); + } else { + //normal data byte - add to buffer + bufferDataAtPosition(inputData, sysexBytesRead); + ++sysexBytesRead; + } + } else if ( (waitForData > 0) && (inputData < 128) ) { + --waitForData; + bufferDataAtPosition(inputData, waitForData); + if ( (waitForData == 0) && executeMultiByteCommand ) { // got the whole message + switch (executeMultiByteCommand) { + case ANALOG_MESSAGE: + if (currentAnalogCallback) { + (*currentAnalogCallback)(currentAnalogCallbackContext, + multiByteChannel, + (dataBuffer[0] << 7) + + dataBuffer[1]); + } + break; + case DIGITAL_MESSAGE: + if (currentDigitalCallback) { + (*currentDigitalCallback)(currentDigitalCallbackContext, + multiByteChannel, + (dataBuffer[0] << 7) + + dataBuffer[1]); + } + break; + case SET_PIN_MODE: + if (currentPinModeCallback) + (*currentPinModeCallback)(currentPinModeCallbackContext, dataBuffer[1], dataBuffer[0]); + break; + case SET_DIGITAL_PIN_VALUE: + if (currentPinValueCallback) + (*currentPinValueCallback)(currentPinValueCallbackContext, dataBuffer[1], dataBuffer[0]); + break; + case REPORT_ANALOG: + if (currentReportAnalogCallback) + (*currentReportAnalogCallback)(currentReportAnalogCallbackContext, multiByteChannel, dataBuffer[0]); + break; + case REPORT_DIGITAL: + if (currentReportDigitalCallback) + (*currentReportDigitalCallback)(currentReportDigitalCallbackContext, multiByteChannel, dataBuffer[0]); + break; + } + executeMultiByteCommand = 0; + } + } else { + // remove channel info from command byte if less than 0xF0 + if (inputData < 0xF0) { + command = inputData & 0xF0; + multiByteChannel = inputData & 0x0F; + } else { + command = inputData; + // commands in the 0xF* range don't use channel data + } + switch (command) { + case ANALOG_MESSAGE: + case DIGITAL_MESSAGE: + case SET_PIN_MODE: + case SET_DIGITAL_PIN_VALUE: + waitForData = 2; // two data bytes needed + executeMultiByteCommand = command; + break; + case REPORT_ANALOG: + case REPORT_DIGITAL: + waitForData = 1; // one data byte needed + executeMultiByteCommand = command; + break; + case START_SYSEX: + parsingSysex = true; + sysexBytesRead = 0; + break; + case SYSTEM_RESET: + systemReset(); + break; + case REPORT_VERSION: + if (currentReportVersionCallback) + (*currentReportVersionCallback)(currentReportVersionCallbackContext); + break; + } + } +} + +/** + * @return Returns true if the parser is actively parsing data. + */ +bool FirmataParser::isParsingMessage(void) +const +{ + return (waitForData > 0 || parsingSysex); +} + +/** + * Provides a mechanism to either set or update the working buffer of the parser. + * The method will be enabled when no buffer has been provided, or an overflow + * condition exists. + * @param dataBuffer A pointer to an external buffer used to store parsed data + * @param dataBufferSize The size of the external buffer + */ +int FirmataParser::setDataBufferOfSize(uint8_t * dataBuffer, size_t dataBufferSize) +{ + int result; + + if ( !allowBufferUpdate ) { + result = __LINE__; + } else if ((uint8_t *)NULL == dataBuffer) { + result = __LINE__; + } else { + this->dataBuffer = dataBuffer; + this->dataBufferSize = dataBufferSize; + allowBufferUpdate = false; + result = 0; + } + + return result; +} + +/** + * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, + * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, callbackFunction newFunction, void * context) +{ + switch (command) { + case ANALOG_MESSAGE: + currentAnalogCallback = newFunction; + currentAnalogCallbackContext = context; + break; + case DIGITAL_MESSAGE: + currentDigitalCallback = newFunction; + currentDigitalCallbackContext = context; + break; + case REPORT_ANALOG: + currentReportAnalogCallback = newFunction; + currentReportAnalogCallbackContext = context; + break; + case REPORT_DIGITAL: + currentReportDigitalCallback = newFunction; + currentReportDigitalCallbackContext = context; + break; + case SET_PIN_MODE: + currentPinModeCallback = newFunction; + currentPinModeCallbackContext = context; + break; + case SET_DIGITAL_PIN_VALUE: + currentPinValueCallback = newFunction; + currentPinValueCallbackContext = context; + break; + } +} + +/** + * Attach a version callback function (supported option: REPORT_FIRMWARE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, versionCallbackFunction newFunction, void * context) +{ + switch (command) { + case REPORT_FIRMWARE: + currentReportFirmwareCallback = newFunction; + currentReportFirmwareCallbackContext = context; + break; + } +} + +/** + * Attach a system callback function (supported options are: SYSTEM_RESET, REPORT_VERSION). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, systemCallbackFunction newFunction, void * context) +{ + switch (command) { + case REPORT_VERSION: + currentReportVersionCallback = newFunction; + currentReportVersionCallbackContext = context; + break; + case SYSTEM_RESET: + currentSystemResetCallback = newFunction; + currentSystemResetCallbackContext = context; + break; + } +} + +/** + * Attach a callback function for the STRING_DATA command. + * @param command Must be set to STRING_DATA or it will be ignored. + * @param newFunction A reference to the string callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, stringCallbackFunction newFunction, void * context) +{ + switch (command) { + case STRING_DATA: + currentStringCallback = newFunction; + currentStringCallbackContext = context; + break; + } +} + +/** + * Attach a generic sysex callback function to sysex command. + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the sysex callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(uint8_t command, sysexCallbackFunction newFunction, void * context) +{ + (void)command; + currentSysexCallback = newFunction; + currentSysexCallbackContext = context; +} + +/** + * Attach a buffer overflow callback + * @param newFunction A reference to the buffer overflow callback function to attach. + * @param context An optional context to be provided to the callback function (NULL by default). + * @note The context parameter is provided so you can pass a parameter, by reference, to + * your callback function. + */ +void FirmataParser::attach(dataBufferOverflowCallbackFunction newFunction, void * context) +{ + currentDataBufferOverflowCallback = newFunction; + currentDataBufferOverflowCallbackContext = context; +} + +/** + * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, + * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). + * @param command The ID of the command to detatch the callback function from. + */ +void FirmataParser::detach(uint8_t command) +{ + switch (command) { + case REPORT_FIRMWARE: + attach(command, (versionCallbackFunction)NULL, NULL); + break; + case REPORT_VERSION: + case SYSTEM_RESET: + attach(command, (systemCallbackFunction)NULL, NULL); + break; + case STRING_DATA: + attach(command, (stringCallbackFunction)NULL, NULL); + break; + case START_SYSEX: + attach(command, (sysexCallbackFunction)NULL, NULL); + break; + default: + attach(command, (callbackFunction)NULL, NULL); + break; + } +} + +/** + * Detach the buffer overflow callback + * @param Any pointer of type dataBufferOverflowCallbackFunction. + */ +void FirmataParser::detach(dataBufferOverflowCallbackFunction) +{ + currentDataBufferOverflowCallback = (dataBufferOverflowCallbackFunction)NULL; + currentDataBufferOverflowCallbackContext = (void *)NULL; +} + +//****************************************************************************** +//* Private Methods +//****************************************************************************** + +/** + * Buffer abstraction to prevent memory corruption + * @param data The byte to put into the buffer + * @param pos The position to insert the byte into the buffer + * @return writeError A boolean to indicate if an error occured + * @private + */ +bool FirmataParser::bufferDataAtPosition(const uint8_t data, const size_t pos) +{ + bool bufferOverflow = (pos >= dataBufferSize); + + // Notify of overflow condition + if ( bufferOverflow + && ((dataBufferOverflowCallbackFunction)NULL != currentDataBufferOverflowCallback) ) + { + allowBufferUpdate = true; + currentDataBufferOverflowCallback(currentDataBufferOverflowCallbackContext); + // Check if overflow was resolved during callback + bufferOverflow = (pos >= dataBufferSize); + } + + // Write data to buffer if no overflow condition persist + if ( !bufferOverflow ) + { + dataBuffer[pos] = data; + } + + return bufferOverflow; +} + +/** + * Transform 7-bit firmata message into 8-bit stream + * @param bytec The encoded data byte length of the message (max: 16383). + * @param bytev A pointer to the encoded array of data bytes. + * @return The length of the decoded data. + * @note The conversion will be done in place on the provided buffer. + * @private + */ +size_t FirmataParser::decodeByteStream(size_t bytec, uint8_t * bytev) { + size_t decoded_bytes, i; + + for ( i = 0, decoded_bytes = 0 ; i < bytec ; ++decoded_bytes, ++i ) { + bytev[decoded_bytes] = bytev[i]; + bytev[decoded_bytes] |= (uint8_t)(bytev[++i] << 7); + } + + return decoded_bytes; +} + +/** + * Process incoming sysex messages. Handles REPORT_FIRMWARE and STRING_DATA internally. + * Calls callback function for STRING_DATA and all other sysex messages. + * @private + */ +void FirmataParser::processSysexMessage(void) +{ + switch (dataBuffer[0]) { //first byte in buffer is command + case REPORT_FIRMWARE: + if (currentReportFirmwareCallback) { + const size_t major_version_offset = 1; + const size_t minor_version_offset = 2; + const size_t string_offset = 3; + // Test for malformed REPORT_FIRMWARE message (used to query firmware prior to Firmata v3.0.0) + if ( 3 > sysexBytesRead ) { + (*currentReportFirmwareCallback)(currentReportFirmwareCallbackContext, 0, 0, (const char *)NULL); + } else { + const size_t end_of_string = (string_offset + decodeByteStream((sysexBytesRead - string_offset), &dataBuffer[string_offset])); + bufferDataAtPosition('\0', end_of_string); // NULL terminate the string + (*currentReportFirmwareCallback)(currentReportFirmwareCallbackContext, (size_t)dataBuffer[major_version_offset], (size_t)dataBuffer[minor_version_offset], (const char *)&dataBuffer[string_offset]); + } + } + break; + case STRING_DATA: + if (currentStringCallback) { + const size_t string_offset = 1; + const size_t end_of_string = (string_offset + decodeByteStream((sysexBytesRead - string_offset), &dataBuffer[string_offset])); + bufferDataAtPosition('\0', end_of_string); // NULL terminate the string + (*currentStringCallback)(currentStringCallbackContext, (const char *)&dataBuffer[string_offset]); + } + break; + default: + if (currentSysexCallback) + (*currentSysexCallback)(currentSysexCallbackContext, dataBuffer[0], sysexBytesRead - 1, dataBuffer + 1); + } +} + +/** + * Resets the system state upon a SYSTEM_RESET message from the host software. + * @private + */ +void FirmataParser::systemReset(void) +{ + size_t i; + + waitForData = 0; // this flag says the next serial input will be data + executeMultiByteCommand = 0; // execute this after getting multi-byte data + multiByteChannel = 0; // channel data for multiByteCommands + + for (i = 0; i < dataBufferSize; ++i) { + dataBuffer[i] = 0; + } + + parsingSysex = false; + sysexBytesRead = 0; + + if (currentSystemResetCallback) + (*currentSystemResetCallback)(currentSystemResetCallbackContext); +} diff --git a/libs/Firmata/FirmataParser.h b/libs/Firmata/FirmataParser.h new file mode 100644 index 0000000..bb0c8be --- /dev/null +++ b/libs/Firmata/FirmataParser.h @@ -0,0 +1,105 @@ +/* + FirmataParser.h + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataParser_h +#define FirmataParser_h + +#if defined(__cplusplus) && !defined(ARDUINO) + #include + #include +#else + #include + #include +#endif + +namespace firmata { + +class FirmataParser +{ + public: + /* callback function types */ + typedef void (*callbackFunction)(void * context, uint8_t command, uint16_t value); + typedef void (*dataBufferOverflowCallbackFunction)(void * context); + typedef void (*stringCallbackFunction)(void * context, const char * c_str); + typedef void (*sysexCallbackFunction)(void * context, uint8_t command, size_t argc, uint8_t * argv); + typedef void (*systemCallbackFunction)(void * context); + typedef void (*versionCallbackFunction)(void * context, size_t sv_major, size_t sv_minor, const char * firmware); + + FirmataParser(uint8_t * dataBuffer = (uint8_t *)NULL, size_t dataBufferSize = 0); + + /* serial receive handling */ + void parse(uint8_t value); + bool isParsingMessage(void) const; + int setDataBufferOfSize(uint8_t * dataBuffer, size_t dataBufferSize); + + /* attach & detach callback functions to messages */ + void attach(uint8_t command, callbackFunction newFunction, void * context = NULL); + void attach(dataBufferOverflowCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, stringCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, sysexCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, systemCallbackFunction newFunction, void * context = NULL); + void attach(uint8_t command, versionCallbackFunction newFunction, void * context = NULL); + void detach(uint8_t command); + void detach(dataBufferOverflowCallbackFunction); + + private: + /* input message handling */ + bool allowBufferUpdate; + uint8_t * dataBuffer; // multi-byte data + size_t dataBufferSize; + uint8_t executeMultiByteCommand; // execute this after getting multi-byte data + uint8_t multiByteChannel; // channel data for multiByteCommands + size_t waitForData; // this flag says the next serial input will be data + + /* sysex */ + bool parsingSysex; + size_t sysexBytesRead; + + /* callback context */ + void * currentAnalogCallbackContext; + void * currentDigitalCallbackContext; + void * currentReportAnalogCallbackContext; + void * currentReportDigitalCallbackContext; + void * currentPinModeCallbackContext; + void * currentPinValueCallbackContext; + void * currentReportFirmwareCallbackContext; + void * currentReportVersionCallbackContext; + void * currentDataBufferOverflowCallbackContext; + void * currentStringCallbackContext; + void * currentSysexCallbackContext; + void * currentSystemResetCallbackContext; + + /* callback functions */ + callbackFunction currentAnalogCallback; + callbackFunction currentDigitalCallback; + callbackFunction currentReportAnalogCallback; + callbackFunction currentReportDigitalCallback; + callbackFunction currentPinModeCallback; + callbackFunction currentPinValueCallback; + dataBufferOverflowCallbackFunction currentDataBufferOverflowCallback; + stringCallbackFunction currentStringCallback; + sysexCallbackFunction currentSysexCallback; + versionCallbackFunction currentReportFirmwareCallback; + systemCallbackFunction currentReportVersionCallback; + systemCallbackFunction currentSystemResetCallback; + + /* private methods ------------------------------ */ + bool bufferDataAtPosition(const uint8_t data, const size_t pos); + size_t decodeByteStream(size_t bytec, uint8_t * bytev); + void processSysexMessage(void); + void systemReset(void); +}; + +} // firmata + +#endif /* FirmataParser_h */ diff --git a/libs/Firmata/LICENSE.txt b/libs/Firmata/LICENSE.txt new file mode 100644 index 0000000..77cec6d --- /dev/null +++ b/libs/Firmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libs/Firmata/docs/Doxyfile b/libs/Firmata/docs/Doxyfile new file mode 100644 index 0000000..a420115 --- /dev/null +++ b/libs/Firmata/docs/Doxyfile @@ -0,0 +1,2539 @@ +# Doxyfile 1.8.16 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "Firmata firmware for Arduino" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = "Firmata is a protocol for communicating with microcontrollers from software on a host computer" + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = . + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all generated output in the proper direction. +# Possible values are: None, LTR, RTL and Context. +# The default value is: None. + +OUTPUT_TEXT_DIRECTION = None + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = ../ + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines (in the resulting output). You can put ^^ in the value part of an +# alias to insert a newline as if a physical newline was in the original file. +# When you need a literal { or } or , in the value part of an alias you have to +# escape them by means of a backslash (\), this can lead to conflicts with the +# commands \{ and \} for these it is advised to use the version @{ and @} or use +# a double escape (\\{ and \\}) + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, +# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is +# Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 5 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# (including Cygwin) ands Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. If +# EXTRACT_ALL is set to YES then this flag will automatically be disabled. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = ../ \ + ../readme.md + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: https://www.gnu.org/software/libiconv/) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, +# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf \ + *.ice + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = readme.md + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via Javascript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have Javascript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_MENUS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: https://developer.apple.com/xcode/), introduced with OSX +# 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. +# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/ + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /