Ver código fonte

dla potrzeb omniniecia bariery CS 53 port

a.binder 5 anos atrás
pai
commit
61fead07dc
54 arquivos alterados com 8991 adições e 2 exclusões
  1. 33 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/CONTRIBUTIONS.txt
  2. 42 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/README.md
  3. 108 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/AdvancedChatServer/AdvancedChatServer.ino
  4. 223 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino
  5. 80 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/ChatServer/ChatServer.ino
  6. 60 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino
  7. 88 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/DhcpChatServer/DhcpChatServer.ino
  8. 94 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/TelnetClient/TelnetClient.ino
  9. 119 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/UDPSendReceiveString/UDPSendReceiveString.ino
  10. 142 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/UdpNtpClient/UdpNtpClient.ino
  11. 88 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebClient/WebClient.ino
  12. 108 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebClientRepeating/WebClientRepeating.ino
  13. 101 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebServer/WebServer.ino
  14. 38 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/keywords.txt
  15. 9 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/library.properties
  16. 753 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/license.txt
  17. 518 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dhcp.cpp
  18. 182 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dhcp.h
  19. 423 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dns.cpp
  20. 41 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dns.h
  21. 209 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Ethernet2.cpp
  22. 74 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Ethernet2.h
  23. 168 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetClient.cpp
  24. 39 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetClient.h
  25. 91 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetServer.cpp
  26. 22 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetServer.h
  27. 222 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetUdp2.cpp
  28. 105 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetUdp2.h
  29. 91 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Twitter.cpp
  30. 49 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/Twitter.h
  31. 13 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/util.h
  32. 412 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/socket.cpp
  33. 48 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/socket.h
  34. 14 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/util.h
  35. 187 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/w5500.cpp
  36. 420 0
      SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/w5500.h
  37. BIN
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/MCP2515Calc.xlsx
  38. 39 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/README.md
  39. 88 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_loopback/CAN_loopback.ino
  40. 62 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_receive/CAN_receive.ino
  41. 36 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_send/CAN_send.ino
  42. 59 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_to_Ethernet/CAN_to_Ethernet.ino
  43. 19 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_to_Ethernet/udp_listen.pl
  44. 55 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Dual_CAN/Dual_CAN.ino
  45. 87 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Extended_MaskFilter/Extended_MaskFilter.ino
  46. 1046 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/OBD_Sim/OBD_Sim.ino
  47. 94 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Standard_MaskFilter/Standard_MaskFilter.ino
  48. 60 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/keywords.txt
  49. 1308 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can.cpp
  50. 143 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can.h
  51. 476 0
      SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can_dfs.h
  52. 2 2
      SE/stuff/P5_Automation_can-dev-res-working-1930/_Slave_Ports_broadcast_func.h
  53. 2 0
      SE/stuff/P5_Automation_can-dev-res-working-1930/___loop/__main_loop_end.h
  54. 1 0
      SE/stuff/P5_Automation_can-dev/P5_Automation_can-dev.xpr

+ 33 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/CONTRIBUTIONS.txt

@@ -0,0 +1,33 @@
+---------------
+DHCP.cpp
+
+// DHCP Library v0.3 - April 25, 2009
+// Author: Jordan Terrell - blog.jordanterrell.com
+
+---------------
+DNS.cpp
+
+// Arduino DNS client for WizNet5100-based Ethernet shield
+// (c) Copyright 2009-2010 MCQN Ltd.
+// Released under Apache License, version 2.0
+
+---------------
+Ethernet2: 
+ modified 12 Aug 2013
+ by Soohwan Kim (suhwan@wiznet.co.kr)
+
+---------------
+UDP.cpp: bjoern@cs.stanford.edu 12/30/2008
+
+---------------
+
+Twitter.cpp - Arduino library to Post messages to Twitter using OAuth.
+  Copyright (c) NeoCat 2010-2011. All right reserved.
+
+---------------
+Wiz5500.cpp
+
+Copyright (c) 2010 by WIZnet <support@wiznet.co.kr>
+
+--------------
+Various by Arduino.org team

+ 42 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/README.md

@@ -0,0 +1,42 @@
+Ethernet "2" Library for Arduino
+================================
+
+This Arduino library is for shields that use the **Wiznet [W5500]** chipset only.
+It does **not** work with other chipsets, such as the original Arduino Ethernet shield which
+uses the Wiznet [W5100] chipset.
+
+For more information about this library please visit us at: 
+http://www.arduino.cc/en/Reference/Ethernet
+
+
+W5500 Shields
+-------------
+
+* [Adafruit W5500 Ethernet Shield](https://www.adafruit.com/products/2971)
+* [Arduino Ethernet Shield v2](https://www.arduino.cc/en/Main/ArduinoEthernetShieldV2)
+* [Industruino Ethernet module](https://industruino.com/shop/product/ethernet-expansion-module-10)
+* [Wiznet W5500 Ethernet Shield](http://www.wiznet.co.kr/product-item/w5500-ethernet-shield/)
+
+
+License
+-------
+
+Copyright (c) 2009-2016 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
+
+
+[W5100]:                   http://www.wiznet.co.kr/product-item/w5100/
+[W5500]:                   http://www.wiznet.co.kr/product-item/w5500/

+ 108 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/AdvancedChatServer/AdvancedChatServer.ino

@@ -0,0 +1,108 @@
+/*
+ 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
+ * Analog inputs attached to pins A0 through A5 (optional)
+
+ 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 <SPI.h>
+#include <Ethernet2.h>
+
+// 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 gateway(192,168,1, 1);
+IPAddress subnet(255, 255, 0, 0);
+
+
+// telnet defaults to port 23
+EthernetServer server(23);
+
+EthernetClient clients[4];
+
+void setup() {
+  // initialize the ethernet device
+  Ethernet.begin(mac, ip, gateway, subnet);
+  // start listening for clients
+  server.begin();
+ // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+   while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+
+  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) {
+
+    boolean newClient = true;
+    for (byte i=0;i<4;i++) {
+      //check whether this client refers to the same socket as one of the existing instances:
+      if (clients[i]==client) {
+        newClient = false;
+        break;
+      }
+    }
+
+    if (newClient) {
+      //check which of the existing clients can be overridden:
+      for (byte i=0;i<4;i++) {
+        if (!clients[i] && clients[i]!=client) {
+          clients[i] = client;
+          // clead out the input buffer:
+          client.flush();
+          Serial.println("We have a new client");
+          client.print("Hello, client number: ");
+          client.print(i);
+          client.println();
+          break;
+        }
+      }
+    }
+
+    if (client.available() > 0) {
+      // read the bytes incoming from the client:
+      char thisChar = client.read();
+      // echo the bytes back to all other connected clients:
+      for (byte i=0;i<4;i++) {
+        if (clients[i] && (clients[i]!=client)) {
+          clients[i].write(thisChar);
+        }
+      }
+      // echo the bytes to the server as well:
+      Serial.write(thisChar);
+    }
+  }
+  for (byte i=0;i<4;i++) {
+    if (!(clients[i].connected())) {
+      // client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
+      clients[i].stop();
+    }
+  }
+}

+ 223 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino

@@ -0,0 +1,223 @@
+/*
+  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
+ http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
+
+ This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
+ http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
+
+ 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 <Ethernet2.h>
+// the sensor communicates using SPI, so include the library:
+#include <SPI.h>
+
+
+// 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);
+IPAddress gateway(192, 168, 1, 1);
+IPAddress subnet(255, 255, 255, 0);
+
+
+// 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() {
+  // start the SPI library:
+  SPI.begin();
+
+  // start the Ethernet connection and the server:
+  Ethernet.begin(mac, ip);
+  server.begin();
+
+  // initalize the  data ready and chip select pins:
+  pinMode(dataReadyPin, INPUT);
+  pinMode(chipSelectPin, OUTPUT);
+
+  Serial.begin(9600);
+
+  //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 tp 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
+    boolean 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("<br />");
+          client.print("Pressure: " + String(pressure));
+          client.print(" Pa");
+          client.println("<br />");
+          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:
+  int command = 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);
+}

+ 80 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/ChatServer/ChatServer.ino

@@ -0,0 +1,80 @@
+/*
+ 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
+ * Analog inputs attached to pins A0 through A5 (optional)
+
+ created 18 Dec 2009
+ by David A. Mellis
+ modified 9 Apr 2012
+ by Tom Igoe
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// 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 gateway(192, 168, 1, 1);
+IPAddress subnet(255, 255, 0, 0);
+
+
+// telnet defaults to port 23
+EthernetServer server(23);
+boolean alreadyConnected = false; // whether or not the client was connected previously
+
+void setup() {
+  // initialize the ethernet device
+  Ethernet.begin(mac, ip, gateway, subnet);
+  // start listening for clients
+  server.begin();
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+
+  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) {
+      // clead 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);
+    }
+  }
+}
+
+
+

+ 60 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino

@@ -0,0 +1,60 @@
+/*
+  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
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// 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() {
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  // this check is only needed on the Leonardo:
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // 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.print("My IP address: ");
+  for (byte thisByte = 0; thisByte < 4; thisByte++) {
+    // print the value of each byte of the IP address:
+    Serial.print(Ethernet.localIP()[thisByte], DEC);
+    Serial.print(".");
+  }
+  Serial.println();
+}
+
+void loop() {
+
+}
+
+

+ 88 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/DhcpChatServer/DhcpChatServer.ino

@@ -0,0 +1,88 @@
+/*
+ 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
+ Based on ChatServer example by David A. Mellis
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// 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[] = {
+  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
+};
+IPAddress ip(192, 168, 1, 177);
+IPAddress gateway(192, 168, 1, 1);
+IPAddress subnet(255, 255, 0, 0);
+
+// telnet defaults to port 23
+EthernetServer server(23);
+boolean gotAMessage = false; // whether or not you got a message from the client yet
+
+void setup() {
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  // this check is only needed on the Leonardo:
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo 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");
+    // initialize the ethernet device not using DHCP:
+    Ethernet.begin(mac, ip, gateway, subnet);
+  }
+  // print your local IP address:
+  Serial.print("My IP address: ");
+  ip = Ethernet.localIP();
+  for (byte thisByte = 0; thisByte < 4; thisByte++) {
+    // print the value of each byte of the IP address:
+    Serial.print(ip[thisByte], DEC);
+    Serial.print(".");
+  }
+  Serial.println();
+  // 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);
+  }
+}
+

+ 94 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/TelnetClient/TelnetClient.ino

@@ -0,0 +1,94 @@
+/*
+  Telnet client
+
+ This sketch connects to a 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
+ http://processing.org/
+
+ Circuit:
+ * Ethernet shield attached to pins 10, 11, 12, 13
+
+ created 14 Sep 2010
+ modified 9 Apr 2012
+ by Tom Igoe
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// 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() {
+  // 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 Leonardo only
+  }
+
+
+  // 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);
+  }
+}
+
+
+
+

+ 119 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/UDPSendReceiveString/UDPSendReceiveString.ino

@@ -0,0 +1,119 @@
+/*
+  UDPSendReceive.pde:
+ 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 received messages for testing with a computer.
+
+ created 21 Aug 2010
+ by Michael Margolis
+
+ This code is in the public domain.
+ */
+
+
+#include <SPI.h>         // needed for Arduino versions later than 0018
+#include <Ethernet2.h>
+#include <EthernetUdp2.h>         // 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
+
+// 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() {
+  // 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);
+    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 packetBufffer
+    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();
+ }
+ */
+
+

+ 142 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/UdpNtpClient/UdpNtpClient.ino

@@ -0,0 +1,142 @@
+/*
+
+ 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 http://en.wikipedia.org/wiki/Network_Time_Protocol
+
+ created 4 Sep 2010
+ by Michael Margolis
+ modified 9 Apr 2012
+ by Tom Igoe
+
+ This code is in the public domain.
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+#include <EthernetUdp2.h>
+
+// 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
+
+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()
+{
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+
+  // start Ethernet and UDP
+  if (Ethernet.begin(mac) == 0) {
+    Serial.println("Failed to configure Ethernet using DHCP");
+    // no point in carrying on, so do nothing forevermore:
+    for (;;)
+      ;
+  }
+  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, esxtract 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);
+}
+
+// send an NTP request to the time server at the given address
+unsigned long sendNTPpacket(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();
+}
+
+
+
+
+
+
+
+
+
+

+ 88 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebClient/WebClient.ino

@@ -0,0 +1,88 @@
+/*
+  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 <SPI.h>
+#include <Ethernet2.h>
+
+// 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);
+
+// 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() {
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // 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:
+    // try to congifure using IP address instead of DHCP:
+    Ethernet.begin(mac, ip);
+  }
+  // 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, 80)) {
+    Serial.println("connected");
+    // 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 {
+    // kf 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);
+  }
+
+  // if the server's disconnected, stop the client:
+  if (!client.connected()) {
+    Serial.println();
+    Serial.println("disconnecting.");
+    client.stop();
+
+    // do nothing forevermore:
+    while (true);
+  }
+}
+

+ 108 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebClientRepeating/WebClientRepeating.ino

@@ -0,0 +1,108 @@
+/*
+  Repeating Web client
+
+ This sketch connects to a 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
+
+ http://arduino.cc/en/Tutorial/WebClientRepeating
+ This code is in the public domain.
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// assign a MAC address for the ethernet controller.
+// fill in your address here:
+byte mac[] = {
+  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
+};
+// fill in an available IP address on your network here,
+// for manual configuration:
+IPAddress ip(192, 168, 1, 177);
+
+// fill in your Domain Name Server address here:
+IPAddress myDns(1, 1, 1, 1);
+
+// initialize the library instance:
+EthernetClient client;
+
+char server[] = "www.arduino.cc";
+//IPAddress server(64,131,82,241);
+
+unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
+const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
+// the "L" is needed to use long type numbers
+
+void setup() {
+  // start serial port:
+  Serial.begin(9600);
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+  // give the ethernet module time to boot up:
+  delay(1000);
+  // start the Ethernet connection using a fixed IP address and DNS server:
+  Ethernet.begin(mac, ip, myDns);
+  // print the Ethernet board/shield's IP address:
+  Serial.print("My IP address: ");
+  Serial.println(Ethernet.localIP());
+}
+
+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 WiFi shield
+  client.stop();
+
+  // if there's a successful connection:
+  if (client.connect(server, 80)) {
+    Serial.println("connecting...");
+    // send the HTTP PUT 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");
+  }
+}
+
+

+ 101 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/examples/WebServer/WebServer.ino

@@ -0,0 +1,101 @@
+/*
+  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
+
+ */
+
+#include <SPI.h>
+#include <Ethernet2.h>
+
+// 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() {
+  // Open serial communications and wait for port to open:
+  Serial.begin(9600);
+  while (!Serial) {
+    ; // wait for serial port to connect. Needed for Leonardo only
+  }
+
+
+  // start the Ethernet connection and the server:
+  Ethernet.begin(mac, ip);
+  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
+    boolean 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("<!DOCTYPE HTML>");
+          client.println("<html>");
+          // 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("<br />");
+          }
+          client.println("</html>");
+          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");
+  }
+}
+

+ 38 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/keywords.txt

@@ -0,0 +1,38 @@
+#######################################
+# Syntax Coloring Map For Ethernet
+#######################################
+
+#######################################
+# Datatypes (KEYWORD1)
+#######################################
+
+Ethernet2	KEYWORD1
+EthernetClient	KEYWORD1
+EthernetServer	KEYWORD1
+IPAddress	KEYWORD1
+EthernetUdp2	KEYWORD1
+
+#######################################
+# Methods and Functions (KEYWORD2)
+#######################################
+
+status	KEYWORD2
+connect	KEYWORD2
+write	KEYWORD2
+available	KEYWORD2
+read	KEYWORD2
+peek	KEYWORD2
+flush	KEYWORD2
+stop	KEYWORD2
+connected	KEYWORD2
+begin	KEYWORD2
+beginPacket	KEYWORD2
+endPacket	KEYWORD2
+parsePacket	KEYWORD2
+remoteIP	KEYWORD2
+remotePort	KEYWORD2
+
+#######################################
+# Constants (LITERAL1)
+#######################################
+

+ 9 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/library.properties

@@ -0,0 +1,9 @@
+name=Ethernet2
+version=1.0.4
+author=Various
+maintainer=Adafruit <info@adafruit.com>
+sentence=Enables network connection (local and Internet) using W5500 based Ethernet shields.
+paragraph=With this library you can use W5500 based Ethernet shields, such as the 'Arduino Ethernet Shield v2' to connect to Internet, but not older W5100 based shields. 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://github.com/adafruit/Ethernet2
+architectures=*

+ 753 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/license.txt

@@ -0,0 +1,753 @@
+this file includes licensing information for parts of arduino.
+
+first, the gnu general public license, which covers the main body 
+of the processing/arduino code (in general, all the stuff inside the 'app'
+and 'core' subfolders).
+
+next, the gnu lesser general public license that covers the arduino core
+and libraries.
+
+
+.....................................................................
+
+
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, 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 or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+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 give any other recipients of the Program a copy of this License
+along with the Program.
+
+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 Program or any portion
+of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+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 Program, 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 Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) 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; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, 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 executable.  However, as a
+special exception, the source code 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.
+
+If distribution of executable or 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 counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program 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.
+
+  5. 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 Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program 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 to
+this License.
+
+  7. 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 Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program 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 Program.
+
+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.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program 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.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the 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 Program
+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 Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, 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
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+
+
+.....................................................................
+
+		  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.
+

+ 518 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dhcp.cpp

@@ -0,0 +1,518 @@
+// DHCP Library v0.3 - April 25, 2009
+// Author: Jordan Terrell - blog.jordanterrell.com
+
+#include "utility/w5500.h"
+
+#include <string.h>
+#include <stdlib.h>
+#include "Dhcp.h"
+#include "Arduino.h"
+#include "utility/util.h"
+
+int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
+{
+    _dhcpLeaseTime=0;
+    _dhcpT1=0;
+    _dhcpT2=0;
+    _lastCheck=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)
+        {
+            //Serial.println("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 = _dhcpT1 << 1;
+                }
+                _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++;
+
+    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 (-1 == _dhcpUdpSocket.beginPacket(dest_addr, DHCP_SERVER_PORT))
+    {
+        // 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 w5500 transmit buffer
+    _dhcpUdpSocket.write(buffer, 28);
+
+    memset(buffer, 0, 32); // clear local buffer
+
+    memcpy(buffer, _dhcpMacAddr, 6); // chaddr
+
+    //put data in w5500 transmit buffer
+    _dhcpUdpSocket.write(buffer, 16);
+
+    memset(buffer, 0, 32); // clear local buffer
+
+    // leave zeroed out for sname && file
+    // put in w5500 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 w5500 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 w5500 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 w5500 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();
+            return 0;
+        }
+
+        memcpy(_dhcpLocalIp, fixedMsg.yiaddr, 4);
+
+        // Skip to the option part
+        // Doing this a byte at a time so we don't have to put a big buffer
+        // on the stack (as we don't have lots of memory lying around)
+        for (int i =0; i < (240 - (int)sizeof(RIP_MSG_FIXED)); i++)
+        {
+            _dhcpUdpSocket.read(); // we don't care about the returned byte
+        }
+
+        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);
+                    for (int i = 0; i < opt_len-4; i++)
+                    {
+                        _dhcpUdpSocket.read();
+                    }
+                    break;
+                
+                case dns :
+					opt_len = _dhcpUdpSocket.read();
+                    _dhcpUdpSocket.read(_dhcpDnsServerIp, 4);
+                    for (int i = 0; i < opt_len-4; i++)
+                    {
+                        _dhcpUdpSocket.read();
+                    }
+                    break;
+                    
+                case domainName:
+                    opt_len = _dhcpUdpSocket.read();
+                    _dhcpDnsdomainName = (char*)malloc(sizeof(char)*opt_len+1);
+                    _dhcpUdpSocket.read(_dhcpDnsdomainName, opt_len);
+                    _dhcpDnsdomainName[opt_len] = '\0';
+                    break;
+                case hostName:
+                    opt_len = _dhcpUdpSocket.read();
+                    _dhcpHostName = (char*)malloc(sizeof(char)*opt_len+1);
+                    _dhcpUdpSocket.read(_dhcpHostName, opt_len);
+                    _dhcpHostName[opt_len] = '\0';
+                    break;
+                case dhcpServerIdentifier :
+                    
+					opt_len = _dhcpUdpSocket.read();
+                    if(((_dhcpDhcpServerIp[0] == 0) && (_dhcpDhcpServerIp[1] == 0) && (_dhcpDhcpServerIp[2] == 0) && (_dhcpDhcpServerIp[3] == 0))  || (IPAddress(_dhcpDhcpServerIp) == _dhcpUdpSocket.remoteIP())) 
+                    {
+                        _dhcpUdpSocket.read(_dhcpDhcpServerIp, sizeof(_dhcpDhcpServerIp));
+                    }
+                    else
+                    {
+                        // Skip over the rest of this option
+                        while (opt_len--)
+                        {
+                            _dhcpUdpSocket.read();
+                        }
+                    }
+                    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
+                    while (opt_len--)
+                    {
+                        _dhcpUdpSocket.read();
+                    }
+                    break;
+            }
+        }
+    }
+
+    // Need to skip to end of the packet regardless here
+    _dhcpUdpSocket.flush();
+
+    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(){
+    //this uses a signed / unsigned trick to deal with millis overflow
+    unsigned long now = millis();
+    signed long snow = (long)now;
+    int rc=DHCP_CHECK_NONE;
+    if (_lastCheck != 0){
+        signed long factor;
+        //calc how many ms past the timeout we are
+        factor = snow - (long)_secTimeout;
+        //if on or passed the timeout, reduce the counters
+        if ( factor >= 0 ){
+            //next timeout should be now plus 1000 ms minus parts of second in factor
+            _secTimeout = snow + 1000 - factor % 1000;
+            //how many seconds late are we, minimum 1
+            factor = factor / 1000 +1;
+            
+            //reduce the counters by that mouch
+            //if we can assume that the cycle time (factor) is fairly constant
+            //and if the remainder is less than cycle time * 2 
+            //do it early instead of late
+            if(_renewInSec < factor*2 )
+                _renewInSec = 0;
+            else
+                _renewInSec -= factor;
+            
+            if(_rebindInSec < factor*2 )
+                _rebindInSec = 0;
+            else
+                _rebindInSec -= factor;
+        }
+
+        //if we have a lease but should renew, do it
+        if (_dhcp_state == STATE_DHCP_LEASED && _renewInSec <=0){
+            _dhcp_state = STATE_DHCP_REREQUEST;
+            rc = 1 + request_DHCP_lease();
+        }
+
+        //if we have a lease or is renewing but should bind, do it
+        if( (_dhcp_state == STATE_DHCP_LEASED || _dhcp_state == STATE_DHCP_START) && _rebindInSec <=0){
+            //this should basically restart completely
+            _dhcp_state = STATE_DHCP_START;
+            reset_DHCP_lease();
+            rc = 3 + request_DHCP_lease();
+        }
+    }
+    else{
+        _secTimeout = snow + 1000;
+    }
+
+    _lastCheck = now;
+    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);
+}
+
+char* DhcpClass::getDnsDomainName()
+{
+    return _dhcpDnsdomainName;
+}
+
+char* DhcpClass::getHostName()
+{
+    return _dhcpHostName;
+}
+
+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);
+}

+ 182 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dhcp.h

@@ -0,0 +1,182 @@
+// DHCP Library v0.3 - April 25, 2009
+// Author: Jordan Terrell - blog.jordanterrell.com
+
+#ifndef Dhcp_h
+#define Dhcp_h
+
+#include "EthernetUdp2.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;
+
+class DhcpClass {
+
+private:
+  uint32_t _dhcpInitialTransactionId;
+  uint32_t _dhcpTransactionId;
+  uint8_t  _dhcpMacAddr[6];
+  uint8_t  _dhcpLocalIp[4];
+  char* _dhcpDnsdomainName;
+  char* _dhcpHostName;
+  uint8_t  _dhcpSubnetMask[4];
+  uint8_t  _dhcpGatewayIp[4];
+  uint8_t  _dhcpDhcpServerIp[4];
+  uint8_t  _dhcpDnsServerIp[4];
+  uint32_t _dhcpLeaseTime;
+  uint32_t _dhcpT1, _dhcpT2;
+  signed long _renewInSec;
+  signed long _rebindInSec;
+  signed long _lastCheck;
+  unsigned long _timeout;
+  unsigned long _responseTimeout;
+  unsigned long _secTimeout;
+  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();
+  char* getDnsDomainName();
+  char* getHostName();
+  
+  int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 5000);  
+  int checkLease();
+};
+
+#endif

+ 423 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dns.cpp

@@ -0,0 +1,423 @@
+// Arduino DNS client for WizNet5100-based Ethernet shield
+// (c) Copyright 2009-2010 MCQN Ltd.
+// Released under Apache License, version 2.0
+
+#include "utility/w5500.h"
+#include "EthernetUdp2.h"
+#include "utility/util.h"
+
+#include "Dns.h"
+#include <string.h>
+//#include <stdlib.h>
+#include "Arduino.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* aIPAddrString, IPAddress& aResult)
+{
+    // See if we've been given a valid IP address
+    const char* p =aIPAddrString;
+    while (*p &&
+           ( (*p == '.') || (*p >= '0') || (*p <= '9') ))
+    {
+        p++;
+    }
+
+    if (*p == '\0')
+    {
+        // It's looking promising, we haven't found any invalid characters
+        p = aIPAddrString;
+        int segment =0;
+        int segmentValue =0;
+        while (*p && (segment < 4))
+        {
+            if (*p == '.')
+            {
+                // We've reached the end of a segment
+                if (segmentValue > 255)
+                {
+                    // You can't have IP address segments that don't fit in a byte
+                    return 0;
+                }
+                else
+                {
+                    aResult[segment] = (byte)segmentValue;
+                    segment++;
+                    segmentValue = 0;
+                }
+            }
+            else
+            {
+                // Next digit
+                segmentValue = (segmentValue*10)+(*p - '0');
+            }
+            p++;
+        }
+        // We've reached the end of address, but there'll still be the last
+        // segment to deal with
+        if ((segmentValue > 255) || (segment > 3))
+        {
+            // You can't have IP address segments that don't fit in a byte,
+            // or more than four segments
+            return 0;
+        }
+        else
+        {
+            aResult[segment] = (byte)segmentValue;
+            return 1;
+        }
+    }
+    else
+    {
+        return 0;
+    }
+}
+
+int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult)
+{
+    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(5000, 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
+    // 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, DNS_HEADER_SIZE);
+
+    uint16_t header_flags = htons(*((uint16_t*)&header[2]));
+    // Check that it's a response to this request
+    if ( ( iRequestId != (*((uint16_t*)&header[0])) ) ||
+        ((header_flags & QUERY_RESPONSE_MASK) != (uint16_t)RESPONSE_FLAG) )
+    {
+        // Mark the entire packet as read
+        iUdp.flush();
+        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();
+        return -5; //INVALID_RESPONSE;
+    }
+
+    // And make sure we've got (at least) one answer
+    uint16_t answerCount = htons(*((uint16_t*)&header[6]));
+    if (answerCount == 0 )
+    {
+        // Mark the entire packet as read
+        iUdp.flush();
+        return -6; //INVALID_RESPONSE;
+    }
+
+    // Skip over any questions
+    for (uint16_t i =0; i < htons(*((uint16_t*)&header[4])); 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
+                while(len--)
+                {
+                    iUdp.read(); // we don't care about the returned byte
+                }
+            }
+        } while (len != 0);
+
+        // Now jump over the type and class
+        for (int i =0; i < 4; i++)
+        {
+            iUdp.read(); // we don't care about the returned byte
+        }
+    }
+
+    // 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
+                    while(len--)
+                    {
+                        iUdp.read(); // we don't care about the returned byte
+                    }
+                }
+            }
+            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(); // we don't care about the returned 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
+        for (int i =0; i < TTL_SIZE; i++)
+        {
+            iUdp.read(); // we don't care about the returned byte
+        }
+
+        // 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();
+                return -9;//INVALID_RESPONSE;
+            }
+            iUdp.read(aAddress.raw_address(), 4);
+            return SUCCESS;
+        }
+        else
+        {
+            // This isn't an answer type we're after, move onto the next one
+            for (uint16_t i =0; i < htons(header_flags); i++)
+            {
+                iUdp.read(); // we don't care about the returned byte
+            }
+        }
+    }
+
+    // Mark the entire packet as read
+    iUdp.flush();
+
+    // If we get here then we haven't found an answer
+    return -10;//INVALID_RESPONSE;
+}
+

+ 41 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Dns.h

@@ -0,0 +1,41 @@
+// Arduino DNS client for WizNet5100-based Ethernet shield
+// (c) Copyright 2009-2010 MCQN Ltd.
+// Released under Apache License, version 2.0
+
+#ifndef DNSClient_h
+#define DNSClient_h
+
+#include <EthernetUdp2.h>
+
+class DNSClient
+{
+public:
+    // ctor
+    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);
+
+protected:
+    uint16_t BuildRequest(const char* aName);
+    uint16_t ProcessResponse(uint16_t aTimeout, IPAddress& aAddress);
+
+    IPAddress iDNSServer;
+    uint16_t iRequestId;
+    EthernetUDP iUdp;
+};
+
+#endif

+ 209 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Ethernet2.cpp

@@ -0,0 +1,209 @@
+/*
+ modified 12 Aug 2013
+ by Soohwan Kim (suhwan@wiznet.co.kr)
+
+- 10 Apr. 2015
+ Added support for Arduino Ethernet Shield 2
+ by Arduino.org team
+
+ */
+ 
+#include "Ethernet2.h"
+#include "Dhcp.h"
+
+// XXX: don't make assumptions about the value of MAX_SOCK_NUM.
+uint8_t EthernetClass::_state[MAX_SOCK_NUM] = { 0, };
+uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = { 0, };
+
+
+
+#if defined(WIZ550io_WITH_MACADDRESS)
+int EthernetClass::begin(void)
+{
+  byte mac_address[6] ={0,};
+  if (_dhcp != NULL) {
+    delete _dhcp;
+  }
+  _dhcp = new DhcpClass();
+
+  // Initialise the basic info
+  w5500.init(w5500_cspin);
+  w5500.setIPAddress(IPAddress(0,0,0,0).raw_address());
+  w5500.getMACAddress(mac_address);
+  
+  // Now try to get our config info from a DHCP server
+  int ret = _dhcp->beginWithDHCP(mac_address);
+  if(ret == 1)
+  {
+    // We've successfully found a DHCP server and got our configuration info, so set things
+    // accordingly
+    w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
+    w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
+    w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
+    _dnsServerAddress = _dhcp->getDnsServerIp();
+    _dnsDomainName = _dhcp->getDnsDomainName();
+    _hostName = _dhcp->getHostName();
+  }
+
+  return ret;
+}
+
+void EthernetClass::begin(IPAddress local_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_server = local_ip;
+  dns_server[3] = 1;
+  begin(local_ip, dns_server);
+}
+
+void EthernetClass::begin(IPAddress local_ip, IPAddress dns_server)
+{
+  // Assume the gateway will be the machine on the same network as the local IP
+  // but with last octet being '1'
+  IPAddress gateway = local_ip;
+  gateway[3] = 1;
+  begin(local_ip, dns_server, gateway);
+}
+
+void EthernetClass::begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
+{
+  IPAddress subnet(255, 255, 255, 0);
+  begin(local_ip, dns_server, gateway, subnet);
+}
+
+void EthernetClass::begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)
+{
+  w5500.init(w5500_cspin);
+  w5500.setIPAddress(local_ip.raw_address());
+  w5500.setGatewayIp(gateway.raw_address());
+  w5500.setSubnetMask(subnet.raw_address());
+  _dnsServerAddress = dns_server;
+}
+#else
+int EthernetClass::begin(uint8_t *mac_address)
+{
+   if (_dhcp != NULL) {
+     delete _dhcp;
+   }
+  _dhcp = new DhcpClass();
+  // Initialise the basic info
+  w5500.init(w5500_cspin);
+  w5500.setMACAddress(mac_address);
+  w5500.setIPAddress(IPAddress(0,0,0,0).raw_address());
+
+  // Now try to get our config info from a DHCP server
+  int ret = _dhcp->beginWithDHCP(mac_address);
+  if(ret == 1)
+  {
+    // We've successfully found a DHCP server and got our configuration info, so set things
+    // accordingly
+    w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
+    w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
+    w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
+    _dnsServerAddress = _dhcp->getDnsServerIp();
+    _dnsDomainName = _dhcp->getDnsDomainName();
+    _hostName = _dhcp->getHostName();
+  }
+
+  return ret;
+}
+
+void EthernetClass::begin(uint8_t *mac_address, IPAddress local_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_server = local_ip;
+  dns_server[3] = 1;
+  begin(mac_address, local_ip, dns_server);
+}
+
+void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server)
+{
+  // Assume the gateway will be the machine on the same network as the local IP
+  // but with last octet being '1'
+  IPAddress gateway = local_ip;
+  gateway[3] = 1;
+  begin(mac_address, local_ip, dns_server, gateway);
+}
+
+void EthernetClass::begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway)
+{
+  IPAddress subnet(255, 255, 255, 0);
+  begin(mac_address, local_ip, dns_server, gateway, subnet);
+}
+
+void EthernetClass::begin(uint8_t *mac, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet)
+{
+  w5500.init(w5500_cspin);
+  w5500.setMACAddress(mac);
+  w5500.setIPAddress(local_ip.raw_address());
+  w5500.setGatewayIp(gateway.raw_address());
+  w5500.setSubnetMask(subnet.raw_address());
+  _dnsServerAddress = dns_server;
+}
+
+#endif
+
+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.
+        w5500.setIPAddress(_dhcp->getLocalIp().raw_address());
+        w5500.setGatewayIp(_dhcp->getGatewayIp().raw_address());
+        w5500.setSubnetMask(_dhcp->getSubnetMask().raw_address());
+        _dnsServerAddress = _dhcp->getDnsServerIp();
+        _dnsDomainName = _dhcp->getDnsDomainName();
+        _hostName = _dhcp->getHostName();
+        break;
+      default:
+        //this is actually a error, it will retry though
+        break;
+    }
+  }
+  return rc;
+}
+
+IPAddress EthernetClass::localIP()
+{
+  IPAddress ret;
+  w5500.getIPAddress(ret.raw_address());
+  return ret;
+}
+
+IPAddress EthernetClass::subnetMask()
+{
+  IPAddress ret;
+  w5500.getSubnetMask(ret.raw_address());
+  return ret;
+}
+
+IPAddress EthernetClass::gatewayIP()
+{
+  IPAddress ret;
+  w5500.getGatewayIp(ret.raw_address());
+  return ret;
+}
+
+IPAddress EthernetClass::dnsServerIP()
+{
+  return _dnsServerAddress;
+}
+
+char* EthernetClass::dnsDomainName(){
+    return _dnsDomainName;
+}
+
+char* EthernetClass::hostName(){
+    return _hostName;
+}
+
+EthernetClass Ethernet;

+ 74 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Ethernet2.h

@@ -0,0 +1,74 @@
+/*
+ modified 12 Aug 2013
+ by Soohwan Kim (suhwan@wiznet.co.kr)
+
+ - 10 Apr. 2015
+ Added support for Arduino Ethernet Shield 2
+ by Arduino.org team
+ 
+ */
+#ifndef ethernet_h
+#define ethernet_h
+
+#include <inttypes.h>
+#include "utility/w5500.h"
+#include "IPAddress.h"
+#include "EthernetClient.h"
+#include "EthernetServer.h"
+#include "Dhcp.h"
+
+
+
+class EthernetClass {
+private:
+  IPAddress _dnsServerAddress;
+  char* _dnsDomainName;
+  char* _hostName;
+  DhcpClass* _dhcp;
+public:
+  uint8_t w5500_cspin;
+
+  static uint8_t _state[MAX_SOCK_NUM];
+  static uint16_t _server_port[MAX_SOCK_NUM];
+
+  EthernetClass() { _dhcp = NULL; w5500_cspin = 10; }
+  void init(uint8_t _cspin = 10) { w5500_cspin = _cspin; }
+
+#if defined(WIZ550io_WITH_MACADDRESS)
+  // Initialize function when use the ioShield serise (included WIZ550io)
+  // WIZ550io has a MAC address which is written after reset.
+  // Default IP, Gateway and subnet address are also writen.
+  // so, It needs some initial time. please refer WIZ550io Datasheet in details.
+  int begin(void);
+  void begin(IPAddress local_ip);
+  void begin(IPAddress local_ip, IPAddress dns_server);
+  void begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway);
+  void begin(IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);
+#else
+  // Initialize 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
+  int begin(uint8_t *mac_address);
+  void begin(uint8_t *mac_address, IPAddress local_ip);
+  void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server);
+  void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway);
+  void begin(uint8_t *mac_address, IPAddress local_ip, IPAddress dns_server, IPAddress gateway, IPAddress subnet);
+
+#endif
+  
+  int maintain();
+
+  IPAddress localIP();
+  IPAddress subnetMask();
+  IPAddress gatewayIP();
+  IPAddress dnsServerIP();
+  char* dnsDomainName();
+  char* hostName();
+
+  friend class EthernetClient;
+  friend class EthernetServer;
+};
+
+extern EthernetClass Ethernet;
+
+#endif

+ 168 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetClient.cpp

@@ -0,0 +1,168 @@
+#include "utility/w5500.h"
+#include "utility/socket.h"
+
+extern "C" {
+  #include "string.h"
+}
+
+#include "Arduino.h"
+
+#include "Ethernet2.h"
+#include "EthernetClient.h"
+#include "EthernetServer.h"
+#include "Dns.h"
+
+uint16_t EthernetClient::_srcport = 1024;
+
+EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
+}
+
+EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
+}
+
+int EthernetClient::connect(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 connect(remote_addr, port);
+  } else {
+    return ret;
+  }
+}
+
+int EthernetClient::connect(IPAddress ip, uint16_t port) {
+  if (_sock != MAX_SOCK_NUM)
+    return 0;
+
+  for (int i = 0; i < MAX_SOCK_NUM; i++) {
+    uint8_t s = w5500.readSnSR(i);
+    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
+      _sock = i;
+      break;
+    }
+  }
+
+  if (_sock == MAX_SOCK_NUM)
+    return 0;
+
+  _srcport++;
+  if (_srcport == 0) _srcport = 1024;
+  socket(_sock, SnMR::TCP, _srcport, 0);
+
+  if (!::connect(_sock, rawIPAddress(ip), port)) {
+    _sock = MAX_SOCK_NUM;
+    return 0;
+  }
+
+  while (status() != SnSR::ESTABLISHED) {
+    delay(1);
+    if (status() == SnSR::CLOSED) {
+      _sock = MAX_SOCK_NUM;
+      return 0;
+    }
+  }
+
+  return 1;
+}
+
+size_t EthernetClient::write(uint8_t b) {
+  return write(&b, 1);
+}
+
+size_t EthernetClient::write(const uint8_t *buf, size_t size) {
+  if (_sock == MAX_SOCK_NUM) {
+    setWriteError();
+    return 0;
+  }
+  if (!send(_sock, buf, size)) {
+    setWriteError();
+    return 0;
+  }
+  return size;
+}
+
+int EthernetClient::available() {
+  if (_sock != MAX_SOCK_NUM)
+    return w5500.getRXReceivedSize(_sock);
+  return 0;
+}
+
+int EthernetClient::read() {
+  uint8_t b;
+  if ( recv(_sock, &b, 1) > 0 )
+  {
+    // recv worked
+    return b;
+  }
+  else
+  {
+    // No data available
+    return -1;
+  }
+}
+
+int EthernetClient::read(uint8_t *buf, size_t size) {
+  return recv(_sock, buf, size);
+}
+
+int EthernetClient::peek() {
+  uint8_t b;
+  // Unlike recv, peek doesn't check to see if there's any data available, so we must
+  if (!available())
+    return -1;
+  ::peek(_sock, &b);
+  return b;
+}
+
+void EthernetClient::flush() {
+  ::flush(_sock);
+}
+
+void EthernetClient::stop() {
+  if (_sock == MAX_SOCK_NUM)
+    return;
+
+  // attempt to close the connection gracefully (send a FIN to other side)
+  disconnect(_sock);
+  unsigned long start = millis();
+
+  // wait a second for the connection to close
+  while (status() != SnSR::CLOSED && millis() - start < 1000)
+    delay(1);
+
+  // if it hasn't closed, close it forcefully
+  if (status() != SnSR::CLOSED)
+    close(_sock);
+
+  EthernetClass::_server_port[_sock] = 0;
+  _sock = MAX_SOCK_NUM;
+}
+
+uint8_t EthernetClient::connected() {
+  if (_sock == MAX_SOCK_NUM) return 0;
+  
+  uint8_t s = status();
+  return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
+    (s == SnSR::CLOSE_WAIT && !available()));
+}
+
+uint8_t EthernetClient::status() {
+  if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
+  return w5500.readSnSR(_sock);
+}
+
+// the next function allows us to use the client returned by
+// EthernetServer::available() as the condition in an if-statement.
+
+EthernetClient::operator bool() {
+  return _sock != MAX_SOCK_NUM;
+}
+
+bool EthernetClient::operator==(const EthernetClient& rhs) {
+  return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM;
+}

+ 39 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetClient.h

@@ -0,0 +1,39 @@
+#ifndef ethernetclient_h
+#define ethernetclient_h
+#include "Arduino.h"	
+#include "Print.h"
+#include "Client.h"
+#include "IPAddress.h"
+
+class EthernetClient : public Client {
+
+public:
+  EthernetClient();
+  EthernetClient(uint8_t sock);
+
+  uint8_t status();
+  virtual int connect(IPAddress ip, uint16_t port);
+  virtual int connect(const char *host, uint16_t port);
+  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();
+  virtual bool operator==(const EthernetClient&);
+  virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); };
+
+  friend class EthernetServer;
+  
+  using Print::write;
+
+private:
+  static uint16_t _srcport;
+  uint8_t _sock;
+};
+
+#endif

+ 91 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetServer.cpp

@@ -0,0 +1,91 @@
+#include "utility/w5500.h"
+#include "utility/socket.h"
+extern "C" {
+#include "string.h"
+}
+
+#include "Ethernet2.h"
+#include "EthernetClient.h"
+#include "EthernetServer.h"
+
+EthernetServer::EthernetServer(uint16_t port)
+{
+  _port = port;
+}
+
+void EthernetServer::begin()
+{
+  for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
+    EthernetClient client(sock);
+    if (client.status() == SnSR::CLOSED) {
+      socket(sock, SnMR::TCP, _port, 0);
+      listen(sock);
+      EthernetClass::_server_port[sock] = _port;
+      break;
+    }
+  }  
+}
+
+void EthernetServer::accept()
+{
+  int listening = 0;
+
+  for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
+    EthernetClient client(sock);
+
+    if (EthernetClass::_server_port[sock] == _port) {
+      if (client.status() == SnSR::LISTEN) {
+        listening = 1;
+      } 
+      else if (client.status() == SnSR::CLOSE_WAIT && !client.available()) {
+        client.stop();
+      }
+    } 
+  }
+
+  if (!listening) {
+    begin();
+  }
+}
+
+EthernetClient EthernetServer::available()
+{
+  accept();
+
+  for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
+    EthernetClient client(sock);
+    if (EthernetClass::_server_port[sock] == _port &&
+        (client.status() == SnSR::ESTABLISHED ||
+         client.status() == SnSR::CLOSE_WAIT)) {
+      if (client.available()) {
+        // XXX: don't always pick the lowest numbered socket.
+        return client;
+      }
+    }
+  }
+
+  return EthernetClient(MAX_SOCK_NUM);
+}
+
+size_t EthernetServer::write(uint8_t b) 
+{
+  return write(&b, 1);
+}
+
+size_t EthernetServer::write(const uint8_t *buffer, size_t size) 
+{
+  size_t n = 0;
+  
+  accept();
+
+  for (int sock = 0; sock < MAX_SOCK_NUM; sock++) {
+    EthernetClient client(sock);
+
+    if (EthernetClass::_server_port[sock] == _port &&
+      client.status() == SnSR::ESTABLISHED) {
+      n += client.write(buffer, size);
+    }
+  }
+  
+  return n;
+}

+ 22 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetServer.h

@@ -0,0 +1,22 @@
+#ifndef ethernetserver_h
+#define ethernetserver_h
+
+#include "Server.h"
+
+class EthernetClient;
+
+class EthernetServer : 
+public Server {
+private:
+  uint16_t _port;
+  void accept();
+public:
+  EthernetServer(uint16_t);
+  EthernetClient available();
+  virtual void begin();
+  virtual size_t write(uint8_t);
+  virtual size_t write(const uint8_t *buf, size_t size);
+  using Print::write;
+};
+
+#endif

+ 222 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetUdp2.cpp

@@ -0,0 +1,222 @@
+/*
+ *  Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
+ *  This version only offers minimal wrapping of socket.c/socket.h
+ *  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
+ *
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ */
+
+#include "utility/w5500.h"
+#include "utility/socket.h"
+#include "Ethernet2.h"
+#include "Udp.h"
+#include "Dns.h"
+
+/* Constructor */
+EthernetUDP::EthernetUDP() : _sock(MAX_SOCK_NUM) {}
+
+/* Start EthernetUDP socket, listening at local port PORT */
+uint8_t EthernetUDP::begin(uint16_t port) {
+  if (_sock != MAX_SOCK_NUM)
+    return 0;
+
+  for (int i = 0; i < MAX_SOCK_NUM; i++) {
+    uint8_t s = w5500.readSnSR(i);
+    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) {
+      _sock = i;
+      break;
+    }
+  }
+
+  if (_sock == MAX_SOCK_NUM)
+    return 0;
+
+  _port = port;
+  _remaining = 0;
+  socket(_sock, SnMR::UDP, _port, 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 (_sock == MAX_SOCK_NUM)
+    return;
+
+  close(_sock);
+
+  EthernetClass::_server_port[_sock] = 0;
+  _sock = 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 beginPacket(remote_addr, port);
+  } else {
+    return ret;
+  }
+}
+
+int EthernetUDP::beginPacket(IPAddress ip, uint16_t port)
+{
+  _offset = 0;
+  return startUDP(_sock, rawIPAddress(ip), port);
+}
+
+int EthernetUDP::endPacket()
+{
+  return sendUDP(_sock);
+}
+
+size_t EthernetUDP::write(uint8_t byte)
+{
+  return write(&byte, 1);
+}
+
+size_t EthernetUDP::write(const uint8_t *buffer, size_t size)
+{
+  uint16_t bytes_written = bufferData(_sock, _offset, buffer, size);
+  _offset += bytes_written;
+  return bytes_written;
+}
+
+int EthernetUDP::parsePacket()
+{
+  // discard any remaining bytes in the last packet
+  flush();
+
+  if (w5500.getRXReceivedSize(_sock) > 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 = recv(_sock,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) && (recv(_sock, &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 = recv(_sock, buffer, _remaining);
+    }
+    else
+    {
+      // too much data for the buffer, 
+      // grab as much as will fit
+      got = recv(_sock, buffer, len);
+    }
+
+    if (got > 0)
+    {
+      _remaining -= got;
+      return got;
+    }
+
+  }
+
+  // If we get here, there's no data available or recv failed
+  return -1;
+
+}
+
+int EthernetUDP::peek()
+{
+  uint8_t b;
+  // 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 (!_remaining)
+    return -1;
+  ::peek(_sock, &b);
+  return b;
+}
+
+void EthernetUDP::flush()
+{
+  // 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 w5500 always behaves :)
+
+  while (_remaining)
+  {
+    read();
+  }
+}
+

+ 105 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/EthernetUdp2.h

@@ -0,0 +1,105 @@
+/*
+ *  Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield.
+ *  This version only offers minimal wrapping of socket.c/socket.h
+ *  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
+ *
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ *
+ */
+ 
+
+#ifndef ethernetudp_h
+#define ethernetudp_h
+
+#include <Udp.h>
+
+#define UDP_TX_PACKET_MAX_SIZE 24
+
+class EthernetUDP : public UDP {
+private:
+  uint8_t _sock;  // socket ID for Wiz5100
+  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
+  uint16_t _remaining; // remaining bytes of incoming packet yet to be processed
+
+public:
+  EthernetUDP();  // 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 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; };
+};
+
+#endif

+ 91 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Twitter.cpp

@@ -0,0 +1,91 @@
+/*
+  Twitter.cpp - Arduino library to Post messages to Twitter using OAuth.
+  Copyright (c) NeoCat 2010-2011. All right reserved.
+  
+  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. 
+ */
+
+// ver1.2 - Use <string.h>
+// ver1.3 - Support IDE 1.0
+
+#include <string.h>
+#include "Twitter.h"
+
+#define LIB_DOMAIN "arduino-tweet.appspot.com"
+
+#if defined(ARDUINO) && ARDUINO < 100
+static uint8_t server[] = {0,0,0,0}; // IP address of LIB_DOMAIN
+Twitter::Twitter(const char *token) : client(server, 80), token(token)
+{
+}
+#else
+Twitter::Twitter(const char *token) : token(token)
+{
+}
+#endif
+
+bool Twitter::post(const char *msg)
+{
+#if defined(ARDUINO) && ARDUINO < 100
+	DNSError err = EthernetDNS.resolveHostName(LIB_DOMAIN, server);
+	if (err != DNSSuccess) {
+		return false;
+	}
+#endif
+	parseStatus = 0;
+	statusCode = 0;
+#if defined(ARDUINO) && ARDUINO < 100
+	if (client.connect()) {
+#else
+	if (client.connect(LIB_DOMAIN, 80)) {
+#endif
+		client.println("POST http://" LIB_DOMAIN "/update HTTP/1.0");
+		client.print("Content-Length: ");
+		client.println(strlen(msg)+strlen(token)+14);
+		client.println();
+		client.print("token=");
+		client.print(token);
+		client.print("&status=");
+		client.println(msg);
+	} else {
+		return false;
+	}
+	return true;
+}
+
+bool Twitter::checkStatus(Print *debug)
+{
+	if (!client.connected()) {
+		if (debug)
+			while(client.available())
+				debug->print((char)client.read());
+		client.flush();
+		client.stop();
+		return false;
+	}
+	if (!client.available())
+		return true;
+	char c = client.read();
+	if (debug)
+		debug->print(c);
+	switch(parseStatus) {
+	case 0:
+		if (c == ' ') parseStatus++; break;  // skip "HTTP/1.1 "
+	case 1:
+		if (c >= '0' && c <= '9') {
+			statusCode *= 10;
+			statusCode += c - '0';
+		} else {
+			parseStatus++;
+		}
+	}
+	return true;
+}
+
+int Twitter::wait(Print *debug)
+{
+	while (checkStatus(debug));
+	return statusCode;
+}

+ 49 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/Twitter.h

@@ -0,0 +1,49 @@
+/*
+  Twitter.cpp - Arduino library to Post messages to Twitter using OAuth.
+  Copyright (c) NeoCat 2010-2011. All right reserved.
+  
+  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. 
+ */
+
+// ver1.2 - Use <Udp.h> to support IDE 0019 or later
+// ver1.3 - Support IDE 1.0
+
+#ifndef TWITTER_H
+#define TWITTER_H
+
+#include <inttypes.h>
+#if defined(__AVR__) 
+#include <avr/pgmspace.h>
+#endif
+
+#if defined(ARDUINO) && ARDUINO > 18   // Arduino 0019 or later
+#include <SPI.h>
+#endif
+#include <Ethernet2.h>
+#if defined(ARDUINO) && ARDUINO < 100  // earlier than Arduino 1.0
+#include <EthernetDNS.h>
+#endif
+
+class Twitter
+{
+private:
+	uint8_t parseStatus;
+	int statusCode;
+	const char *token;
+#if defined(ARDUINO) && ARDUINO < 100
+	Client client;
+#else
+	EthernetClient client;
+#endif
+public:
+	Twitter(const char *user_and_passwd);
+	
+	bool post(const char *msg);
+	bool checkStatus(Print *debug = NULL);
+	int  wait(Print *debug = NULL);
+	int  status(void) { return statusCode; }
+};
+
+#endif	//TWITTER_H

+ 13 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/util.h

@@ -0,0 +1,13 @@
+#ifndef UTIL_H
+#define UTIL_H
+
+#define htons(x) ( ((x)<<8) | (((x)>>8)&0xFF) )
+#define ntohs(x) htons(x)
+
+#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
+                   ((x)<< 8 & 0x00FF0000UL) | \
+                   ((x)>> 8 & 0x0000FF00UL) | \
+                   ((x)>>24 & 0x000000FFUL) )
+#define ntohl(x) htonl(x)
+
+#endif

+ 412 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/socket.cpp

@@ -0,0 +1,412 @@
+ /*
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ */
+ 
+#include "utility/w5500.h"
+#include "utility/socket.h"
+
+static uint16_t local_port;
+
+/**
+ * @brief	This Socket function initialize the channel in perticular mode, and set the port and wait for w5500 done it.
+ * @return 	1 for success else 0.
+ */
+uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag)
+{
+  if ((protocol == SnMR::TCP) || (protocol == SnMR::UDP) || (protocol == SnMR::IPRAW) || (protocol == SnMR::MACRAW) || (protocol == SnMR::PPPOE))
+  {
+    close(s);
+    w5500.writeSnMR(s, protocol | flag);
+    if (port != 0) {
+      w5500.writeSnPORT(s, port);
+    } 
+    else {
+      local_port++; // if don't set the source port, set local_port number.
+      w5500.writeSnPORT(s, local_port);
+    }
+
+    w5500.execCmdSn(s, Sock_OPEN);
+    
+    return 1;
+  }
+
+  return 0;
+}
+
+
+/**
+ * @brief	This function close the socket and parameter is "s" which represent the socket number
+ */
+void close(SOCKET s)
+{
+  w5500.execCmdSn(s, Sock_CLOSE);
+  w5500.writeSnIR(s, 0xFF);
+}
+
+
+/**
+ * @brief	This function established  the connection for the channel in passive (server) mode. This function waits for the request from the peer.
+ * @return	1 for success else 0.
+ */
+uint8_t listen(SOCKET s)
+{
+  if (w5500.readSnSR(s) != SnSR::INIT)
+    return 0;
+  w5500.execCmdSn(s, Sock_LISTEN);
+  return 1;
+}
+
+
+/**
+ * @brief	This function established  the connection for the channel in Active (client) mode. 
+ * 		This function waits for the untill the connection is established.
+ * 		
+ * @return	1 for success else 0.
+ */
+uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port)
+{
+  if 
+    (
+  ((addr[0] == 0xFF) && (addr[1] == 0xFF) && (addr[2] == 0xFF) && (addr[3] == 0xFF)) ||
+    ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
+    (port == 0x00) 
+    ) 
+    return 0;
+
+  // set destination IP
+  w5500.writeSnDIPR(s, addr);
+  w5500.writeSnDPORT(s, port);
+  w5500.execCmdSn(s, Sock_CONNECT);
+
+  return 1;
+}
+
+
+
+/**
+ * @brief	This function used for disconnect the socket and parameter is "s" which represent the socket number
+ * @return	1 for success else 0.
+ */
+void disconnect(SOCKET s)
+{
+  w5500.execCmdSn(s, Sock_DISCON);
+}
+
+
+/**
+ * @brief	This function used to send the data in TCP mode
+ * @return	1 for success else 0.
+ */
+uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len)
+{
+  uint8_t status=0;
+  uint16_t ret=0;
+  uint16_t freesize=0;
+
+  if (len > w5500.SSIZE) 
+    ret = w5500.SSIZE; // check size not to exceed MAX size.
+  else 
+    ret = len;
+
+  // if freebuf is available, start.
+  do 
+  {
+    freesize = w5500.getTXFreeSize(s);
+    status = w5500.readSnSR(s);
+    if ((status != SnSR::ESTABLISHED) && (status != SnSR::CLOSE_WAIT))
+    {
+      ret = 0; 
+      break;
+    }
+  } 
+  while (freesize < ret);
+
+  // copy data
+  w5500.send_data_processing(s, (uint8_t *)buf, ret);
+  w5500.execCmdSn(s, Sock_SEND);
+
+  /* +2008.01 bj */
+  while ( (w5500.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) 
+  {
+    /* m2008.01 [bj] : reduce code */
+    if ( w5500.readSnSR(s) == SnSR::CLOSED )
+    {
+      close(s);
+      return 0;
+    }
+  }
+  /* +2008.01 bj */
+  w5500.writeSnIR(s, SnIR::SEND_OK);
+  return ret;
+}
+
+
+/**
+ * @brief	This function is an application I/F function which is used to receive the data in TCP mode.
+ * 		It continues to wait for data as much as the application wants to receive.
+ * 		
+ * @return	received data size for success else -1.
+ */
+int16_t recv(SOCKET s, uint8_t *buf, int16_t len)
+{
+  // Check how much data is available
+  int16_t ret = w5500.getRXReceivedSize(s);
+  if ( ret == 0 )
+  {
+    // No data available.
+    uint8_t status = w5500.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;
+  }
+
+  if ( ret > 0 )
+  {
+    w5500.recv_data_processing(s, buf, ret);
+    w5500.execCmdSn(s, Sock_RECV);
+  }
+  return ret;
+}
+
+
+/**
+ * @brief	Returns the first byte in the receive queue (no checking)
+ * 		
+ * @return
+ */
+uint16_t peek(SOCKET s, uint8_t *buf)
+{
+  w5500.recv_data_processing(s, buf, 1, 1);
+
+  return 1;
+}
+
+
+/**
+ * @brief	This function is an application I/F function which is used to send the data for other then TCP mode. 
+ * 		Unlike TCP transmission, The peer's destination address and the port is needed.
+ * 		
+ * @return	This function return send data size for success else -1.
+ */
+uint16_t sendto(SOCKET s, const uint8_t *buf, uint16_t len, uint8_t *addr, uint16_t port)
+{
+  uint16_t ret=0;
+
+  if (len > w5500.SSIZE) ret = w5500.SSIZE; // check size not to exceed MAX size.
+  else ret = len;
+
+  if
+    (
+  ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
+    ((port == 0x00)) ||(ret == 0)
+    ) 
+  {
+    /* +2008.01 [bj] : added return value */
+    ret = 0;
+  }
+  else
+  {
+    w5500.writeSnDIPR(s, addr);
+    w5500.writeSnDPORT(s, port);
+
+    // copy data
+    w5500.send_data_processing(s, (uint8_t *)buf, ret);
+    w5500.execCmdSn(s, Sock_SEND);
+
+    /* +2008.01 bj */
+    while ( (w5500.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) 
+    {
+      if (w5500.readSnIR(s) & SnIR::TIMEOUT)
+      {
+        /* +2008.01 [bj]: clear interrupt */
+        w5500.writeSnIR(s, (SnIR::SEND_OK | SnIR::TIMEOUT)); /* clear SEND_OK & TIMEOUT */
+        return 0;
+      }
+    }
+
+    /* +2008.01 bj */
+    w5500.writeSnIR(s, SnIR::SEND_OK);
+  }
+  return ret;
+}
+
+
+/**
+ * @brief	This function is an application I/F function which is used to receive the data in other then
+ * 	TCP mode. This function is used to receive UDP, IP_RAW and MAC_RAW mode, and handle the header as well. 
+ * 	
+ * @return	This function return received data size for success else -1.
+ */
+uint16_t recvfrom(SOCKET s, uint8_t *buf, uint16_t len, uint8_t *addr, uint16_t *port)
+{
+  uint8_t head[8];
+  uint16_t data_len=0;
+  uint16_t ptr=0;
+
+  if ( len > 0 )
+  {
+    ptr = w5500.readSnRX_RD(s);
+    switch (w5500.readSnMR(s) & 0x07)
+    {
+    case SnMR::UDP :
+      w5500.read_data(s, ptr, head, 0x08);
+      ptr += 8;
+      // read peer's IP address, port number.
+      addr[0] = head[0];
+      addr[1] = head[1];
+      addr[2] = head[2];
+      addr[3] = head[3];
+      *port = head[4];
+      *port = (*port << 8) + head[5];
+      data_len = head[6];
+      data_len = (data_len << 8) + head[7];
+
+      w5500.read_data(s, ptr, buf, data_len); // data copy.
+      ptr += data_len;
+
+      w5500.writeSnRX_RD(s, ptr);
+      break;
+
+    case SnMR::IPRAW :
+      w5500.read_data(s, ptr, head, 0x06);
+      ptr += 6;
+
+      addr[0] = head[0];
+      addr[1] = head[1];
+      addr[2] = head[2];
+      addr[3] = head[3];
+      data_len = head[4];
+      data_len = (data_len << 8) + head[5];
+
+      w5500.read_data(s, ptr, buf, data_len); // data copy.
+      ptr += data_len;
+
+      w5500.writeSnRX_RD(s, ptr);
+      break;
+
+    case SnMR::MACRAW:
+      w5500.read_data(s, ptr, head, 2);
+      ptr+=2;
+      data_len = head[0];
+      data_len = (data_len<<8) + head[1] - 2;
+
+      w5500.read_data(s, ptr, buf, data_len);
+      ptr += data_len;
+      w5500.writeSnRX_RD(s, ptr);
+      break;
+
+    default :
+      break;
+    }
+    w5500.execCmdSn(s, Sock_RECV);
+  }
+  return data_len;
+}
+
+/**
+ * @brief	Wait for buffered transmission to complete.
+ */
+void flush(SOCKET s) {
+  // TODO
+}
+
+uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len)
+{
+  uint8_t status=0;
+  uint16_t ret=0;
+
+  if (len > w5500.SSIZE) 
+    ret = w5500.SSIZE; // check size not to exceed MAX size.
+  else 
+    ret = len;
+
+  if (ret == 0)
+    return 0;
+
+  w5500.send_data_processing(s, (uint8_t *)buf, ret);
+  w5500.execCmdSn(s, Sock_SEND);
+
+  while ( (w5500.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) 
+  {
+    status = w5500.readSnSR(s);
+    if (w5500.readSnIR(s) & SnIR::TIMEOUT)
+    {
+      /* in case of igmp, if send fails, then socket closed */
+      /* if you want change, remove this code. */
+      close(s);
+      return 0;
+    }
+  }
+
+  w5500.writeSnIR(s, SnIR::SEND_OK);
+  return ret;
+}
+
+uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len)
+{
+  uint16_t ret =0;
+  if (len > w5500.getTXFreeSize(s))
+  {
+    ret = w5500.getTXFreeSize(s); // check size not to exceed MAX size.
+  }
+  else
+  {
+    ret = len;
+  }
+  w5500.send_data_processing_offset(s, offset, buf, ret);
+  return ret;
+}
+
+int startUDP(SOCKET s, uint8_t* addr, uint16_t port)
+{
+  if
+    (
+     ((addr[0] == 0x00) && (addr[1] == 0x00) && (addr[2] == 0x00) && (addr[3] == 0x00)) ||
+     ((port == 0x00))
+    ) 
+  {
+    return 0;
+  }
+  else
+  {
+    w5500.writeSnDIPR(s, addr);
+    w5500.writeSnDPORT(s, port);
+    return 1;
+  }
+}
+
+int sendUDP(SOCKET s)
+{
+  w5500.execCmdSn(s, Sock_SEND);
+		
+  /* +2008.01 bj */
+  while ( (w5500.readSnIR(s) & SnIR::SEND_OK) != SnIR::SEND_OK ) 
+  {
+    if (w5500.readSnIR(s) & SnIR::TIMEOUT)
+    {
+      /* +2008.01 [bj]: clear interrupt */
+      w5500.writeSnIR(s, (SnIR::SEND_OK|SnIR::TIMEOUT));
+      return 0;
+    }
+  }
+
+  /* +2008.01 bj */	
+  w5500.writeSnIR(s, SnIR::SEND_OK);
+
+  /* Sent ok */
+  return 1;
+}
+

+ 48 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/socket.h

@@ -0,0 +1,48 @@
+ /*
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ */
+ 
+#ifndef	_SOCKET_H_
+#define	_SOCKET_H_
+
+#include "utility/w5500.h"
+
+extern uint8_t socket(SOCKET s, uint8_t protocol, uint16_t port, uint8_t flag); // Opens a socket(TCP or UDP or IP_RAW mode)
+extern void close(SOCKET s); // Close socket
+extern uint8_t connect(SOCKET s, uint8_t * addr, uint16_t port); // Establish TCP connection (Active connection)
+extern void disconnect(SOCKET s); // disconnect the connection
+extern uint8_t listen(SOCKET s);	// Establish TCP connection (Passive connection)
+extern uint16_t send(SOCKET s, const uint8_t * buf, uint16_t len); // Send data (TCP)
+extern int16_t recv(SOCKET s, uint8_t * buf, int16_t len);	// Receive data (TCP)
+extern uint16_t peek(SOCKET s, uint8_t *buf);
+extern uint16_t sendto(SOCKET s, const uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t port); // Send data (UDP/IP RAW)
+extern uint16_t recvfrom(SOCKET s, uint8_t * buf, uint16_t len, uint8_t * addr, uint16_t *port); // Receive data (UDP/IP RAW)
+extern void flush(SOCKET s); // Wait for transmission to complete
+
+extern uint16_t igmpsend(SOCKET s, const uint8_t * buf, uint16_t len);
+
+// Functions to allow buffered UDP send (i.e. where the UDP datagram is built up over a
+// number of calls before being sent
+/*
+  @brief This function 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 1 if the datagram was successfully set up, or 0 if there was an error
+*/
+extern int startUDP(SOCKET s, uint8_t* addr, uint16_t port);
+/*
+  @brief This function copies 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
+*/
+uint16_t bufferData(SOCKET s, uint16_t offset, const uint8_t* buf, uint16_t len);
+/*
+  @brief Send a UDP datagram built up from a sequence of startUDP followed by one or more
+  calls to bufferData.
+  @return 1 if the datagram was successfully sent, or 0 if there was an error
+*/
+int sendUDP(SOCKET s);
+
+#endif
+/* _SOCKET_H_ */

+ 14 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/util.h

@@ -0,0 +1,14 @@
+#ifndef UTIL_H
+#define UTIL_H
+
+#define htons(x) ( ((x)<< 8 & 0xFF00) | \
+                   ((x)>> 8 & 0x00FF) )
+#define ntohs(x) htons(x)
+
+#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
+                   ((x)<< 8 & 0x00FF0000UL) | \
+                   ((x)>> 8 & 0x0000FF00UL) | \
+                   ((x)>>24 & 0x000000FFUL) )
+#define ntohl(x) htonl(x)
+
+#endif

+ 187 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/w5500.cpp

@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2010 by WIZnet <support@wiznet.co.kr>
+ *
+ * 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.
+ *
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include "Arduino.h"
+
+#include "utility/w5500.h"
+//#if defined(W5500_ETHERNET_SHIELD)
+
+// W5500 controller instance
+W5500Class w5500;
+
+// SPI details
+SPISettings wiznet_SPI_settings(8000000, MSBFIRST, SPI_MODE0);
+uint8_t SPI_CS;
+
+void W5500Class::init(uint8_t ss_pin)
+{
+  SPI_CS = ss_pin;
+
+  delay(1000);
+  initSS();
+  SPI.begin();
+  w5500.swReset();
+  for (int i=0; i<MAX_SOCK_NUM; i++) {
+    uint8_t cntl_byte = (0x0C + (i<<5));
+    write( 0x1E, cntl_byte, 2); //0x1E - Sn_RXBUF_SIZE
+    write( 0x1F, cntl_byte, 2); //0x1F - Sn_TXBUF_SIZE
+  }
+}
+
+uint16_t W5500Class::getTXFreeSize(SOCKET s)
+{
+    uint16_t val=0, val1=0;
+    do {
+        val1 = readSnTX_FSR(s);
+        if (val1 != 0)
+            val = readSnTX_FSR(s);
+    } 
+    while (val != val1);
+    return val;
+}
+
+uint16_t W5500Class::getRXReceivedSize(SOCKET s)
+{
+    uint16_t val=0,val1=0;
+    do {
+        val1 = readSnRX_RSR(s);
+        if (val1 != 0)
+            val = readSnRX_RSR(s);
+    } 
+    while (val != val1);
+    return val;
+}
+
+void W5500Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len)
+{
+  // This is same as having no offset in a call to send_data_processing_offset
+  send_data_processing_offset(s, 0, data, len);
+
+}
+
+void W5500Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len)
+{
+    uint16_t ptr = readSnTX_WR(s);
+    uint8_t cntl_byte = (0x14+(s<<5));
+    ptr += data_offset;
+    write(ptr, cntl_byte, data, len);
+    ptr += len;
+    writeSnTX_WR(s, ptr);
+}
+
+void W5500Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek)
+{
+    uint16_t ptr;
+    ptr = readSnRX_RD(s);
+
+    read_data(s, ptr, data, len);
+    if (!peek)
+    {
+        ptr += len;
+        writeSnRX_RD(s, ptr);
+    }
+}
+
+void W5500Class::read_data(SOCKET s, volatile uint16_t src, volatile uint8_t *dst, uint16_t len)
+{
+    uint8_t cntl_byte = (0x18+(s<<5));
+    read((uint16_t)src , cntl_byte, (uint8_t *)dst, len);
+}
+
+uint8_t W5500Class::write(uint16_t _addr, uint8_t _cb, uint8_t _data)
+{
+    SPI.beginTransaction(wiznet_SPI_settings);
+    setSS();  
+    SPI.transfer(_addr >> 8);
+    SPI.transfer(_addr & 0xFF);
+    SPI.transfer(_cb);
+    SPI.transfer(_data);
+    resetSS();
+    SPI.endTransaction();
+
+    return 1;
+}
+
+uint16_t W5500Class::write(uint16_t _addr, uint8_t _cb, const uint8_t *_buf, uint16_t _len)
+{
+    SPI.beginTransaction(wiznet_SPI_settings);
+    setSS();
+    SPI.transfer(_addr >> 8);
+    SPI.transfer(_addr & 0xFF);
+    SPI.transfer(_cb);
+    for (uint16_t i=0; i<_len; i++){
+        SPI.transfer(_buf[i]);
+    }
+    resetSS();
+    SPI.endTransaction();
+
+    return _len;
+}
+
+uint8_t W5500Class::read(uint16_t _addr, uint8_t _cb)
+{
+    SPI.beginTransaction(wiznet_SPI_settings);
+    setSS();
+    SPI.transfer(_addr >> 8);
+    SPI.transfer(_addr & 0xFF);
+    SPI.transfer(_cb);
+    uint8_t _data = SPI.transfer(0);
+    resetSS();
+    SPI.endTransaction();
+
+    return _data;
+}
+
+uint16_t W5500Class::read(uint16_t _addr, uint8_t _cb, uint8_t *_buf, uint16_t _len)
+{ 
+    SPI.beginTransaction(wiznet_SPI_settings);
+    setSS();
+    SPI.transfer(_addr >> 8);
+    SPI.transfer(_addr & 0xFF);
+    SPI.transfer(_cb);
+    for (uint16_t i=0; i<_len; i++){
+        _buf[i] = SPI.transfer(0);
+    }
+    resetSS();
+    SPI.endTransaction();
+
+    return _len;
+}
+
+void W5500Class::execCmdSn(SOCKET s, SockCMD _cmd) {
+    // Send command to socket
+    writeSnCR(s, _cmd);
+    // Wait for command to complete
+    while (readSnCR(s))
+    ;
+}
+
+
+uint8_t W5500Class::readVersion(void)
+{
+    SPI.beginTransaction(wiznet_SPI_settings);
+    setSS();
+    SPI.transfer( 0x00 );
+    SPI.transfer( 0x39 );
+    SPI.transfer( 0x01);
+    uint8_t _data = SPI.transfer(0);
+    resetSS();
+    SPI.endTransaction();
+
+    return _data;
+}
+
+
+//#endif

+ 420 - 0
SE/stuff/P5_Automation-library-dev/Ethernet2/src/utility/w5500.h

@@ -0,0 +1,420 @@
+/*
+* Copyright (c) 2010 by WIZnet <support@wiznet.co.kr>
+ *
+ * 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.
+ *
+ * - 10 Apr. 2015
+ * Added support for Arduino Ethernet Shield 2
+ * by Arduino.org team
+ */
+
+#ifndef	W5500_H_INCLUDED
+#define	W5500_H_INCLUDED
+
+#define MAX_SOCK_NUM 8
+#include <Arduino.h>
+#include <SPI.h>
+
+extern uint8_t SPI_CS;
+
+
+typedef uint8_t SOCKET;
+/*
+class MR {
+public:
+  static const uint8_t RST   = 0x80;
+  static const uint8_t PB    = 0x10;
+  static const uint8_t PPPOE = 0x08;
+  static const uint8_t LB    = 0x04;
+  static const uint8_t AI    = 0x02;
+  static const uint8_t IND   = 0x01;
+};
+*/
+/*
+class IR {
+public:
+  static const uint8_t CONFLICT = 0x80;
+  static const uint8_t UNREACH  = 0x40;
+  static const uint8_t PPPoE    = 0x20;
+  static const uint8_t SOCK0    = 0x01;
+  static const uint8_t SOCK1    = 0x02;
+  static const uint8_t SOCK2    = 0x04;
+  static const uint8_t SOCK3    = 0x08;
+  static inline uint8_t SOCK(SOCKET ch) { return (0x01 << ch); };
+};
+*/
+
+class SnMR {
+public:
+  static const uint8_t CLOSE  = 0x00;
+  static const uint8_t TCP    = 0x01;
+  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 SnCmd {
+public:
+  static const uint8_t OPEN      = 0x01;
+  static const uint8_t LISTEN    = 0x02;
+  static const uint8_t CONNECT   = 0x04;
+  static const uint8_t DISCON    = 0x08;
+  static const uint8_t CLOSE     = 0x10;
+  static const uint8_t SEND      = 0x20;
+  static const uint8_t SEND_MAC  = 0x21;
+  static const uint8_t SEND_KEEP = 0x22;
+  static const uint8_t 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;
+};
+
+class W5500Class {
+
+public:
+  void init(uint8_t ss_pin = 10);
+  uint8_t readVersion(void);
+
+  /**
+   * @brief	This function is being used for copy the data form Receive buffer of the chip to application buffer.
+   * 
+   * It calculate the actual physical address where one has to read
+   * the data from Receive buffer. Here also take care of the condition while it exceed
+   * the Rx memory uper-bound of socket.
+   */
+  void read_data(SOCKET s, volatile uint16_t  src, volatile uint8_t * dst, uint16_t len);
+  
+  /**
+   * @brief	 This function is being called by send() and sendto() function also. 
+   * 
+   * This function read the Tx write pointer register and after copy the data in buffer update the Tx write pointer
+   * register. User should read upper byte first and lower byte later to get proper value.
+   */
+  void send_data_processing(SOCKET s, const uint8_t *data, uint16_t len);
+  /**
+   * @brief A copy of send_data_processing that uses the provided ptr for the
+   *        write offset.  Only needed for the "streaming" UDP API, where
+   *        a single UDP packet is built up over a number of calls to
+   *        send_data_processing_ptr, because TX_WR doesn't seem to get updated
+   *        correctly in those scenarios
+   * @param ptr value to use in place of TX_WR.  If 0, then the value is read
+   *        in from TX_WR
+   * @return New value for ptr, to be used in the next call
+   */
+  // FIXME Update documentation
+  void send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len);
+
+  /**
+   * @brief	This function is being called by recv() also.
+   * 
+   * This function read the Rx read pointer register
+   * and after copy the data from receive buffer update the Rx write pointer register.
+   * User should read upper byte first and lower byte later to get proper value.
+   */
+  void recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek = 0);
+
+  inline void setGatewayIp(uint8_t *_addr);
+  inline void getGatewayIp(uint8_t *_addr);
+
+  inline void setSubnetMask(uint8_t *_addr);
+  inline void getSubnetMask(uint8_t *_addr);
+
+  inline void setMACAddress(uint8_t * addr);
+  inline void getMACAddress(uint8_t * addr);
+
+  inline void setIPAddress(uint8_t * addr);
+  inline void getIPAddress(uint8_t * addr);
+
+  inline void setRetransmissionTime(uint16_t timeout);
+  inline void setRetransmissionCount(uint8_t _retry);
+
+  inline void swReset();
+
+  inline void setPHYCFGR(uint8_t _val);
+  inline uint8_t getPHYCFGR();
+
+  void execCmdSn(SOCKET s, SockCMD _cmd);
+  
+  uint16_t getTXFreeSize(SOCKET s);
+  uint16_t getRXReceivedSize(SOCKET s);
+  
+
+  // W5500 Registers
+  // ---------------
+private:
+  static uint8_t  write(uint16_t _addr, uint8_t _cb, uint8_t _data);
+  static uint16_t write(uint16_t _addr, uint8_t _cb, const uint8_t *buf, uint16_t len);
+  static uint8_t  read(uint16_t _addr, uint8_t _cb );
+  static uint16_t read(uint16_t _addr, uint8_t _cb, uint8_t *buf, uint16_t len);
+  
+#define __GP_REGISTER8(name, address)             \
+  static inline void write##name(uint8_t _data) { \
+    write(address, 0x04, _data);                  \
+  }                                               \
+  static inline uint8_t read##name() {            \
+    return read(address, 0x00);                   \
+  }
+#define __GP_REGISTER16(name, address)            \
+  static void write##name(uint16_t _data) {       \
+    write(address,  0x04, _data >> 8);            \
+    write(address+1, 0x04, _data & 0xFF);         \
+  }                                               \
+  static uint16_t read##name() {                  \
+    uint16_t res = read(address, 0x00);           \
+    res = (res << 8) + read(address + 1, 0x00);   \
+    return res;                                   \
+  }
+#define __GP_REGISTER_N(name, address, size)      \
+  static uint16_t write##name(uint8_t *_buff) {   \
+    return write(address, 0x04, _buff, size);     \
+  }                                               \
+  static uint16_t read##name(uint8_t *_buff) {    \
+    return read(address, 0x00, _buff, size);      \
+  }
+
+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,    0x0019);    // Timeout address
+  __GP_REGISTER8 (RCR,    0x001B);    // Retry count
+  __GP_REGISTER_N(UIPR,   0x0028, 4); // Unreachable IP address in UDP mode
+  __GP_REGISTER16(UPORT,  0x002C);    // Unreachable Port address in UDP mode
+  __GP_REGISTER8 (PHYCFGR,     0x002E);    // PHY Configuration register, default value: 0b 1011 1xxx
+
+  
+#undef __GP_REGISTER8
+#undef __GP_REGISTER16
+#undef __GP_REGISTER_N
+
+  // W5500 Socket registers
+  // ----------------------
+private:
+  static inline uint8_t readSn(SOCKET _s, uint16_t _addr);
+  static inline uint8_t writeSn(SOCKET _s, uint16_t _addr, uint8_t _data);
+  static inline uint16_t readSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t len);
+  static inline uint16_t writeSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t len);
+
+  //static const uint16_t CH_BASE = 0x0000;
+  //static const uint16_t CH_SIZE = 0x0000;
+
+#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);                              \
+  }
+#if defined(REL_GR_KURUMI) || defined(REL_GR_KURUMI_PROTOTYPE)  
+#define __SOCKET_REGISTER16(name, address)                   \
+  static void write##name(SOCKET _s, uint16_t _data) {       \
+    writeSn(_s, address,   _data >> 8);                      \
+    writeSn(_s, address+1, _data & 0xFF);                    \
+  }                                                          \
+  static uint16_t read##name(SOCKET _s) {                    \
+    uint16_t res = readSn(_s, address);                      \
+    uint16_t res2 = readSn(_s,address + 1);                  \
+    res = res << 8;                                          \
+    res2 = res2 & 0xFF;                                      \
+    res = res | res2;                                        \
+    return res;                                              \
+  }
+#else
+#define __SOCKET_REGISTER16(name, address)                   \
+  static void write##name(SOCKET _s, uint16_t _data) {       \
+    writeSn(_s, address,   _data >> 8);                      \
+    writeSn(_s, address+1, _data & 0xFF);                    \
+  }                                                          \
+  static uint16_t read##name(SOCKET _s) {                    \
+    uint16_t res = readSn(_s, address);                      \
+    res = (res << 8) + readSn(_s, address + 1);              \
+    return res;                                              \
+  }
+#endif  
+#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_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 const uint8_t  RST = 7; // Reset BIT
+  static const int SOCKETS = 8;
+
+public:
+  static const uint16_t SSIZE = 2048; // Max Tx buffer size
+private:
+  static const uint16_t RSIZE = 2048; // Max Rx buffer size
+
+private:
+  // could do inline optimizations
+  static inline void initSS()  { pinMode(SPI_CS, OUTPUT); }
+  static inline void setSS()   {  digitalWrite(SPI_CS, LOW); }
+  static inline void resetSS() {  digitalWrite(SPI_CS, HIGH); }
+};
+
+extern W5500Class w5500;
+
+uint8_t W5500Class::readSn(SOCKET _s, uint16_t _addr) {
+    uint8_t cntl_byte = (_s<<5)+0x08;
+    return read(_addr, cntl_byte);
+}
+
+uint8_t W5500Class::writeSn(SOCKET _s, uint16_t _addr, uint8_t _data) {
+    uint8_t cntl_byte = (_s<<5)+0x0C;
+    return write(_addr, cntl_byte, _data);
+}
+
+uint16_t W5500Class::readSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t _len) {
+    uint8_t cntl_byte = (_s<<5)+0x08;
+    return read(_addr, cntl_byte, _buf, _len );
+}
+
+uint16_t W5500Class::writeSn(SOCKET _s, uint16_t _addr, uint8_t *_buf, uint16_t _len) {
+    uint8_t cntl_byte = (_s<<5)+0x0C;
+    return write(_addr, cntl_byte, _buf, _len);
+}
+
+void W5500Class::getGatewayIp(uint8_t *_addr) {
+  readGAR(_addr);
+}
+
+void W5500Class::setGatewayIp(uint8_t *_addr) {
+  writeGAR(_addr);
+}
+
+void W5500Class::getSubnetMask(uint8_t *_addr) {
+  readSUBR(_addr);
+}
+
+void W5500Class::setSubnetMask(uint8_t *_addr) {
+  writeSUBR(_addr);
+}
+
+void W5500Class::getMACAddress(uint8_t *_addr) {
+  readSHAR(_addr);
+}
+
+void W5500Class::setMACAddress(uint8_t *_addr) {
+  writeSHAR(_addr);
+}
+
+void W5500Class::getIPAddress(uint8_t *_addr) {
+  readSIPR(_addr);
+}
+
+void W5500Class::setIPAddress(uint8_t *_addr) {
+  writeSIPR(_addr);
+}
+
+void W5500Class::setRetransmissionTime(uint16_t _timeout) {
+  writeRTR(_timeout);
+}
+
+void W5500Class::setRetransmissionCount(uint8_t _retry) {
+  writeRCR(_retry);
+}
+
+void W5500Class::setPHYCFGR(uint8_t _val) {
+  writePHYCFGR(_val);
+}
+
+uint8_t W5500Class::getPHYCFGR() {
+//  readPHYCFGR();
+  return read(0x002E, 0x00);
+}
+
+void W5500Class::swReset() {
+  writeMR( (readMR() | 0x80) );
+}
+
+#endif

BIN
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/MCP2515Calc.xlsx


+ 39 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/README.md

@@ -0,0 +1,39 @@
+MCP_CAN Library for Arduino
+==============
+MCP_CAN library v1.5
+This library is compatible with any shield or board that uses the MCP2515 or MCP25625 CAN protocol controller.
+
+This version supports setting the ID filter mode of the protocol controller, the BAUD rate with clock speed with the begin() function.  Baudrates 5k, 10k, 20k, 50k, 100k, 125k, 250k, 500k, & 1000k using 16MHz clock on the MCP2515 are confirmed to work using a Peak-System PCAN-USB dongle as a reference.  Baudrates for 8MHz and 20MHz crystals are yet to be confirmed but were calculated appropiately.
+
+**The readMsgBuf() functions bring in the message ID. The getCanId() function is obsolete and no longer exists, don't use it.**
+
+The readMsgBuf(*ID, *DLC, *DATA) function will return the ID type (extended or standard) and it will bring back the remote request status bit.  
+If the ID AND 0x80000000 EQUALS 0x80000000, the ID is of the Extended type, otherwise it is standard.  
+If the ID AND 0x40000000 EQUALS 0x40000000, the message is a remote request.  
+
+The readMsgBuf(*ID, *EXT, *DLC, *DATA) function will return the ID unaltered and doesn't inform us of a remote request.  
+If EXT is true, the ID is extended.  
+  
+The sendMsgBuf(ID, DLC, DATA) function can send extended or standard IDs.  
+To mark an ID as extended, OR the ID with 0x80000000.    
+To send a remote request, OR the ID with 0x40000000.  
+  
+The sendMsgBuf(ID, EXT, DLC, DATA) has not changed other than fixing return values.  
+
+Using the setMode() function the sketch can now put the protocol controller into sleep, loop-back, or listen-only modes as well as normal operation.  Right now the code defaults to loop-back mode after the begin() function runs.  I have found this to increase the stability of filtering when the controller is initialized while connected to an active bus.
+
+User can enable and disable (default) One-Shot transmission mode from the sketch using enOneShotTX() or disOneShotTX() respectively.
+
+Installation
+==============
+Copy this into the "[.../MySketches/]libraries/" folder and restart the Arduino editor.
+
+NOTE: If an older version of the library exists (e.g. CAN_BUS_Shield) be sure to remove it from the libraries folder or replace the files with those in this library to avoid conflicts.
+
+
+Help and Support
+==============
+This is primarily for non-bug related issues: Please start a *new thread* in an appropriate area at Seeedstudio forums or Arduino.cc forums and then send me (coryjfowler) a link through the PM system, my user name is the same as it is here.  I will receive an email about the PM and generally get to it with-in a week or less.  Keep in mind, I do this in my spare time.
+
+
+*Happy Coding!*

+ 88 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_loopback/CAN_loopback.ino

@@ -0,0 +1,88 @@
+/* CAN Loopback Example
+ * This example sends a message once a second and receives that message
+ *   no CAN bus is required.  This example will test the functionality 
+ *   of the protocol controller, and connections to it.
+ *   
+ *   Written By: Cory J. Fowler - October 5th 2016
+ */
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+// CAN TX Variables
+unsigned long prevTX = 0;                                        // Variable to store last execution time
+const unsigned int invlTX = 1000;                                // One second interval constant
+byte data[] = {0xAA, 0x55, 0x01, 0x10, 0xFF, 0x12, 0x34, 0x56};  // Generic CAN data to send
+
+// CAN RX Variables
+long unsigned int rxId;
+unsigned char len;
+unsigned char rxBuf[8];
+
+// Serial Output String Buffer
+char msgString[128];
+
+// CAN0 INT and CS
+#define CAN0_INT 2                              // Set INT to pin 2
+MCP_CAN CAN0(10);                               // Set CS to pin 10
+
+
+void setup()
+{
+  Serial.begin(115200);  // CAN is running at 500,000BPS; 115,200BPS is SLOW, not FAST, thus 9600 is crippling.
+  
+  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
+  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
+    Serial.println("MCP2515 Initialized Successfully!");
+  else
+    Serial.println("Error Initializing MCP2515...");
+  
+  // Since we do not set NORMAL mode, we are in loopback mode by default.
+  //CAN0.setMode(MCP_NORMAL);
+
+  pinMode(CAN0_INT, INPUT);                           // Configuring pin for /INT input
+  
+  Serial.println("MCP2515 Library Loopback Example...");
+}
+
+void loop()
+{
+  if(!digitalRead(CAN0_INT))                          // If CAN0_INT pin is low, read receive buffer
+  {
+    CAN0.readMsgBuf(&rxId, &len, rxBuf);              // Read data: len = data length, buf = data byte(s)
+    
+    if((rxId & 0x80000000) == 0x80000000)             // Determine if ID is standard (11 bits) or extended (29 bits)
+      sprintf(msgString, "Extended ID: 0x%.8lX  DLC: %1d  Data:", (rxId & 0x1FFFFFFF), len);
+    else
+      sprintf(msgString, "Standard ID: 0x%.3lX       DLC: %1d  Data:", rxId, len);
+  
+    Serial.print(msgString);
+  
+    if((rxId & 0x40000000) == 0x40000000){            // Determine if message is a remote request frame.
+      sprintf(msgString, " REMOTE REQUEST FRAME");
+      Serial.print(msgString);
+    } else {
+      for(byte i = 0; i<len; i++){
+        sprintf(msgString, " 0x%.2X", rxBuf[i]);
+        Serial.print(msgString);
+      }
+    }
+        
+    Serial.println();
+  }
+  
+  if(millis() - prevTX >= invlTX){                    // Send this at a one second interval. 
+    prevTX = millis();
+    byte sndStat = CAN0.sendMsgBuf(0x100, 8, data);
+    
+    if(sndStat == CAN_OK)
+      Serial.println("Message Sent Successfully!");
+    else
+      Serial.println("Error Sending Message...");
+
+  }
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 62 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_receive/CAN_receive.ino

@@ -0,0 +1,62 @@
+// CAN Receive Example
+//
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+long unsigned int rxId;
+unsigned char len = 0;
+unsigned char rxBuf[8];
+char msgString[128];                        // Array to store serial string
+
+#define CAN0_INT 2                              // Set INT to pin 2
+MCP_CAN CAN0(10);                               // Set CS to pin 10
+
+
+void setup()
+{
+  Serial.begin(115200);
+  
+  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
+  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
+    Serial.println("MCP2515 Initialized Successfully!");
+  else
+    Serial.println("Error Initializing MCP2515...");
+  
+  CAN0.setMode(MCP_NORMAL);                     // Set operation mode to normal so the MCP2515 sends acks to received data.
+
+  pinMode(CAN0_INT, INPUT);                            // Configuring pin for /INT input
+  
+  Serial.println("MCP2515 Library Receive Example...");
+}
+
+void loop()
+{
+  if(!digitalRead(CAN0_INT))                         // If CAN0_INT pin is low, read receive buffer
+  {
+    CAN0.readMsgBuf(&rxId, &len, rxBuf);      // Read data: len = data length, buf = data byte(s)
+    
+    if((rxId & 0x80000000) == 0x80000000)     // Determine if ID is standard (11 bits) or extended (29 bits)
+      sprintf(msgString, "Extended ID: 0x%.8lX  DLC: %1d  Data:", (rxId & 0x1FFFFFFF), len);
+    else
+      sprintf(msgString, "Standard ID: 0x%.3lX       DLC: %1d  Data:", rxId, len);
+  
+    Serial.print(msgString);
+  
+    if((rxId & 0x40000000) == 0x40000000){    // Determine if message is a remote request frame.
+      sprintf(msgString, " REMOTE REQUEST FRAME");
+      Serial.print(msgString);
+    } else {
+      for(byte i = 0; i<len; i++){
+        sprintf(msgString, " 0x%.2X", rxBuf[i]);
+        Serial.print(msgString);
+      }
+    }
+        
+    Serial.println();
+  }
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 36 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_send/CAN_send.ino

@@ -0,0 +1,36 @@
+// CAN Send Example
+//
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+MCP_CAN CAN0(10);     // Set CS to pin 10
+
+void setup()
+{
+  Serial.begin(115200);
+
+  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
+  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.println("MCP2515 Initialized Successfully!");
+  else Serial.println("Error Initializing MCP2515...");
+
+  CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted
+}
+
+byte data[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
+
+void loop()
+{
+  // send data:  ID = 0x100, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
+  byte sndStat = CAN0.sendMsgBuf(0x100, 0, 8, data);
+  if(sndStat == CAN_OK){
+    Serial.println("Message Sent Successfully!");
+  } else {
+    Serial.println("Error Sending Message...");
+  }
+  delay(100);   // send data per 100ms
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 59 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_to_Ethernet/CAN_to_Ethernet.ino

@@ -0,0 +1,59 @@
+//  CAN to Ethernet
+//  Jan 28th, 2014
+//  Written by: Cory J. Fowler
+
+#include <mcp_can.h>
+#include <SPI.h>
+#include <Ethernet.h>
+#include <EthernetUdp.h>
+
+// Change these for your network!
+byte mac[] = {0x00, 0x55, 0x66, 0xEE, 0xFF, 0xFF};
+IPAddress      ip(10, 100, 50, 233);
+IPAddress gateway(10, 100, 50, 254);
+IPAddress    dest(10, 100, 50, 210);
+
+unsigned int localPort = 8888;
+unsigned int   remPort = 54321;
+
+unsigned long rxId;
+byte len = 0;
+byte rxBuf[8];
+char buffer[50];
+
+MCP_CAN CAN0(9);                                   // Set CS to pin 9
+
+EthernetUDP UDP;
+void setup()
+{
+  Serial.begin(115200);
+//  CAN0.begin(CAN_250KBPS);                         // init CAN Bus with 250kb/s baudrate
+  CAN0.begin(MCP_ANY, CAN_250KBPS, MCP_16MHZ);     // init CAN Bus with 250kb/s baudrate at 16MHz with Mask & Filters Disabled
+  CAN0.setMode(MCP_NORMAL);                        // Set operation mode to normal so the MCP2515 sends acks to received data.
+  pinMode(2, INPUT);                               // Setting pin 2, MCP2515 /INT, to input mode
+  Ethernet.begin(mac,ip);                          // Initialize Ethernet
+  UDP.begin(localPort);                            // Initialize the UDP listen port that is currently unused!
+
+  Serial.println("CAN to Ethernet...");
+}
+
+void loop()
+{
+    if(!digitalRead(2))                            // If pin 2 is low, read receive buffer
+    {
+      CAN0.readMsgBuf(&rxId, &len, rxBuf);         // Read Data: rxID = Message ID, len = Data Length, buf = Data Byte(s)
+//      CAN0.readMsgBuf(&len, rxBuf);                // Read Data: len = Data Length, buf = Data Byte(s)
+//      rxId = CAN0.getCanId();                      // Function will be depreciated soon due to readMsgBuf now returning ID
+
+      sprintf(buffer, "ID: %.8lX  Data: %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\n\r",
+              rxId, rxBuf[0], rxBuf[1], rxBuf[2], rxBuf[3], rxBuf[4], rxBuf[5], rxBuf[6], rxBuf[7]);
+
+      UDP.beginPacket(dest, remPort);
+      UDP.write(buffer);
+      UDP.endPacket();
+    }
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 19 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/CAN_to_Ethernet/udp_listen.pl

@@ -0,0 +1,19 @@
+#!/usr/bin/perl -w
+#This works on Debian Linux
+#I have not tested it on a Windows system running Perl, but it should work if all dependencies are met.
+#Also, FIREWALL.  <--- I gaurantee that will be the issue.
+
+use IO::Socket;
+
+### Create UDP Listen Socket
+my $udpsocket = new IO::Socket::INET (
+  LocalPort => '54321',
+  Proto => 'udp',
+  );
+  die "Could not create socket: $!\n" unless $udpsocket;
+
+### Data Manipulation and Display
+while(1) {
+    $udpsocket->recv(my $data,512);
+    print $data;
+}

+ 55 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Dual_CAN/Dual_CAN.ino

@@ -0,0 +1,55 @@
+// Demo: Dual CAN-BUS Shields, Data Pass-through
+// Written by: Cory J. Fowler
+// January 31st 2014
+// This examples the ability of this library to support more than one MCP2515 based CAN interface.
+
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+unsigned long rxId;
+byte len;
+byte rxBuf[8];
+
+byte txBuf0[] = {AA,55,AA,55,AA,55,AA,55};
+byte txBuf1[] = {55,AA,55,AA,55,AA,55,AA};
+
+MCP_CAN CAN0(10);                              // CAN0 interface usins CS on digital pin 10
+MCP_CAN CAN1(9);                               // CAN1 interface using CS on digital pin 9
+
+void setup()
+{
+  Serial.begin(115200);
+  
+  // init CAN0 bus, baudrate: 250k@16MHz
+  if(CAN0.begin(MCP_EXT, CAN_250KBPS, MCP_16MHZ) == CAN_OK){
+  Serial.print("CAN0: Init OK!\r\n");
+  CAN0.setMode(MCP_NORMAL);
+  } else Serial.print("CAN0: Init Fail!!!\r\n");
+  
+  // init CAN1 bus, baudrate: 250k@16MHz
+  if(CAN1.begin(MCP_EXT, CAN_250KBPS, MCP_16MHZ) == CAN_OK){
+  Serial.print("CAN1: Init OK!\r\n");
+  CAN1.setMode(MCP_NORMAL);
+  } else Serial.print("CAN1: Init Fail!!!\r\n");
+  
+  SPI.setClockDivider(SPI_CLOCK_DIV2);         // Set SPI to run at 8MHz (16MHz / 2 = 8 MHz)
+  
+  CAN0.sendMsgBuf(0x1000000, 1, 8, tx0Buf);
+  CAN1.sendMsgBuf(0x1000001, 1, 8, tx1Buf);
+}
+
+void loop(){  
+  if(!digitalRead(2)){                         // If pin 2 is low, read CAN0 receive buffer
+    CAN0.readMsgBuf(&rxId, &len, rxBuf);       // Read data: len = data length, buf = data byte(s)
+    CAN1.sendMsgBuf(rxId, 1, len, rxBuf);      // Immediately send message out CAN1 interface
+  }
+  if(!digitalRead(3)){                         // If pin 3 is low, read CAN1 receive buffer
+    CAN1.readMsgBuf(&rxId, &len, rxBuf);       // Read data: len = data length, buf = data byte(s)
+    CAN0.sendMsgBuf(rxId, 1, len, rxBuf);      // Immediately send message out CAN0 interface
+  }
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 87 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Extended_MaskFilter/Extended_MaskFilter.ino

@@ -0,0 +1,87 @@
+
+// MCP2515 Mask and Filter example for extended CAN message frames.
+// Written by Cory J. Fowler (20140717)
+
+/***********************************************************************************
+If you send the following extended IDs below to an Arduino loaded with this sketch
+you will find that 0x00FFCC00 and 0x00FF9900 will not get in.
+
+   ID in Hex is the same as the Filter in Hex.
+   0x00FFEE00
+   0x00FFDD00
+   0x00FFCC00  This example will NOT be receiving this ID
+   0x00FFBB00
+   0x00FFAA00
+   0x00FF9900  This example will NOT be receiving this ID
+   0x00FF8800
+   0x00FF7700
+
+   This mask will check the filters against ID bits 23 through 8.
+   (Those familiar with J1939 might see why I used this mask.)
+    MASK = 0x00FFFF00
+   If there is an explicit filter match to those bits, the message will be passed to the
+   receive buffer and the interrupt pin will be set.
+   
+   This example will NOT be exclusive to ONLY the above message IDs, for that a mask such
+   as the below would be used: 
+    MASK = 0x1FFFFFFF
+   
+   At the moment, to disable a filter or mask, copy the value of a used filter or mask.
+   
+***********************************************************************************/
+
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+long unsigned int rxId;
+unsigned char len = 0;
+unsigned char rxBuf[8];
+
+MCP_CAN CAN0(10);                          // Set CS to pin 10
+
+void setup()
+{
+  Serial.begin(115200);
+  if(CAN0.begin(MCP_STDEXT, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.print("MCP2515 Init Okay!!\r\n");
+  else Serial.print("MCP2515 Init Failed!!\r\n");
+  pinMode(2, INPUT);                       // Setting pin 2 for /INT input
+
+  CAN0.init_Mask(0,1,0x00FFFF00);                // Init first mask...
+  CAN0.init_Filt(0,1,0x00FFEE00);                // Init first filter...
+  CAN0.init_Filt(1,1,0x00FFDD00);                // Init second filter...
+  
+  CAN0.init_Mask(1,1,0x00FFFF00);                // Init second mask... 
+  CAN0.init_Filt(2,1,0x00FFBB00);                // Init third filter...
+  CAN0.init_Filt(3,1,0x00FFAA00);                // Init fouth filter...
+  CAN0.init_Filt(4,1,0x00FF8800);                // Init fifth filter...
+  CAN0.init_Filt(5,1,0x00FF7700);                // Init sixth filter...
+  
+  Serial.println("MCP2515 Library Mask & Filter Example...");
+  CAN0.setMode(MCP_NORMAL);                // Change to normal mode to allow messages to be transmitted
+}
+
+void loop()
+{
+    if(!digitalRead(2))                    // If pin 2 is low, read receive buffer
+    {
+      CAN0.readMsgBuf(&rxId, &len, rxBuf); // Read data: len = data length, buf = data byte(s)
+      Serial.print("ID: ");
+      Serial.print(rxId, HEX);
+      Serial.print(" Data: ");
+      for(int i = 0; i<len; i++)           // Print each byte of the data
+      {
+        if(rxBuf[i] < 0x10)                // If data byte is less than 0x10, add a leading zero
+        {
+          Serial.print("0");
+        }
+        Serial.print(rxBuf[i], HEX);
+        Serial.print(" ");
+      }
+      Serial.println();
+    }
+}
+
+/*********************************************************************************************************
+END FILE
+*********************************************************************************************************/

+ 1046 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/OBD_Sim/OBD_Sim.ino

@@ -0,0 +1,1046 @@
+/* CAN OBD & UDS Simulator
+ *  
+ *  Currently replies to some general OBD requests 
+ *  Place holders exist for what I've been able to locate on the Internet
+ *  Does not currently support UDS correctly, just placeholders with mode descriptions
+ *  
+ *  Written By: Cory J. Fowler  December 20th, 2016
+ *  
+ */ 
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+
+#define PAD 0x00
+
+// What CAN ID type?  Standard or Extended
+#define standard 0
+
+// 7E0/8 = Engine ECM
+// 7E1/9 = Transmission ECM
+
+#if standard == 1
+  #define REPLY_ID 0x7E9
+  #define LISTEN_ID 0x7E1
+  #define FUNCTIONAL_ID 0x7DF  
+#else
+  #define REPLY_ID 0x98DAF101
+  #define LISTEN_ID 0x98DA01F1
+  #define FUNCTIONAL_ID 0x98DB33F1
+#endif
+
+
+// CAN RX Variables
+unsigned long rxId;
+byte dlc;
+byte rxBuf[8];
+
+// CAN Interrupt and Chip Select
+#define CAN0_INT 2                              // Set CAN0 INT to pin 2
+MCP_CAN CAN0(9);                                // Set CAN0 CS to pin 9
+
+
+void setup()
+{
+  Serial.begin(115200);
+  while(!Serial);
+  
+  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
+  if(CAN0.begin(MCP_STDEXT, CAN_500KBPS, MCP_20MHZ) == CAN_OK)
+    Serial.println("MCP2515 Initialized Successfully!");
+  else
+    Serial.println("Error Initializing MCP2515...");
+
+
+#if standard == 1
+  // Standard ID Filters
+  CAN0.init_Mask(0,0x7F00000);                // Init first mask...
+  CAN0.init_Filt(0,0x7DF0000);                // Init first filter...
+  CAN0.init_Filt(1,0x7E10000);                // Init second filter...
+  
+  CAN0.init_Mask(1,0x7F00000);                // Init second mask... 
+  CAN0.init_Filt(2,0x7DF0000);                // Init third filter...
+  CAN0.init_Filt(3,0x7E10000);                // Init fouth filter...
+  CAN0.init_Filt(4,0x7DF0000);                // Init fifth filter...
+  CAN0.init_Filt(5,0x7E10000);                // Init sixth filter...
+
+#else
+  // Extended ID Filters
+  CAN0.init_Mask(0,0x90FFFF00);                // Init first mask...
+  CAN0.init_Filt(0,0x90DB3300);                // Init first filter...
+  CAN0.init_Filt(1,0x90DA0100);                // Init second filter...
+  
+  CAN0.init_Mask(1,0x90FFFF00);                // Init second mask... 
+  CAN0.init_Filt(2,0x90DB3300);                // Init third filter...
+  CAN0.init_Filt(3,0x90DA0100);                // Init fouth filter...
+  CAN0.init_Filt(4,0x90DB3300);                // Init fifth filter...
+  CAN0.init_Filt(5,0x90DA0100);                // Init sixth filter...
+#endif
+  
+  CAN0.setMode(MCP_NORMAL);                          // Set operation mode to normal so the MCP2515 sends acks to received data.
+
+  pinMode(CAN0_INT, INPUT);                          // Configuring pin for /INT input
+  
+  Serial.println("OBD-II CAN Simulator");
+}
+
+void loop()
+{
+  if(!digitalRead(CAN0_INT))                         // If CAN0_INT pin is low, read receive buffer
+  {
+    CAN0.readMsgBuf(&rxId, &dlc, rxBuf);             // Get CAN data
+    
+    // First request from most adapters...
+    if(rxId == FUNCTIONAL_ID){
+      obdReq(rxBuf);
+    }       
+  }
+}
+
+
+void obdReq(byte *data){
+  byte numofBytes = data[0];
+  byte mode = data[1] & 0x0F;
+  byte pid = data[2];
+  bool tx = false;
+  byte txData[] = {0x00,(0x40 | mode),pid,PAD,PAD,PAD,PAD,PAD};
+
+  
+  //txData[1] = 0x40 | mode;
+  //txData[2] = pid; 
+  
+  //=============================================================================
+  // MODE $01 - Show current data
+  //=============================================================================
+  if(mode == 0x01){
+    if(pid == 0x00){        // Supported PIDs 01-20
+      txData[0] = 0x06;
+      
+      txData[3] = 0x80;
+      txData[4] = 0x38;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+    else if(pid == 0x01){    // Monitor status since DTs cleared.
+      bool MIL = true;
+      byte DTC = 5;
+      txData[0] = 0x06;
+      
+      txData[3] = (MIL << 7) | (DTC & 0x7F);
+      txData[4] = 0x07;
+      txData[5] = 0xFF;
+      txData[6] = 0x00;
+      tx = true;
+    }
+//    else if(pid == 0x02){    // Freeze DTC
+//    }
+    else if(pid == 0x03){    // Fuel system status
+      txData[0] = 0x03;
+      
+      txData[3] = 0xFA;
+      tx = true;
+    }
+//    else if(pid == 0x04){    // Calculated engine load
+//    }
+    else if(pid == 0x05){    // Engine coolant temperature
+      txData[0] = 0x03;
+      
+      txData[3] = 0xFA;
+      tx = true;
+    }
+//    else if(pid == 0x06){    // Short term fuel trim - Bank 1
+//    }
+//    else if(pid == 0x07){    // Long tern fuel trim - Bank 1
+//    }
+//    else if(pid == 0x08){    // Short term fuel trim - Bank 2
+//    }
+//    else if(pid == 0x09){    // Long term fuel trim - Bank 2
+//    }
+//    else if(pid == 0x0A){    // Fuel pressure (gauge)
+//    }
+    else if(pid == 0x0B){    // Intake manifold absolute pressure
+      txData[0] = 0x03;
+      
+      txData[3] = 0x64;
+      tx = true;
+    }
+    else if(pid == 0x0C){    // Engine RPM
+      txData[0] = 0x04;
+      
+      txData[3] = 0x9C;
+      txData[4] = 0x40;
+      tx = true;
+    }
+    else if(pid == 0x0D){    // Vehicle speed
+      txData[0] = 0x03;
+      
+      txData[3] = 0xFA;
+      tx = true;
+    }
+//    else if(pid == 0x0E){    // Timing advance
+//    }
+    else if(pid == 0x0F){    // Intake air temperature
+      txData[0] = 0x03;
+      
+      txData[3] = 0xFA;
+      tx = true;
+    }
+//    else if(pid == 0x10){    // MAF air flow rate
+//    }
+    else if(pid == 0x11){    // Throttle position
+      txData[0] = 0x03;
+      
+      txData[3] = 0xFA;
+      tx = true;
+    }
+//    else if(pid == 0x12){    // Commanded secondary air status
+//    }
+//    else if(pid == 0x13){    // Oxygen sensors present (in 2 banks)
+//    }
+//    else if(pid == 0x14){    // Oxygen Sensor 1 (Voltage & Trim)
+//    }
+//    else if(pid == 0x15){    // Oxygen Sensor 2 (Voltage & Trim)
+//    }
+//    else if(pid == 0x16){    // Oxygen Sensor 3 (Voltage & Trim)
+//    }
+//    else if(pid == 0x17){    // Oxygen Sensor 4 (Voltage & Trim)
+//    }
+//    else if(pid == 0x18){    // Oxygen Sensor 5 (Voltage & Trim)
+//    }
+//    else if(pid == 0x19){    // Oxygen Sensor 6 (Voltage & Trim)
+//    }
+//    else if(pid == 0x1A){    // Oxygen Sensor 7 (Voltage & Trim)
+//    }
+//    else if(pid == 0x1B){    // Oxygen Sensor 8 (Voltage & Trim)
+//    }
+//    else if(pid == 0x1C){    // OBD standards this vehicle conforms to
+//    }
+//    else if(pid == 0x1D){    // Oxygen sensors present (in 4 banks)
+//    }
+//    else if(pid == 0x1E){    // Auxillary input status
+//    }
+//    else if(pid == 0x1F){    // Run time since engine start
+//    }
+    else if(pid == 0x20){    // Supported PIDs 21-40
+      txData[0] = 0x06;
+      
+      txData[3] = 0x80;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+    else if(pid == 0x21){    // Distance traveled with MIL on
+      txData[0] = 0x04;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x23;
+      tx = true;
+    }
+//    else if(pid == 0x22){    // Fuel rail pressure (Relative to Manifold Vacuum)
+//    }
+//    else if(pid == 0x23){    // Fuel rail gauge pressure (diesel or gasoline direct injection)
+//    }
+//    else if(pid == 0x24){    // Oxygen Sensor 1 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x25){    // Oxygen Sensor 2 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x26){    // Oxygen Sensor 3 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x27){    // Oxygen Sensor 4 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x28){    // Oxygen Sensor 5 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x29){    // Oxygen Sensor 6 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x2A){    // Oxygen Sensor 7 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x2B){    // Oxygen Sensor 8 (Fuel to Air & Voltage)
+//    }
+//    else if(pid == 0x2C){    // Commanded EGR
+//    }
+//    else if(pid == 0x2D){    // EGR Error
+//    }
+//    else if(pid == 0x2E){    // Commanded evaporative purge
+//    }
+//    else if(pid == 0x2F){    // Fuel tank level input
+//    }
+//    else if(pid == 0x30){    // Warm-ups since codes cleared
+//    }
+//    else if(pid == 0x31){    // Distance traveled since codes cleared
+//    }
+//    else if(pid == 0x32){    // Evap. System Vapor Pressure
+//    }
+//    else if(pid == 0x33){    // Absolute Barometric Pressure
+//    }
+//    else if(pid == 0x34){    // Oxygen Sensor 1 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x35){    // Oxygen Sensor 2 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x36){    // Oxygen Sensor 3 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x37){    // Oxygen Sensor 4 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x38){    // Oxygen Sensor 5 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x39){    // Oxygen Sensor 6 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x3A){    // Oxygen Sensor 7 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x3B){    // Oxygen Sensor 8 (Fuel to Air & Current) 
+//    }
+//    else if(pid == 0x3C){    // Catalyst Temperature: Bank 1, Sensor 1
+//    }
+//    else if(pid == 0x3D){    // Catalyst Temperature: Bank 2, Sensor 1
+//    }
+//    else if(pid == 0x3E){    // Catalyst Temperature: Bank 1, Sensor 2
+//    }
+//    else if(pid == 0x3F){    // Catalyst Temperature: Bank 2, Sensor 2
+//    }
+    else if(pid == 0x40){    // Supported PIDs 41-60
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x08;
+      txData[5] = 0x00;
+      txData[6] = 0x0D;
+      tx = true;
+    }
+//    else if(pid == 0x41){    // Monitor status this drive cycle
+//    }
+//    else if(pid == 0x42){    // Control module voltage
+//    }
+//    else if(pid == 0x43){    // Absolute load value
+//    }
+//    else if(pid == 0x44){    // Fuel-Air commanded equivalence ratio
+//    }
+//    else if(pid == 0x45){    // Relative throttle position
+//    }
+//    else if(pid == 0x46){    // Ambient air temperature
+//    }
+//    else if(pid == 0x47){    // Absolute throttle postion B
+//    }
+//    else if(pid == 0x48){    // Absolute throttle postion C
+//    }
+//    else if(pid == 0x49){    // Accelerator pedal position D
+//    }
+//    else if(pid == 0x4A){    // Accelerator pedal position E
+//    }
+//    else if(pid == 0x4B){    // Accelerator pedal position F
+//    }
+//    else if(pid == 0x4C){    // Commanded throttle actuator
+//    }
+    else if(pid == 0x4D){    // Time run with MIL on
+      txData[0] = 0x04;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x3C;
+      tx = true;
+    }
+//    else if(pid == 0x4E){    // Time since troble codes cleared
+//    }
+//    else if(pid == 0x4F){    // Time since trouble codes cleared
+//    }
+//    else if(pid == 0x50){    // Maximum value for Fuel-Air equivalence ratio, oxygen sensor voltage, oxygen sensro current, and intake manifold absolute-pressure
+//    }
+//    else if(pid == 0x51){    // Fuel Type
+//    }
+//    else if(pid == 0x52){    // Ethanol Fuel %
+//    }
+//    else if(pid == 0x53){    // Absolute evap system vapor pressure
+//    }
+//    else if(pid == 0x54){    // Evap system vapor pressure
+//    }
+//    else if(pid == 0x55){    // Short term secondary oxygen sensor trim, A: bank 1, B: bank 3
+//    }
+//    else if(pid == 0x56){    // Long term secondary oxygen sensor trim, A: bank 1, B: bank 3
+//    }
+//    else if(pid == 0x57){    // Short term secondary oxygen sensor trim, A: bank 2, B: bank 4
+//    }
+//    else if(pid == 0x58){    // Long term secondary oxygen sensor trim, A: bank 2, B: bank 4
+//    }
+//    else if(pid == 0x59){    // Fuel rail absolute pressure
+//    }
+//    else if(pid == 0x5A){    // Relative accelerator pedal position
+//    }
+//    else if(pid == 0x5B){    // Hybrid battery pack remaining life
+//    }
+    else if(pid == 0x5C){    // Engine oil Temperature
+      txData[0] = 0x03;
+      
+      txData[3] = 0x1E;
+      tx = true;
+    }
+    else if(pid == 0x5D){    // Fuel injection timing
+      txData[0] = 0x04;
+      
+      txData[3] = 0x61;
+      txData[4] = 0x80;
+      tx = true;
+    }
+    else if(pid == 0x5E){    // Engine fuel rate
+      txData[0] = 0x04;
+      
+      txData[3] = 0x07;
+      txData[4] = 0xD0;
+      tx = true;
+    }
+//    else if(pid == 0x5F){    // Emissions requirements to which vehicle is designed
+//    }
+    else if(pid == 0x60){    // Supported PIDs 61-80
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+//    else if(pid == 0x61){    // Driver's demand engine - percent torque
+//    }
+//    else if(pid == 0x62){    // Actual engine - percent torque
+//    }
+//    else if(pid == 0x63){    // Engine reference torque
+//    }
+//    else if(pid == 0x64){    // Engine percent torque data
+//    }
+//    else if(pid == 0x65){    // Auxiliary input / output supported
+//    }
+//    else if(pid == 0x66){    // Mas air flow sensor
+//    }
+//    else if(pid == 0x67){    // Engine coolant temperature
+//    }
+//    else if(pid == 0x68){    // Intake air temperature sensor
+//    }
+//    else if(pid == 0x69){    // Commanded EGR and EGR error
+//    }
+//    else if(pid == 0x6A){    // Commanded Diesel intake air flow control and relative intake air flow position
+//    }
+//    else if(pid == 0x6B){    // Exhaust gas recirculation temperature
+//    }
+//    else if(pid == 0x6C){    // Commanded throttle actuator control and relative throttle position
+//    }
+//    else if(pid == 0x6D){    // Fuel pressure control system
+//    }
+//    else if(pid == 0x6E){    // Injection pressure control system
+//    }
+//    else if(pid == 0x6F){    // Turbocharger compressor inlet pressure
+//    }
+//    else if(pid == 0x70){    // Boost pressure control
+//    }
+//    else if(pid == 0x71){    // Variable Geometry turbo sensor
+//    }
+//    else if(pid == 0x72){    // Wastegate control
+//    }  
+//    else if(pid == 0x73){    // Exhaust pressure
+//    }
+//    else if(pid == 0x74){    // Turbocharger RPM
+//    }
+//    else if(pid == 0x75){    // Turbocharger temperature
+//    }
+//    else if(pid == 0x76){    // Turbocharger temperature
+//    }
+//    else if(pid == 0x77){    // Charge air cooler temperature (CACT)
+//    }
+//    else if(pid == 0x78){    // Exhaust Gas Temperature (EGT) bank 1
+//    }
+//    else if(pid == 0x79){    // Exhaust Gas Temperature (EGT) bank 2
+//    }
+//    else if(pid == 0x7A){    // Diesel particulate filter (DPF)
+//    }
+//    else if(pid == 0x7B){    // Diesel particulate filter (DPF)
+//    }
+//    else if(pid == 0x7C){    // Diesel particulate filter (DPF) temperature
+//    }
+//    else if(pid == 0x7D){    // NOx NTE control area status
+//    }
+//    else if(pid == 0x7E){    // PM NTE control area status
+//    }
+//    else if(pid == 0x7F){    // Engine run time
+//    }
+    else if(pid == 0x80){    // Supported PIDs 81-A0
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+//    else if(pid == 0x81){    // Engine run time for Auxiliary Emissions Control Device (AECD)
+//    }
+//    else if(pid == 0x82){    // Engine run time for Auxiliary Emissions Control Device (AECD)
+//    }  
+//    else if(pid == 0x83){    // NOx sensor
+//    }
+//    else if(pid == 0x84){    // Manifold surface temperature
+//    }
+//    else if(pid == 0x85){    // NOx reqgent system
+//    }
+//    else if(pid == 0x86){    // Particulate Matter (PM) sensor
+//    }
+//    else if(pid == 0x87){    // Intake manifold absolute pressure
+//    }
+    else if(pid == 0xA0){    // Supported PIDs A1-C0
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+    else if(pid == 0xC0){    // Supported PIDs C1-E0
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x01;
+      tx = true;
+    }
+    else if(pid == 0xE0){    // Supported PIDs E1-FF?
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x00;
+      tx = true;
+    }
+    else{
+      unsupported(mode, pid);
+    }
+  }
+  
+  //=============================================================================
+  // MODE $02 - Show freeze frame data
+  //=============================================================================
+  else if(mode == 0x02){
+      unsupported(mode, pid);
+  }
+  
+  //=============================================================================
+  // MODE $03 - Show stored DTCs
+  //=============================================================================
+  else if(mode == 0x03){
+      byte DTCs[] = {(0x40 | mode), 0x05, 0xC0, 0xBA, 0x00, 0x11, 0x80, 0x13, 0x90, 0x45, 0xA0, 0x31};
+      iso_tp(mode, pid, 12, DTCs);
+  }
+  
+  //=============================================================================
+  // MODE $04 - Clear DTCs and stored values
+  //=============================================================================
+  else if(mode == 0x04){
+      // Need to cleat DTCs.  We just acknowledge the command for now.
+      txData[0] = 0x01;
+      tx = true;
+  }
+  
+  //=============================================================================
+  // MODE $05 - Test Results, oxygen sensor monitoring (non CAN only)
+  //=============================================================================
+  else if(mode == 0x05){
+      unsupported(mode, pid);
+  }
+  
+  //=============================================================================
+  // MODE $06 - Test Results, On-Board Monitoring (Oxygen sensor monitoring for CAN only)
+  //=============================================================================
+  else if(mode == 0x06){
+    if(pid == 0x00){        // Supported PIDs 01-20
+      txData[0] = 0x06;
+      
+      txData[3] = 0x00;
+      txData[4] = 0x00;
+      txData[5] = 0x00;
+      txData[6] = 0x00;
+      tx = true;
+    }
+    else{
+      unsupported(mode, pid);
+    }
+  }
+  
+  //=============================================================================
+  // MODE $07 - Show pending DTCs (Detected during current or last driving cycle)
+  //=============================================================================
+  else if(mode == 0x07){
+      byte DTCs[] = {(0x40 | mode), 0x05, 0xC0, 0xBA, 0x00, 0x11, 0x80, 0x13, 0x90, 0x45, 0xA0, 0x31};
+      iso_tp(mode, pid, 12, DTCs);
+  }
+  
+  //=============================================================================
+  // MODE $08 - Control operation of on-board component/system
+  //=============================================================================
+  else if(mode == 0x08){
+      unsupported(mode, pid);
+  }
+  
+  //=============================================================================
+  // MODE $09 - Request vehcile information
+  //=============================================================================
+  else if(mode == 0x09){
+    if(pid == 0x00){        // Supported PIDs 01-20
+      txData[0] = 0x06;
+      
+      txData[3] = 0x54;
+      txData[4] = 0x40;
+      txData[5] = 0x00;
+      txData[6] = 0x00;
+      tx = true;
+    }
+//    else if(pid == 0x01){    // VIN message count for PID 02. (Only for ISO 9141-2, ISO 14230-4 and SAE J1850.)
+//    }
+    else if(pid == 0x02){    // VIN (17 to 20 Bytes) Uses ISO-TP
+      byte VIN[] = {(0x40 | mode), pid, 0x01, 0x31, 0x5a, 0x56, 0x42, 0x50, 0x38, 0x41, 0x4d, 0x37, 0x44, 0x35, 0x32, 0x32, 0x30, 0x31, 0x38, 0x31};
+      iso_tp(mode, pid, 20, VIN);
+    }
+//    else if(pid == 0x03){    // Calibration ID message count for PID 04. (Only for ISO 9141-2, ISO 14230-4 and SAE J1850.)
+//    }
+    else if(pid == 0x04){    // Calibration ID
+      byte CID[] = {(0x40 | mode), pid, 0x01, 0x41, 0x72, 0x64, 0x75, 0x69, 0x6E, 0x6F, 0x20, 0x4F, 0x42, 0x44, 0x49, 0x49, 0x73, 0x69, 0x6D, 0x51, 0x52, 0x53, 0x54};
+      iso_tp(mode, pid, 23, CID);
+    }
+//    else if(pid == 0x05){    // Calibration Verification Number (CVN) message count for PID 06. (Only for ISO 9141-2, ISO 14230-4 and SAE J1850.)
+//    }
+    else if(pid == 0x06){    // CVN
+      byte CVN[] = {(0x40 | mode), pid, 0x02, 0x11, 0x42, 0x42, 0x42, 0x22, 0x43, 0x43, 0x43};
+      iso_tp(mode, pid, 11, CVN);
+    }
+//    else if(pid == 0x07){    // In-use performance tracking message count for PID 08 and 0B. (Only for ISO 9141-2, ISO 14230-4 and SAE J1850.)
+//    }
+//    else if(pid == 0x08){    // In-use performance tracking for spark ignition vehicles.
+//    }
+//    else if(pid == 0x09){    // ECU name message count for PID 0A.
+//    }
+    else if(pid == 0x0A){    // ECM Name
+      byte ECMname[] = {(0x40 | mode), pid, 0x01, 0x45, 0x43, 0x4D, 0x00, 0x2D, 0x41, 0x72, 0x64, 0x75, 0x69, 0x6E, 0x6F, 0x4F, 0x42, 0x44, 0x49, 0x49, 0x73, 0x69, 0x6D};
+      iso_tp(mode, pid, 23, ECMname);
+    }
+//    else if(pid == 0x0B){    // In-use performance tracking for compression ignition vehicles.
+//    }
+//    else if(pid == 0x0C){    // ESN message count for PID 0D.
+//    }
+    else if(pid == 0x0D){    // ESN
+      byte ESN[] = {(0x40 | mode), pid, 0x01, 0x41, 0x72, 0x64, 0x75, 0x69, 0x6E, 0x6F, 0x2D, 0x4F, 0x42, 0x44, 0x49, 0x49, 0x73, 0x69, 0x6D, 0x00};
+      iso_tp(mode, pid, 20, ESN);
+    }
+    else{
+      unsupported(mode, pid); 
+    }
+  }
+  
+  //=============================================================================
+  // MODE $0A - Show permanent DTCs 
+  //=============================================================================
+  else if(mode == 0x0A){
+      byte DTCs[] = {(0x40 | mode), 0x05, 0xC0, 0xBA, 0x00, 0x11, 0x80, 0x13, 0x90, 0x45, 0xA0, 0x31};
+      iso_tp(mode, pid, 12, DTCs);
+  }
+  
+  // UDS Modes: Diagonstic and Communications Management =======================================
+  //=============================================================================
+  // MODE $10 - Diagnostic Session Control
+  //=============================================================================
+//  else if(mode == 0x10){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $11 - ECU Reset
+  //=============================================================================
+//  else if(mode == 0x11){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $27 - Security Access
+  //=============================================================================
+//  else if(mode == 0x27){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $28 - Communication Control
+  //=============================================================================
+//  else if(mode == 0x28){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $3E - Tester Present
+  //=============================================================================
+//  else if(mode == 0x3E){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $83 - Access Timing Parameters
+  //=============================================================================
+//  else if(mode == 0x83){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $84 - Secured Data Transmission
+  //=============================================================================
+//  else if(mode == 0x84){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+//  
+  //=============================================================================
+  // MODE $85 - Control DTC Sentings
+  //=============================================================================
+//  else if(mode == 0x85){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $86 - Response On Event
+  //=============================================================================
+//  else if(mode == 0x86){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $87 - Link Control
+  //=============================================================================
+//  else if(mode == 0x87){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  // UDS Modes: Data Transmission ==============================================================
+  //=============================================================================
+  // MODE $22 - Read Data By Identifier
+  //=============================================================================
+//  else if(mode == 0x22){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $23 - Read Memory By Address
+  //=============================================================================
+//  else if(mode == 0x23){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $24 - Read Scaling Data By Identifier
+  //=============================================================================
+//  else if(mode == 0x24){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $2A - Read Data By Periodic Identifier
+  //=============================================================================
+//  else if(mode == 0x2A){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $2C - Dynamically Define Data Identifier
+  //=============================================================================
+//  else if(mode == 0x2C){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $2E - Write Data By Identifier
+  //=============================================================================
+//  else if(mode == 0x2E){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $3D - Write Memory By Address
+  //=============================================================================
+//  else if(mode == 0x3D){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  // UDS Modes: Stored Data Transmission =======================================================
+  //=============================================================================
+  // MODE $14 - Clear Diagnostic Information
+  //=============================================================================
+//  else if(mode == 0x14){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $19 - Read DTC Information
+  //=============================================================================
+//  else if(mode == 0x19){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      tx = true;
+//  }
+  
+  // UDS Modes: Input Output Control ===========================================================
+  //=============================================================================
+  // MODE $2F - Input Output Control By Identifier
+  //=============================================================================
+//  else if(mode == 0x2F){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  // UDS Modes: Remote Activation of Routine ===================================================
+  //=============================================================================
+  // MODE $31 - Routine Control
+  //=============================================================================
+//  else if(mode == 0x2F){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  // UDS Modes: Upload / Download ==============================================================
+  //=============================================================================
+  // MODE $34 - Request Download
+  //=============================================================================
+//  else if(mode == 0x34){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $35 - Request Upload
+  //=============================================================================
+//  else if(mode == 0x35){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $36 - Transfer Data
+  //=============================================================================
+//  else if(mode == 0x36){
+//      txData[0] = 0x02;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $37 - Request Transfer Exit
+  //=============================================================================
+//  else if(mode == 0x37){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  
+  //=============================================================================
+  // MODE $38 - Request File Transfer
+  //=============================================================================
+//  else if(mode == 0x38){
+//      txData[0] = 0x03;
+//      
+//      txData[2] = mode;
+//      txData[3] = 0x00;
+//      tx = true;
+//  }
+  else { 
+    unsupported(mode, pid);
+  }
+  
+  if(tx)
+    CAN0.sendMsgBuf(REPLY_ID, 8, txData);
+}
+
+
+// Generic debug serial output
+void unsupported(byte mode, byte pid){
+  negAck(mode, 0x12);
+  unsupportedPrint(mode, pid);  
+}
+
+
+// Generic debug serial output
+void negAck(byte mode, byte reason){
+  byte txData[] = {0x03,0x7F,mode,reason,PAD,PAD,PAD,PAD};
+  CAN0.sendMsgBuf(REPLY_ID, 8, txData);
+}
+
+
+// Generic debug serial output
+void unsupportedPrint(byte mode, byte pid){
+  char msgstring[64];
+  sprintf(msgstring, "Mode $%02X: Unsupported PID $%02X requested!", mode, pid);
+  Serial.println(msgstring);
+}
+
+
+// Blocking example of ISO transport
+void iso_tp(byte mode, byte pid, int len, byte *data){
+  byte tpData[8];
+  int offset = 0;
+  byte index = 0;
+//  byte packetcnt = ((len & 0x0FFF) - 6) / 7;
+//  if((((len & 0x0FFF) - 6) % 7) > 0)
+//    packetcnt++;
+
+  // First frame
+  tpData[0] = 0x10 | ((len >> 8) & 0x0F);
+  tpData[1] = 0x00FF & len;
+  for(byte i=2; i<8; i++){
+    tpData[i] = data[offset++];
+  }
+  CAN0.sendMsgBuf(REPLY_ID, 8, tpData);
+  index++; // We sent a packet so increase our index.
+  
+  bool not_done = true;
+  unsigned long sepPrev = millis();
+  byte sepInvl = 0;
+  byte frames = 0;
+  bool lockout = false;
+  while(not_done){
+    // Need to wait for flow frame
+    if(!digitalRead(CAN0_INT)){
+      CAN0.readMsgBuf(&rxId, &dlc, rxBuf);
+    
+      if((rxId == LISTEN_ID) && ((rxBuf[0] & 0xF0) == 0x30)){
+        if((rxBuf[0] & 0x0F) == 0x00){
+          // Continue
+          frames = rxBuf[1];
+          sepInvl = rxBuf[2];
+          lockout = true;
+        } else if((rxBuf[0] & 0x0F) == 0x01){
+          // Wait
+          lockout = false;
+          delay(rxBuf[2]);
+        } else if((rxBuf[0] & 0x0F) == 0x03){
+          // Abort
+          not_done = false;
+          return;
+        }
+      }
+    }
+
+    if(((millis() - sepPrev) >= sepInvl) && lockout){
+      sepPrev = millis();
+
+      tpData[0] = 0x20 | index++;
+      for(byte i=1; i<8; i++){
+        if(offset != len)
+          tpData[i] = data[offset++];
+        else
+          tpData[i] = 0x00;
+      }
+      
+      // Do consecutive frames as instructed via flow frame
+      CAN0.sendMsgBuf(REPLY_ID, 8, tpData);
+      
+      if(frames-- == 1)
+        lockout = false;
+        
+    }
+
+    if(offset == len)
+      not_done = false;
+    else{
+      char msgstring[32];
+      sprintf(msgstring,"Offset: 0x%04X\tLen: 0x%04X", offset, len);
+      Serial.println(msgstring);
+    }
+
+
+    // Timeout
+    if((millis() - sepPrev) >= 1000)
+      not_done = false;
+  }
+  
+}
+  
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 94 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/examples/Standard_MaskFilter/Standard_MaskFilter.ino

@@ -0,0 +1,94 @@
+
+// MCP2515 Mask and Filter example for standard CAN message frames.
+// Written by Cory J. Fowler (20140717)
+
+/***********************************************************************************
+If you send the following standard IDs below to an Arduino loaded with this sketch
+you will find that 0x102 and 0x105 will not get in.
+
+ID in Hex  -   Two Data Bytes!   -  Filter/Mask in HEX
+   0x100   + 0000 0000 0000 0000 =   0x01000000
+   0x101   + 0000 0000 0000 0000 =   0x01010000
+   0x102   + 0000 0000 0000 0000 =   0x01020000  This example will NOT be receiving this ID
+   0x103   + 0000 0000 0000 0000 =   0x01030000
+   0x104   + 0000 0000 0000 0000 =   0x01040000
+   0x105   + 0000 0000 0000 0000 =   0x01050000  This example will NOT be receiving this ID
+   0x106   + 0000 0000 0000 0000 =   0x01060000
+   0x107   + 0000 0000 0000 0000 =   0x01070000
+
+   This mask will check the filters against ID bit 8 and ID bits 3-0.   
+    MASK   + 0000 0000 0000 0000 =   0x010F0000
+   
+   If there is an explicit filter match to those bits, the message will be passed to the
+   receive buffer and the interrupt pin will be set.
+   This example will NOT be exclusive to ONLY the above frame IDs, for that a mask such
+   as the below would be used: 
+    MASK   + 0000 0000 0000 0000 = 0x07FF0000
+    
+   This mask will check the filters against all ID bits and the first data byte:
+    MASK   + 1111 1111 0000 0000 = 0x07FFFF00
+   If you use this mask and do not touch the filters below, you will find that your first
+   data byte must be 0x00 for the message to enter the receive buffer.
+   
+   At the moment, to disable a filter or mask, copy the value of a used filter or mask.
+   
+   Data bytes are ONLY checked when the MCP2515 is in 'MCP_STDEXT' mode via the begin
+   function, otherwise ('MCP_STD') only the ID is checked.
+***********************************************************************************/
+
+
+#include <mcp_can.h>
+#include <SPI.h>
+
+long unsigned int rxId;
+unsigned char len = 0;
+unsigned char rxBuf[8];
+
+MCP_CAN CAN0(10);                          // Set CS to pin 10
+
+void setup()
+{
+  Serial.begin(115200);
+  if(CAN0.begin(MCP_STDEXT, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.print("MCP2515 Init Okay!!\r\n");
+  else Serial.print("MCP2515 Init Failed!!\r\n");
+  pinMode(2, INPUT);                       // Setting pin 2 for /INT input
+
+
+  CAN0.init_Mask(0,0,0x010F0000);                // Init first mask...
+  CAN0.init_Filt(0,0,0x01000000);                // Init first filter...
+  CAN0.init_Filt(1,0,0x01010000);                // Init second filter...
+  
+  CAN0.init_Mask(1,0,0x010F0000);                // Init second mask... 
+  CAN0.init_Filt(2,0,0x01030000);                // Init third filter...
+  CAN0.init_Filt(3,0,0x01040000);                // Init fouth filter...
+  CAN0.init_Filt(4,0,0x01060000);                // Init fifth filter...
+  CAN0.init_Filt(5,0,0x01070000);                // Init sixth filter...
+  
+  Serial.println("MCP2515 Library Mask & Filter Example...");
+  CAN0.setMode(MCP_NORMAL);                // Change to normal mode to allow messages to be transmitted
+}
+
+void loop()
+{
+    if(!digitalRead(2))                    // If pin 2 is low, read receive buffer
+    {
+      CAN0.readMsgBuf(&rxId, &len, rxBuf); // Read data: len = data length, buf = data byte(s)
+      Serial.print("ID: ");
+      Serial.print(rxId, HEX);
+      Serial.print(" Data: ");
+      for(int i = 0; i<len; i++)           // Print each byte of the data
+      {
+        if(rxBuf[i] < 0x10)                // If data byte is less than 0x10, add a leading zero
+        {
+          Serial.print("0");
+        }
+        Serial.print(rxBuf[i], HEX);
+        Serial.print(" ");
+      }
+      Serial.println();
+    }
+}
+
+/*********************************************************************************************************
+END FILE
+*********************************************************************************************************/

+ 60 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/keywords.txt

@@ -0,0 +1,60 @@
+#######################################
+# Syntax Coloring Map For debug_lvc
+#######################################
+
+#######################################
+# Datatypes (KEYWORD1)
+#######################################
+MCP_CAN	KEYWORD1
+mcp_can_dfs	KEYWORD1
+mcp_can	KEYWORD1
+
+#######################################
+# Methods and Functions (KEYWORD2)
+#######################################
+begin	KEYWORD2
+setMode	KEYWORD2
+init_Mask	KEYWORD2
+init_Filt	KEYWORD2
+sendMsgBuf	KEYWORD2
+readMsgBuf	KEYWORD2
+checkReceive	KEYWORD2
+checkError	KEYWORD2
+
+#######################################
+# Constants (LITERAL1)
+#######################################
+MCP_8MHZ	LITERAL1
+MCP_16MHZ	LITERAL1
+MCP_20MHZ	LITERAL1
+CAN_4K096BPS	LITERAL1
+CAN_5KBPS	LITERAL1
+CAN_10KBPS	LITERAL1
+CAN_20KBPS	LITERAL1
+CAN_31K25BPS	LITERAL1
+CAN_40KBPS	LITERAL1
+CAN_50KBPS	LITERAL1
+CAN_80KBPS	LITERAL1
+CAN_100KBPS	LITERAL1
+CAN_125KBPS	LITERAL1
+CAN_200KBPS	LITERAL1
+CAN_250KBPS	LITERAL1
+CAN_500KBPS	LITERAL1
+CAN_1000KBPS	LITERAL1
+MCP_ANY	LITERAL1
+MCP_STD	LITERAL1
+MCP_EXT	LITERAL1
+MCP_STDEXT	LITERAL1
+CAN_OK	LITERAL1
+CAN_FAILINIT	LITERAL1
+CAN_FAILTX	LITERAL1
+CAN_MSGAVAIL	LITERAL1
+CAN_NOMSG	LITERAL1
+CAN_CTRLERROR	LITERAL1
+CAN_GETTXBFTIMEOUT	LITERAL1
+CAN_SENDMSGTIMEOUT	LITERAL1
+CAN_FAIL	LITERAL1
+MCP_NORMAL	LITERAL1
+MCP_SLEEP	LITERAL1
+MCP_LOOPBACK	LITERAL1
+MCP_LISTENONLY	LITERAL1

+ 1308 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can.cpp

@@ -0,0 +1,1308 @@
+/*
+  mcp_can.cpp
+  2012 Copyright (c) Seeed Technology Inc.  All right reserved.
+  2017 Copyright (c) Cory J. Fowler  All Rights Reserved.
+
+  Author: Loovee
+  Contributor: Cory J. Fowler
+  2017-09-25
+  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
+*/
+#include "mcp_can.h"
+
+#define spi_readwrite SPI.transfer
+#define spi_read() spi_readwrite(0x00)
+
+/*********************************************************************************************************
+** Function name:           mcp2515_reset
+** Descriptions:            Performs a software reset
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_reset(void)                                      
+{
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_RESET);
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+    delayMicroseconds(10);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_readRegister
+** Descriptions:            Read data register
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_readRegister(const INT8U address)                                                                     
+{
+    INT8U ret;
+
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_READ);
+    spi_readwrite(address);
+    ret = spi_read();
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+
+    return ret;
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_readRegisterS
+** Descriptions:            Reads sucessive data registers
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_readRegisterS(const INT8U address, INT8U values[], const INT8U n)
+{
+    INT8U i;
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_READ);
+    spi_readwrite(address);
+    // mcp2515 has auto-increment of address-pointer
+    for (i=0; i<n; i++) 
+        values[i] = spi_read();
+
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_setRegister
+** Descriptions:            Sets data register
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_setRegister(const INT8U address, const INT8U value)
+{
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_WRITE);
+    spi_readwrite(address);
+    spi_readwrite(value);
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_setRegisterS
+** Descriptions:            Sets sucessive data registers
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_setRegisterS(const INT8U address, const INT8U values[], const INT8U n)
+{
+    INT8U i;
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_WRITE);
+    spi_readwrite(address);
+       
+    for (i=0; i<n; i++) 
+        spi_readwrite(values[i]);
+	
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_modifyRegister
+** Descriptions:            Sets specific bits of a register
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
+{
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_BITMOD);
+    spi_readwrite(address);
+    spi_readwrite(mask);
+    spi_readwrite(data);
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_readStatus
+** Descriptions:            Reads status register
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_readStatus(void)                             
+{
+    INT8U i;
+    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
+    MCP2515_SELECT();
+    spi_readwrite(MCP_READ_STATUS);
+    i = spi_read();
+    MCP2515_UNSELECT();
+    SPI.endTransaction();
+    return i;
+}
+
+/*********************************************************************************************************
+** Function name:           setMode
+** Descriptions:            Sets control mode
+*********************************************************************************************************/
+INT8U MCP_CAN::setMode(const INT8U opMode)
+{
+    mcpMode = opMode;
+    return mcp2515_setCANCTRL_Mode(mcpMode);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_setCANCTRL_Mode
+** Descriptions:            Set control mode
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
+{
+    INT8U i;
+
+    mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);
+
+    i = mcp2515_readRegister(MCP_CANCTRL);
+    i &= MODE_MASK;
+
+    if ( i == newmode ) 
+        return MCP2515_OK;
+
+    return MCP2515_FAIL;
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_configRate
+** Descriptions:            Set baudrate
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_configRate(const INT8U canSpeed, const INT8U canClock)            
+{
+    INT8U set, cfg1, cfg2, cfg3;
+    set = 1;
+    switch (canClock)
+    {
+        case (MCP_8MHZ):
+        switch (canSpeed) 
+        {
+            case (CAN_5KBPS):                                               //   5KBPS                  
+            cfg1 = MCP_8MHz_5kBPS_CFG1;
+            cfg2 = MCP_8MHz_5kBPS_CFG2;
+            cfg3 = MCP_8MHz_5kBPS_CFG3;
+            break;
+
+            case (CAN_10KBPS):                                              //  10KBPS                  
+            cfg1 = MCP_8MHz_10kBPS_CFG1;
+            cfg2 = MCP_8MHz_10kBPS_CFG2;
+            cfg3 = MCP_8MHz_10kBPS_CFG3;
+            break;
+
+            case (CAN_20KBPS):                                              //  20KBPS                  
+            cfg1 = MCP_8MHz_20kBPS_CFG1;
+            cfg2 = MCP_8MHz_20kBPS_CFG2;
+            cfg3 = MCP_8MHz_20kBPS_CFG3;
+            break;
+
+            case (CAN_31K25BPS):                                            //  31.25KBPS                  
+            cfg1 = MCP_8MHz_31k25BPS_CFG1;
+            cfg2 = MCP_8MHz_31k25BPS_CFG2;
+            cfg3 = MCP_8MHz_31k25BPS_CFG3;
+            break;
+
+            case (CAN_33K3BPS):                                             //  33.33KBPS                  
+            cfg1 = MCP_8MHz_33k3BPS_CFG1;
+            cfg2 = MCP_8MHz_33k3BPS_CFG2;
+            cfg3 = MCP_8MHz_33k3BPS_CFG3;
+            break;
+
+            case (CAN_40KBPS):                                              //  40Kbps
+            cfg1 = MCP_8MHz_40kBPS_CFG1;
+            cfg2 = MCP_8MHz_40kBPS_CFG2;
+            cfg3 = MCP_8MHz_40kBPS_CFG3;
+            break;
+
+            case (CAN_50KBPS):                                              //  50Kbps
+            cfg1 = MCP_8MHz_50kBPS_CFG1;
+            cfg2 = MCP_8MHz_50kBPS_CFG2;
+            cfg3 = MCP_8MHz_50kBPS_CFG3;
+            break;
+
+            case (CAN_80KBPS):                                              //  80Kbps
+            cfg1 = MCP_8MHz_80kBPS_CFG1;
+            cfg2 = MCP_8MHz_80kBPS_CFG2;
+            cfg3 = MCP_8MHz_80kBPS_CFG3;
+            break;
+
+            case (CAN_100KBPS):                                             // 100Kbps
+            cfg1 = MCP_8MHz_100kBPS_CFG1;
+            cfg2 = MCP_8MHz_100kBPS_CFG2;
+            cfg3 = MCP_8MHz_100kBPS_CFG3;
+            break;
+
+            case (CAN_125KBPS):                                             // 125Kbps
+            cfg1 = MCP_8MHz_125kBPS_CFG1;
+            cfg2 = MCP_8MHz_125kBPS_CFG2;
+            cfg3 = MCP_8MHz_125kBPS_CFG3;
+            break;
+
+            case (CAN_200KBPS):                                             // 200Kbps
+            cfg1 = MCP_8MHz_200kBPS_CFG1;
+            cfg2 = MCP_8MHz_200kBPS_CFG2;
+            cfg3 = MCP_8MHz_200kBPS_CFG3;
+            break;
+
+            case (CAN_250KBPS):                                             // 250Kbps
+            cfg1 = MCP_8MHz_250kBPS_CFG1;
+            cfg2 = MCP_8MHz_250kBPS_CFG2;
+            cfg3 = MCP_8MHz_250kBPS_CFG3;
+            break;
+
+            case (CAN_500KBPS):                                             // 500Kbps
+            cfg1 = MCP_8MHz_500kBPS_CFG1;
+            cfg2 = MCP_8MHz_500kBPS_CFG2;
+            cfg3 = MCP_8MHz_500kBPS_CFG3;
+            break;
+        
+            case (CAN_1000KBPS):                                            //   1Mbps
+            cfg1 = MCP_8MHz_1000kBPS_CFG1;
+            cfg2 = MCP_8MHz_1000kBPS_CFG2;
+            cfg3 = MCP_8MHz_1000kBPS_CFG3;
+            break;  
+
+            default:
+            set = 0;
+	    return MCP2515_FAIL;
+            break;
+        }
+        break;
+
+        case (MCP_16MHZ):
+        switch (canSpeed) 
+        {
+            case (CAN_5KBPS):                                               //   5Kbps
+            cfg1 = MCP_16MHz_5kBPS_CFG1;
+            cfg2 = MCP_16MHz_5kBPS_CFG2;
+            cfg3 = MCP_16MHz_5kBPS_CFG3;
+            break;
+
+            case (CAN_10KBPS):                                              //  10Kbps
+            cfg1 = MCP_16MHz_10kBPS_CFG1;
+            cfg2 = MCP_16MHz_10kBPS_CFG2;
+            cfg3 = MCP_16MHz_10kBPS_CFG3;
+            break;
+
+            case (CAN_20KBPS):                                              //  20Kbps
+            cfg1 = MCP_16MHz_20kBPS_CFG1;
+            cfg2 = MCP_16MHz_20kBPS_CFG2;
+            cfg3 = MCP_16MHz_20kBPS_CFG3;
+            break;
+
+            case (CAN_33K3BPS):                                              //  20Kbps
+            cfg1 = MCP_16MHz_33k3BPS_CFG1;
+            cfg2 = MCP_16MHz_33k3BPS_CFG2;
+            cfg3 = MCP_16MHz_33k3BPS_CFG3;
+            break;
+
+            case (CAN_40KBPS):                                              //  40Kbps
+            cfg1 = MCP_16MHz_40kBPS_CFG1;
+            cfg2 = MCP_16MHz_40kBPS_CFG2;
+            cfg3 = MCP_16MHz_40kBPS_CFG3;
+            break;
+
+            case (CAN_50KBPS):                                              //  50Kbps
+            cfg2 = MCP_16MHz_50kBPS_CFG2;
+            cfg3 = MCP_16MHz_50kBPS_CFG3;
+            break;
+
+            case (CAN_80KBPS):                                              //  80Kbps
+            cfg1 = MCP_16MHz_80kBPS_CFG1;
+            cfg2 = MCP_16MHz_80kBPS_CFG2;
+            cfg3 = MCP_16MHz_80kBPS_CFG3;
+            break;
+
+            case (CAN_100KBPS):                                             // 100Kbps
+            cfg1 = MCP_16MHz_100kBPS_CFG1;
+            cfg2 = MCP_16MHz_100kBPS_CFG2;
+            cfg3 = MCP_16MHz_100kBPS_CFG3;
+            break;
+
+            case (CAN_125KBPS):                                             // 125Kbps
+            cfg1 = MCP_16MHz_125kBPS_CFG1;
+            cfg2 = MCP_16MHz_125kBPS_CFG2;
+            cfg3 = MCP_16MHz_125kBPS_CFG3;
+            break;
+
+            case (CAN_200KBPS):                                             // 200Kbps
+            cfg1 = MCP_16MHz_200kBPS_CFG1;
+            cfg2 = MCP_16MHz_200kBPS_CFG2;
+            cfg3 = MCP_16MHz_200kBPS_CFG3;
+            break;
+
+            case (CAN_250KBPS):                                             // 250Kbps
+            cfg1 = MCP_16MHz_250kBPS_CFG1;
+            cfg2 = MCP_16MHz_250kBPS_CFG2;
+            cfg3 = MCP_16MHz_250kBPS_CFG3;
+            break;
+
+            case (CAN_500KBPS):                                             // 500Kbps
+            cfg1 = MCP_16MHz_500kBPS_CFG1;
+            cfg2 = MCP_16MHz_500kBPS_CFG2;
+            cfg3 = MCP_16MHz_500kBPS_CFG3;
+            break;
+        
+            case (CAN_1000KBPS):                                            //   1Mbps
+            cfg1 = MCP_16MHz_1000kBPS_CFG1;
+            cfg2 = MCP_16MHz_1000kBPS_CFG2;
+            cfg3 = MCP_16MHz_1000kBPS_CFG3;
+            break;  
+
+            default:
+            set = 0;
+	    return MCP2515_FAIL;
+            break;
+        }
+        break;
+        
+        case (MCP_20MHZ):
+        switch (canSpeed) 
+        {
+            case (CAN_40KBPS):                                              //  40Kbps
+            cfg1 = MCP_20MHz_40kBPS_CFG1;
+            cfg2 = MCP_20MHz_40kBPS_CFG2;
+            cfg3 = MCP_20MHz_40kBPS_CFG3;
+            break;
+
+            case (CAN_50KBPS):                                              //  50Kbps
+            cfg1 = MCP_20MHz_50kBPS_CFG1;
+            cfg2 = MCP_20MHz_50kBPS_CFG2;
+            cfg3 = MCP_20MHz_50kBPS_CFG3;
+            break;
+
+            case (CAN_80KBPS):                                              //  80Kbps
+            cfg1 = MCP_20MHz_80kBPS_CFG1;
+            cfg2 = MCP_20MHz_80kBPS_CFG2;
+            cfg3 = MCP_20MHz_80kBPS_CFG3;
+            break;
+
+            case (CAN_100KBPS):                                             // 100Kbps
+            cfg1 = MCP_20MHz_100kBPS_CFG1;
+            cfg2 = MCP_20MHz_100kBPS_CFG2;
+            cfg3 = MCP_20MHz_100kBPS_CFG3;
+            break;
+
+            case (CAN_125KBPS):                                             // 125Kbps
+            cfg1 = MCP_20MHz_125kBPS_CFG1;
+            cfg2 = MCP_20MHz_125kBPS_CFG2;
+            cfg3 = MCP_20MHz_125kBPS_CFG3;
+            break;
+
+            case (CAN_200KBPS):                                             // 200Kbps
+            cfg1 = MCP_20MHz_200kBPS_CFG1;
+            cfg2 = MCP_20MHz_200kBPS_CFG2;
+            cfg3 = MCP_20MHz_200kBPS_CFG3;
+            break;
+
+            case (CAN_250KBPS):                                             // 250Kbps
+            cfg1 = MCP_20MHz_250kBPS_CFG1;
+            cfg2 = MCP_20MHz_250kBPS_CFG2;
+            cfg3 = MCP_20MHz_250kBPS_CFG3;
+            break;
+
+            case (CAN_500KBPS):                                             // 500Kbps
+            cfg1 = MCP_20MHz_500kBPS_CFG1;
+            cfg2 = MCP_20MHz_500kBPS_CFG2;
+            cfg3 = MCP_20MHz_500kBPS_CFG3;
+            break;
+        
+            case (CAN_1000KBPS):                                            //   1Mbps
+            cfg1 = MCP_20MHz_1000kBPS_CFG1;
+            cfg2 = MCP_20MHz_1000kBPS_CFG2;
+            cfg3 = MCP_20MHz_1000kBPS_CFG3;
+            break;  
+
+            default:
+            set = 0;
+            return MCP2515_FAIL;
+            break;
+        }
+        break;
+        
+        default:
+        set = 0;
+	return MCP2515_FAIL;
+        break;
+    }
+
+    if (set) {
+        mcp2515_setRegister(MCP_CNF1, cfg1);
+        mcp2515_setRegister(MCP_CNF2, cfg2);
+        mcp2515_setRegister(MCP_CNF3, cfg3);
+        return MCP2515_OK;
+    }
+     
+    return MCP2515_FAIL;
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_initCANBuffers
+** Descriptions:            Initialize Buffers, Masks, and Filters
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_initCANBuffers(void)
+{
+    INT8U i, a1, a2, a3;
+    
+    INT8U std = 0;               
+    INT8U ext = 1;
+    INT32U ulMask = 0x00, ulFilt = 0x00;
+
+
+    mcp2515_write_mf(MCP_RXM0SIDH, ext, ulMask);			/*Set both masks to 0           */
+    mcp2515_write_mf(MCP_RXM1SIDH, ext, ulMask);			/*Mask register ignores ext bit */
+    
+                                                                        /* Set all filters to 0         */
+    mcp2515_write_mf(MCP_RXF0SIDH, ext, ulFilt);			/* RXB0: extended               */
+    mcp2515_write_mf(MCP_RXF1SIDH, std, ulFilt);			/* RXB1: standard               */
+    mcp2515_write_mf(MCP_RXF2SIDH, ext, ulFilt);			/* RXB2: extended               */
+    mcp2515_write_mf(MCP_RXF3SIDH, std, ulFilt);			/* RXB3: standard               */
+    mcp2515_write_mf(MCP_RXF4SIDH, ext, ulFilt);
+    mcp2515_write_mf(MCP_RXF5SIDH, std, ulFilt);
+
+                                                                        /* Clear, deactivate the three  */
+                                                                        /* transmit buffers             */
+                                                                        /* TXBnCTRL -> TXBnD7           */
+    a1 = MCP_TXB0CTRL;
+    a2 = MCP_TXB1CTRL;
+    a3 = MCP_TXB2CTRL;
+    for (i = 0; i < 14; i++) {                                          /* in-buffer loop               */
+        mcp2515_setRegister(a1, 0);
+        mcp2515_setRegister(a2, 0);
+        mcp2515_setRegister(a3, 0);
+        a1++;
+        a2++;
+        a3++;
+    }
+    mcp2515_setRegister(MCP_RXB0CTRL, 0);
+    mcp2515_setRegister(MCP_RXB1CTRL, 0);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_init
+** Descriptions:            Initialize the controller
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_init(const INT8U canIDMode, const INT8U canSpeed, const INT8U canClock)
+{
+
+  INT8U res;
+
+    mcp2515_reset();
+    
+    mcpMode = MCP_LOOPBACK;
+
+    res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
+    if(res > 0)
+    {
+#if DEBUG_MODE
+      Serial.print("Entering Configuration Mode Failure...\r\n"); 
+#endif
+      return res;
+    }
+#if DEBUG_MODE
+    Serial.print("Entering Configuration Mode Successful!\r\n");
+#endif
+
+    // Set Baudrate
+    if(mcp2515_configRate(canSpeed, canClock))
+    {
+#if DEBUG_MODE
+      Serial.print("Setting Baudrate Failure...\r\n");
+#endif
+      return res;
+    }
+#if DEBUG_MODE
+    Serial.print("Setting Baudrate Successful!\r\n");
+#endif
+
+    if ( res == MCP2515_OK ) {
+
+                                                                        /* init canbuffers              */
+        mcp2515_initCANBuffers();
+
+                                                                        /* interrupt mode               */
+        mcp2515_setRegister(MCP_CANINTE, MCP_RX0IF | MCP_RX1IF);
+
+	//Sets BF pins as GPO
+	mcp2515_setRegister(MCP_BFPCTRL,MCP_BxBFS_MASK | MCP_BxBFE_MASK);
+	//Sets RTS pins as GPI
+	mcp2515_setRegister(MCP_TXRTSCTRL,0x00);
+
+        switch(canIDMode)
+        {
+            case (MCP_ANY):
+            mcp2515_modifyRegister(MCP_RXB0CTRL,
+            MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
+            MCP_RXB_RX_ANY | MCP_RXB_BUKT_MASK);
+            mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
+            MCP_RXB_RX_ANY);
+            break;
+/*          The followingn two functions of the MCP2515 do not work, there is a bug in the silicon.
+            case (MCP_STD): 
+            mcp2515_modifyRegister(MCP_RXB0CTRL,
+            MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
+            MCP_RXB_RX_STD | MCP_RXB_BUKT_MASK );
+            mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
+            MCP_RXB_RX_STD);
+            break;
+
+            case (MCP_EXT): 
+            mcp2515_modifyRegister(MCP_RXB0CTRL,
+            MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
+            MCP_RXB_RX_EXT | MCP_RXB_BUKT_MASK );
+            mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
+            MCP_RXB_RX_EXT);
+            break;
+*/
+            case (MCP_STDEXT): 
+            mcp2515_modifyRegister(MCP_RXB0CTRL,
+            MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK,
+            MCP_RXB_RX_STDEXT | MCP_RXB_BUKT_MASK );
+            mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK,
+            MCP_RXB_RX_STDEXT);
+            break;
+    
+            default:
+#if DEBUG_MODE        
+            Serial.print("`Setting ID Mode Failure...\r\n");
+#endif           
+            return MCP2515_FAIL;
+            break;
+}    
+
+
+        res = mcp2515_setCANCTRL_Mode(mcpMode);                                                                
+        if(res)
+        {
+#if DEBUG_MODE        
+          Serial.print("Returning to Previous Mode Failure...\r\n");
+#endif           
+          return res;
+        }
+
+    }
+    return res;
+
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_write_id
+** Descriptions:            Write CAN ID
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_write_id( const INT8U mcp_addr, const INT8U ext, const INT32U id )
+{
+    uint16_t canid;
+    INT8U tbufdata[4];
+
+    canid = (uint16_t)(id & 0x0FFFF);
+
+    if ( ext == 1) 
+    {
+        tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
+        tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
+        canid = (uint16_t)(id >> 16);
+        tbufdata[MCP_SIDL] = (INT8U) (canid & 0x03);
+        tbufdata[MCP_SIDL] += (INT8U) ((canid & 0x1C) << 3);
+        tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M;
+        tbufdata[MCP_SIDH] = (INT8U) (canid >> 5 );
+    }
+    else 
+    {
+        tbufdata[MCP_SIDH] = (INT8U) (canid >> 3 );
+        tbufdata[MCP_SIDL] = (INT8U) ((canid & 0x07 ) << 5);
+        tbufdata[MCP_EID0] = 0;
+        tbufdata[MCP_EID8] = 0;
+    }
+    
+    mcp2515_setRegisterS( mcp_addr, tbufdata, 4 );
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_write_mf
+** Descriptions:            Write Masks and Filters
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_write_mf( const INT8U mcp_addr, const INT8U ext, const INT32U id )
+{
+    uint16_t canid;
+    INT8U tbufdata[4];
+
+    canid = (uint16_t)(id & 0x0FFFF);
+
+    if ( ext == 1) 
+    {
+        tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
+        tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
+        canid = (uint16_t)(id >> 16);
+        tbufdata[MCP_SIDL] = (INT8U) (canid & 0x03);
+        tbufdata[MCP_SIDL] += (INT8U) ((canid & 0x1C) << 3);
+        tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M;
+        tbufdata[MCP_SIDH] = (INT8U) (canid >> 5 );
+    }
+    else 
+    {
+        tbufdata[MCP_EID0] = (INT8U) (canid & 0xFF);
+        tbufdata[MCP_EID8] = (INT8U) (canid >> 8);
+        canid = (uint16_t)(id >> 16);
+        tbufdata[MCP_SIDL] = (INT8U) ((canid & 0x07) << 5);
+        tbufdata[MCP_SIDH] = (INT8U) (canid >> 3 );
+    }
+    
+    mcp2515_setRegisterS( mcp_addr, tbufdata, 4 );
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_read_id
+** Descriptions:            Read CAN ID
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_read_id( const INT8U mcp_addr, INT8U* ext, INT32U* id )
+{
+    INT8U tbufdata[4];
+
+    *ext = 0;
+    *id = 0;
+
+    mcp2515_readRegisterS( mcp_addr, tbufdata, 4 );
+
+    *id = (tbufdata[MCP_SIDH]<<3) + (tbufdata[MCP_SIDL]>>5);
+
+    if ( (tbufdata[MCP_SIDL] & MCP_TXB_EXIDE_M) ==  MCP_TXB_EXIDE_M ) 
+    {
+                                                                        /* extended id                  */
+        *id = (*id<<2) + (tbufdata[MCP_SIDL] & 0x03);
+        *id = (*id<<8) + tbufdata[MCP_EID8];
+        *id = (*id<<8) + tbufdata[MCP_EID0];
+        *ext = 1;
+    }
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_write_canMsg
+** Descriptions:            Write message
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_write_canMsg( const INT8U buffer_sidh_addr)
+{
+    INT8U mcp_addr;
+    mcp_addr = buffer_sidh_addr;
+    mcp2515_setRegisterS(mcp_addr+5, m_nDta, m_nDlc );                  /* write data bytes             */
+	
+    if ( m_nRtr == 1)                                                   /* if RTR set bit in byte       */
+        m_nDlc |= MCP_RTR_MASK;  
+
+    mcp2515_setRegister((mcp_addr+4), m_nDlc );                         /* write the RTR and DLC        */
+    mcp2515_write_id(mcp_addr, m_nExtFlg, m_nID );                      /* write CAN id                 */
+
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_read_canMsg
+** Descriptions:            Read message
+*********************************************************************************************************/
+void MCP_CAN::mcp2515_read_canMsg( const INT8U buffer_sidh_addr)        /* read can msg                 */
+{
+    INT8U mcp_addr, ctrl;
+
+    mcp_addr = buffer_sidh_addr;
+
+    mcp2515_read_id( mcp_addr, &m_nExtFlg,&m_nID );
+
+    ctrl = mcp2515_readRegister( mcp_addr-1 );
+    m_nDlc = mcp2515_readRegister( mcp_addr+4 );
+
+    if (ctrl & 0x08)
+        m_nRtr = 1;
+    else
+        m_nRtr = 0;
+
+    m_nDlc &= MCP_DLC_MASK;
+    mcp2515_readRegisterS( mcp_addr+5, &(m_nDta[0]), m_nDlc );
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_getNextFreeTXBuf
+** Descriptions:            Send message
+*********************************************************************************************************/
+INT8U MCP_CAN::mcp2515_getNextFreeTXBuf(INT8U *txbuf_n)                 /* get Next free txbuf          */
+{
+    INT8U res, i, ctrlval;
+    INT8U ctrlregs[MCP_N_TXBUFFERS] = { MCP_TXB0CTRL, MCP_TXB1CTRL, MCP_TXB2CTRL };
+
+    res = MCP_ALLTXBUSY;
+    *txbuf_n = 0x00;
+
+                                                                        /* check all 3 TX-Buffers       */
+    for (i=0; i<MCP_N_TXBUFFERS; i++) {
+        ctrlval = mcp2515_readRegister( ctrlregs[i] );
+        if ( (ctrlval & MCP_TXB_TXREQ_M) == 0 ) {
+            *txbuf_n = ctrlregs[i]+1;                                   /* return SIDH-address of Buffer*/
+            
+            res = MCP2515_OK;
+            return res;                                                 /* ! function exit              */
+        }
+    }
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           MCP_CAN
+** Descriptions:            Public function to declare CAN class and the /CS pin.
+*********************************************************************************************************/
+MCP_CAN::MCP_CAN(INT8U _CS)
+{
+    MCPCS = _CS;
+    MCP2515_UNSELECT();
+    pinMode(MCPCS, OUTPUT);
+}
+
+/*********************************************************************************************************
+** Function name:           begin
+** Descriptions:            Public function to declare controller initialization parameters.
+*********************************************************************************************************/
+
+ //static inline void initSS()  { pinMode(SPI_CS, OUTPUT); }
+  //static inline void setSS()   {  digitalWrite(SPI_CS, LOW); }
+  //static inline void resetSS() {  digitalWrite(SPI_CS, HIGH); }
+/*void MCP_CAN::setSS() {
+        Serial.print(" Set Low ");
+        digitalWrite(8, LOW);
+    }
+
+
+void MCP_CAN::resetSS() {
+        digitalWrite(8, HIGH);
+    }
+
+*/
+INT8U MCP_CAN::begin(INT8U idmodeset, INT8U speedset, INT8U clockset)
+{
+    INT8U res;
+
+        SPI.begin();
+            setSS();
+    res = mcp2515_init(idmodeset, speedset, clockset);
+        resetSS();
+    if (res == MCP2515_OK)
+        return CAN_OK;
+    
+    return CAN_FAILINIT;
+}
+
+/*********************************************************************************************************
+** Function name:           init_Mask
+** Descriptions:            Public function to set mask(s).
+*********************************************************************************************************/
+INT8U MCP_CAN::init_Mask(INT8U num, INT8U ext, INT32U ulData)
+{
+    INT8U res = MCP2515_OK;
+#if DEBUG_MODE
+    Serial.print("Starting to Set Mask!\r\n");
+#endif
+    res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
+    if(res > 0){
+#if DEBUG_MODE
+	Serial.print("Entering Configuration Mode Failure...\r\n"); 
+#endif
+	return res;
+     }
+    
+    if (num == 0){
+        mcp2515_write_mf(MCP_RXM0SIDH, ext, ulData);
+
+    }
+    else if(num == 1){
+        mcp2515_write_mf(MCP_RXM1SIDH, ext, ulData);
+    }
+    else res =  MCP2515_FAIL;
+    
+    res = mcp2515_setCANCTRL_Mode(mcpMode);
+    if(res > 0){
+#if DEBUG_MODE
+	Serial.print("Entering Previous Mode Failure...\r\nSetting Mask Failure...\r\n"); 
+#endif
+	return res;
+    }
+#if DEBUG_MODE
+    Serial.print("Setting Mask Successful!\r\n");
+#endif
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           init_Mask
+** Descriptions:            Public function to set mask(s).
+*********************************************************************************************************/
+INT8U MCP_CAN::init_Mask(INT8U num, INT32U ulData)
+{
+    INT8U res = MCP2515_OK;
+    INT8U ext = 0;
+#if DEBUG_MODE
+    Serial.print("Starting to Set Mask!\r\n");
+#endif
+    res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
+    if(res > 0){
+#if DEBUG_MODE
+    Serial.print("Entering Configuration Mode Failure...\r\n"); 
+#endif
+  return res;
+}
+    
+    if((ulData & 0x80000000) == 0x80000000)
+        ext = 1;
+    
+    if (num == 0){
+        mcp2515_write_mf(MCP_RXM0SIDH, ext, ulData);
+
+    }
+    else if(num == 1){
+        mcp2515_write_mf(MCP_RXM1SIDH, ext, ulData);
+    }
+    else res =  MCP2515_FAIL;
+    
+    res = mcp2515_setCANCTRL_Mode(mcpMode);
+    if(res > 0){
+#if DEBUG_MODE
+    Serial.print("Entering Previous Mode Failure...\r\nSetting Mask Failure...\r\n"); 
+#endif
+    return res;
+  }
+#if DEBUG_MODE
+    Serial.print("Setting Mask Successful!\r\n");
+#endif
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           init_Filt
+** Descriptions:            Public function to set filter(s).
+*********************************************************************************************************/
+INT8U MCP_CAN::init_Filt(INT8U num, INT8U ext, INT32U ulData)
+{
+    INT8U res = MCP2515_OK;
+#if DEBUG_MODE
+    Serial.print("Starting to Set Filter!\r\n");
+#endif
+    res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
+    if(res > 0)
+    {
+#if DEBUG_MODE
+      Serial.print("Enter Configuration Mode Failure...\r\n"); 
+#endif
+      return res;
+    }
+    
+    switch( num )
+    {
+        case 0:
+        mcp2515_write_mf(MCP_RXF0SIDH, ext, ulData);
+        break;
+
+        case 1:
+        mcp2515_write_mf(MCP_RXF1SIDH, ext, ulData);
+        break;
+
+        case 2:
+        mcp2515_write_mf(MCP_RXF2SIDH, ext, ulData);
+        break;
+
+        case 3:
+        mcp2515_write_mf(MCP_RXF3SIDH, ext, ulData);
+        break;
+
+        case 4:
+        mcp2515_write_mf(MCP_RXF4SIDH, ext, ulData);
+        break;
+
+        case 5:
+        mcp2515_write_mf(MCP_RXF5SIDH, ext, ulData);
+        break;
+
+        default:
+        res = MCP2515_FAIL;
+    }
+    
+    res = mcp2515_setCANCTRL_Mode(mcpMode);
+    if(res > 0)
+    {
+#if DEBUG_MODE
+      Serial.print("Entering Previous Mode Failure...\r\nSetting Filter Failure...\r\n"); 
+#endif
+      return res;
+    }
+#if DEBUG_MODE
+    Serial.print("Setting Filter Successfull!\r\n");
+#endif
+    
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           init_Filt
+** Descriptions:            Public function to set filter(s).
+*********************************************************************************************************/
+INT8U MCP_CAN::init_Filt(INT8U num, INT32U ulData)
+{
+    INT8U res = MCP2515_OK;
+    INT8U ext = 0;
+    
+#if DEBUG_MODE
+    Serial.print("Starting to Set Filter!\r\n");
+#endif
+    res = mcp2515_setCANCTRL_Mode(MODE_CONFIG);
+    if(res > 0)
+    {
+#if DEBUG_MODE
+      Serial.print("Enter Configuration Mode Failure...\r\n"); 
+#endif
+      return res;
+    }
+    
+    if((ulData & 0x80000000) == 0x80000000)
+        ext = 1;
+    
+    switch( num )
+    {
+        case 0:
+        mcp2515_write_mf(MCP_RXF0SIDH, ext, ulData);
+        break;
+
+        case 1:
+        mcp2515_write_mf(MCP_RXF1SIDH, ext, ulData);
+        break;
+
+        case 2:
+        mcp2515_write_mf(MCP_RXF2SIDH, ext, ulData);
+        break;
+
+        case 3:
+        mcp2515_write_mf(MCP_RXF3SIDH, ext, ulData);
+        break;
+
+        case 4:
+        mcp2515_write_mf(MCP_RXF4SIDH, ext, ulData);
+        break;
+
+        case 5:
+        mcp2515_write_mf(MCP_RXF5SIDH, ext, ulData);
+        break;
+
+        default:
+        res = MCP2515_FAIL;
+    }
+    
+    res = mcp2515_setCANCTRL_Mode(mcpMode);
+    if(res > 0)
+    {
+#if DEBUG_MODE
+      Serial.print("Entering Previous Mode Failure...\r\nSetting Filter Failure...\r\n"); 
+#endif
+      return res;
+    }
+#if DEBUG_MODE
+    Serial.print("Setting Filter Successfull!\r\n");
+#endif
+    
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           setMsg
+** Descriptions:            Set can message, such as dlc, id, dta[] and so on
+*********************************************************************************************************/
+INT8U MCP_CAN::setMsg(INT32U id, INT8U rtr, INT8U ext, INT8U len, INT8U *pData)
+{
+    int i = 0;
+    m_nID     = id;
+    m_nRtr    = rtr;
+    m_nExtFlg = ext;
+    m_nDlc    = len;
+    for(i = 0; i<MAX_CHAR_IN_MESSAGE; i++)
+        m_nDta[i] = *(pData+i);
+	
+    return MCP2515_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           clearMsg
+** Descriptions:            Set all messages to zero
+*********************************************************************************************************/
+INT8U MCP_CAN::clearMsg()
+{
+    m_nID       = 0;
+    m_nDlc      = 0;
+    m_nExtFlg   = 0;
+    m_nRtr      = 0;
+    m_nfilhit   = 0;
+    for(int i = 0; i<m_nDlc; i++ )
+      m_nDta[i] = 0x00;
+
+    return MCP2515_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           sendMsg
+** Descriptions:            Send message
+*********************************************************************************************************/
+INT8U MCP_CAN::sendMsg()
+{
+    INT8U res, res1, txbuf_n;
+    uint16_t uiTimeOut = 0;
+
+    do {
+        res = mcp2515_getNextFreeTXBuf(&txbuf_n);                       /* info = addr.                 */
+        uiTimeOut++;
+    } while (res == MCP_ALLTXBUSY && (uiTimeOut < TIMEOUTVALUE));
+
+    if(uiTimeOut == TIMEOUTVALUE) 
+    {   
+        return CAN_GETTXBFTIMEOUT;                                      /* get tx buff time out         */
+    }
+    uiTimeOut = 0;
+    mcp2515_write_canMsg( txbuf_n);
+    mcp2515_modifyRegister( txbuf_n-1 , MCP_TXB_TXREQ_M, MCP_TXB_TXREQ_M );
+    
+    do
+    {
+        uiTimeOut++;        
+        res1 = mcp2515_readRegister(txbuf_n-1);                         /* read send buff ctrl reg 	*/
+        res1 = res1 & 0x08;                               		
+    } while (res1 && (uiTimeOut < TIMEOUTVALUE));   
+    
+    if(uiTimeOut == TIMEOUTVALUE)                                       /* send msg timeout             */	
+        return CAN_SENDMSGTIMEOUT;
+    
+    return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           sendMsgBuf
+** Descriptions:            Send message to transmitt buffer
+*********************************************************************************************************/
+INT8U MCP_CAN::sendMsgBuf(INT32U id, INT8U ext, INT8U len, INT8U *buf)
+{
+    INT8U res;
+	
+    setMsg(id, 0, ext, len, buf);
+    res = sendMsg();
+    
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           sendMsgBuf
+** Descriptions:            Send message to transmitt buffer
+*********************************************************************************************************/
+INT8U MCP_CAN::sendMsgBuf(INT32U id, INT8U len, INT8U *buf)
+{
+    INT8U ext = 0, rtr = 0;
+    INT8U res;
+    
+    if((id & 0x80000000) == 0x80000000)
+        ext = 1;
+ 
+    if((id & 0x40000000) == 0x40000000)
+        rtr = 1;
+        
+    setMsg(id, rtr, ext, len, buf);
+    res = sendMsg();
+    
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           readMsg
+** Descriptions:            Read message
+*********************************************************************************************************/
+INT8U MCP_CAN::readMsg()
+{
+    INT8U stat, res;
+
+    stat = mcp2515_readStatus();
+
+    if ( stat & MCP_STAT_RX0IF )                                        /* Msg in Buffer 0              */
+    {
+        mcp2515_read_canMsg( MCP_RXBUF_0);
+        mcp2515_modifyRegister(MCP_CANINTF, MCP_RX0IF, 0);
+        res = CAN_OK;
+    }
+    else if ( stat & MCP_STAT_RX1IF )                                   /* Msg in Buffer 1              */
+    {
+        mcp2515_read_canMsg( MCP_RXBUF_1);
+        mcp2515_modifyRegister(MCP_CANINTF, MCP_RX1IF, 0);
+        res = CAN_OK;
+    }
+    else 
+        res = CAN_NOMSG;
+    
+    return res;
+}
+
+/*********************************************************************************************************
+** Function name:           readMsgBuf
+** Descriptions:            Public function, Reads message from receive buffer.
+*********************************************************************************************************/
+INT8U MCP_CAN::readMsgBuf(INT32U *id, INT8U *ext, INT8U *len, INT8U buf[])
+{
+    if(readMsg() == CAN_NOMSG)
+	return CAN_NOMSG;
+	
+    *id  = m_nID;
+    *len = m_nDlc;
+    *ext = m_nExtFlg;
+    for(int i = 0; i<m_nDlc; i++)
+        buf[i] = m_nDta[i];
+
+    return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           readMsgBuf
+** Descriptions:            Public function, Reads message from receive buffer.
+*********************************************************************************************************/
+INT8U MCP_CAN::readMsgBuf(INT32U *id, INT8U *len, INT8U buf[])
+{
+    if(readMsg() == CAN_NOMSG)
+	return CAN_NOMSG;
+
+    if (m_nExtFlg)
+        m_nID |= 0x80000000;
+
+    if (m_nRtr)
+        m_nID |= 0x40000000;
+	
+    *id  = m_nID;
+    *len = m_nDlc;
+    
+    for(int i = 0; i<m_nDlc; i++)
+        buf[i] = m_nDta[i];
+
+    return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           checkReceive
+** Descriptions:            Public function, Checks for received data.  (Used if not using the interrupt output)
+*********************************************************************************************************/
+INT8U MCP_CAN::checkReceive(void)
+{
+    INT8U res;
+    res = mcp2515_readStatus();                                         /* RXnIF in Bit 1 and 0         */
+    if ( res & MCP_STAT_RXIF_MASK )
+        return CAN_MSGAVAIL;
+    else 
+        return CAN_NOMSG;
+}
+
+/*********************************************************************************************************
+** Function name:           checkError
+** Descriptions:            Public function, Returns error register data.
+*********************************************************************************************************/
+INT8U MCP_CAN::checkError(void)
+{
+    INT8U eflg = mcp2515_readRegister(MCP_EFLG);
+
+    if ( eflg & MCP_EFLG_ERRORMASK ) 
+        return CAN_CTRLERROR;
+    else
+        return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           getError
+** Descriptions:            Returns error register value.
+*********************************************************************************************************/
+INT8U MCP_CAN::getError(void)
+{
+    return mcp2515_readRegister(MCP_EFLG);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_errorCountRX
+** Descriptions:            Returns REC register value
+*********************************************************************************************************/
+INT8U MCP_CAN::errorCountRX(void)                             
+{
+    return mcp2515_readRegister(MCP_REC);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_errorCountTX
+** Descriptions:            Returns TEC register value
+*********************************************************************************************************/
+INT8U MCP_CAN::errorCountTX(void)                             
+{
+    return mcp2515_readRegister(MCP_TEC);
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_enOneShotTX
+** Descriptions:            Enables one shot transmission mode
+*********************************************************************************************************/
+INT8U MCP_CAN::enOneShotTX(void)                             
+{
+    mcp2515_modifyRegister(MCP_CANCTRL, MODE_ONESHOT, MODE_ONESHOT);
+    if((mcp2515_readRegister(MCP_CANCTRL) & MODE_ONESHOT) != MODE_ONESHOT)
+	    return CAN_FAIL;
+    else
+	    return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_disOneShotTX
+** Descriptions:            Disables one shot transmission mode
+*********************************************************************************************************/
+INT8U MCP_CAN::disOneShotTX(void)                             
+{
+    mcp2515_modifyRegister(MCP_CANCTRL, MODE_ONESHOT, 0);
+    if((mcp2515_readRegister(MCP_CANCTRL) & MODE_ONESHOT) != 0)
+        return CAN_FAIL;
+    else
+        return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           mcp2515_abortTX
+** Descriptions:            Aborts any queued transmissions
+*********************************************************************************************************/
+INT8U MCP_CAN::abortTX(void)                             
+{
+    mcp2515_modifyRegister(MCP_CANCTRL, ABORT_TX, ABORT_TX);
+	
+    // Maybe check to see if the TX buffer transmission request bits are cleared instead?
+    if((mcp2515_readRegister(MCP_CANCTRL) & ABORT_TX) != ABORT_TX)
+	    return CAN_FAIL;
+    else
+	    return CAN_OK;
+}
+
+/*********************************************************************************************************
+** Function name:           setGPO
+** Descriptions:            Public function, Checks for r
+*********************************************************************************************************/
+INT8U MCP_CAN::setGPO(INT8U data)
+{
+    mcp2515_modifyRegister(MCP_BFPCTRL, MCP_BxBFS_MASK, (data<<4));
+	    
+    return 0;
+}
+
+/*********************************************************************************************************
+** Function name:           getGPI
+** Descriptions:            Public function, Checks for r
+*********************************************************************************************************/
+INT8U MCP_CAN::getGPI(void)
+{
+    INT8U res;
+    res = mcp2515_readRegister(MCP_TXRTSCTRL) & MCP_BxRTS_MASK;
+    return (res >> 3);
+}
+
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 143 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can.h

@@ -0,0 +1,143 @@
+/*
+  mcp_can.h
+  2012 Copyright (c) Seeed Technology Inc.  All right reserved.
+  2017 Copyright (c) Cory J. Fowler  All Rights Reserved.
+
+  Author:Loovee
+  Contributor: Cory J. Fowler
+  2017-09-25
+  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
+*/
+#ifndef _MCP2515_H_
+#define _MCP2515_H_
+
+#include "mcp_can_dfs.h"
+#define MAX_CHAR_IN_MESSAGE 8
+
+class MCP_CAN
+{
+    private:
+    
+    INT8U   m_nExtFlg;                                                  // Identifier Type
+                                                                        // Extended (29 bit) or Standard (11 bit)
+    INT32U  m_nID;                                                      // CAN ID
+    INT8U   m_nDlc;                                                     // Data Length Code
+    INT8U   m_nDta[MAX_CHAR_IN_MESSAGE];                            	// Data array
+    INT8U   m_nRtr;                                                     // Remote request flag
+    INT8U   m_nfilhit;                                                  // The number of the filter that matched the message
+    INT8U   MCPCS;                                                      // Chip Select pin number
+    INT8U   mcpMode;                                                    // Mode to return to after configurations are performed.
+    
+
+/*********************************************************************************************************
+ *  mcp2515 driver function 
+ *********************************************************************************************************/
+   // private:
+   private:
+
+    void mcp2515_reset(void);                                           // Soft Reset MCP2515
+
+    INT8U mcp2515_readRegister(const INT8U address);                    // Read MCP2515 register
+    
+    void mcp2515_readRegisterS(const INT8U address,                     // Read MCP2515 successive registers
+	                             INT8U values[], 
+                               const INT8U n);
+   
+    void mcp2515_setRegister(const INT8U address,                       // Set MCP2515 register
+                             const INT8U value);
+
+    void mcp2515_setRegisterS(const INT8U address,                      // Set MCP2515 successive registers
+                              const INT8U values[],
+                              const INT8U n);
+    
+    void mcp2515_initCANBuffers(void);
+    
+    void mcp2515_modifyRegister(const INT8U address,                    // Set specific bit(s) of a register
+                                const INT8U mask,
+                                const INT8U data);
+
+    INT8U mcp2515_readStatus(void);                                     // Read MCP2515 Status
+    INT8U mcp2515_setCANCTRL_Mode(const INT8U newmode);                 // Set mode
+    INT8U mcp2515_configRate(const INT8U canSpeed,                      // Set baud rate
+                             const INT8U canClock);
+                             
+    INT8U mcp2515_init(const INT8U canIDMode,                           // Initialize Controller
+                       const INT8U canSpeed,
+                       const INT8U canClock);
+		       
+    void mcp2515_write_mf( const INT8U mcp_addr,                        // Write CAN Mask or Filter
+                           const INT8U ext,
+                           const INT32U id );
+			       
+    void mcp2515_write_id( const INT8U mcp_addr,                        // Write CAN ID
+                           const INT8U ext,
+                           const INT32U id );
+
+    void mcp2515_read_id( const INT8U mcp_addr,                         // Read CAN ID
+				INT8U* ext,
+                                INT32U* id );
+
+    void mcp2515_write_canMsg( const INT8U buffer_sidh_addr );          // Write CAN message
+    void mcp2515_read_canMsg( const INT8U buffer_sidh_addr);            // Read CAN message
+    INT8U mcp2515_getNextFreeTXBuf(INT8U *txbuf_n);                     // Find empty transmit buffer
+    
+    
+      inline void initSS()  { pinMode(MCPCS, OUTPUT); }
+      inline void setSS()   {  digitalWrite(MCPCS, LOW); Serial.print(" SET CS["); Serial.print(MCPCS); Serial.print("] "); }
+      inline void resetSS() {  digitalWrite(MCPCS, HIGH); }
+    
+    
+
+/*********************************************************************************************************
+ *  CAN operator function
+ *********************************************************************************************************/
+
+    INT8U setMsg(INT32U id, INT8U rtr, INT8U ext, INT8U len, INT8U *pData);        // Set message
+    INT8U clearMsg();                                                   // Clear all message to zero
+    INT8U readMsg();                                                    // Read message
+    INT8U sendMsg();                                                    // Send message
+
+public:
+    MCP_CAN(INT8U _CS);
+    INT8U begin(INT8U idmodeset, INT8U speedset, INT8U clockset);       // Initialize controller parameters
+    INT8U init_Mask(INT8U num, INT8U ext, INT32U ulData);               // Initialize Mask(s)
+    INT8U init_Mask(INT8U num, INT32U ulData);                          // Initialize Mask(s)
+    INT8U init_Filt(INT8U num, INT8U ext, INT32U ulData);               // Initialize Filter(s)
+    INT8U init_Filt(INT8U num, INT32U ulData);                          // Initialize Filter(s)
+    INT8U setMode(INT8U opMode);                                        // Set operational mode
+    INT8U sendMsgBuf(INT32U id, INT8U ext, INT8U len, INT8U *buf);      // Send message to transmit buffer
+    INT8U sendMsgBuf(INT32U id, INT8U len, INT8U *buf);                 // Send message to transmit buffer
+    INT8U readMsgBuf(INT32U *id, INT8U *ext, INT8U *len, INT8U *buf);   // Read message from receive buffer
+    INT8U readMsgBuf(INT32U *id, INT8U *len, INT8U *buf);               // Read message from receive buffer
+    INT8U checkReceive(void);                                           // Check for received data
+    INT8U checkError(void);                                             // Check for errors
+    INT8U getError(void);                                               // Check for errors
+    INT8U errorCountRX(void);                                           // Get error count
+    INT8U errorCountTX(void);                                           // Get error count
+    INT8U enOneShotTX(void);                                            // Enable one-shot transmission
+    INT8U disOneShotTX(void);                                           // Disable one-shot transmission
+    INT8U abortTX(void);                                                // Abort queued transmission(s)
+    INT8U setGPO(INT8U data);                                           // Sets GPO
+    INT8U getGPI(void);                                                 // Reads GPI
+    
+  
+    
+};
+
+#endif
+/*********************************************************************************************************
+ *  END FILE
+ *********************************************************************************************************/

+ 476 - 0
SE/stuff/P5_Automation-library-dev/MCP_CAN_lib/mcp_can_dfs.h

@@ -0,0 +1,476 @@
+/*
+  mcp_can_dfs.h
+  2012 Copyright (c) Seeed Technology Inc.  All right reserved.
+  2017 Copyright (c) Cory J. Fowler  All Rights Reserved.
+
+  Author:Loovee
+  Contributor: Cory J. Fowler
+  2017-09-25
+  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
+*/
+#ifndef _MCP2515DFS_H_
+#define _MCP2515DFS_H_
+
+#include <Arduino.h>
+#include <SPI.h>
+#include <inttypes.h>
+
+#ifndef INT32U
+#define INT32U unsigned long
+#endif
+
+#ifndef INT8U
+#define INT8U byte
+#endif
+
+// if print debug information
+#define DEBUG_MODE 1
+
+/*
+ *   Begin mt
+ */
+#define TIMEOUTVALUE    50
+#define MCP_SIDH        0
+#define MCP_SIDL        1
+#define MCP_EID8        2
+#define MCP_EID0        3
+
+#define MCP_TXB_EXIDE_M     0x08                                        /* In TXBnSIDL                  */
+#define MCP_DLC_MASK        0x0F                                        /* 4 LSBits                     */
+#define MCP_RTR_MASK        0x40                                        /* (1<<6) Bit 6                 */
+
+#define MCP_RXB_RX_ANY      0x60
+#define MCP_RXB_RX_EXT      0x40
+#define MCP_RXB_RX_STD      0x20
+#define MCP_RXB_RX_STDEXT   0x00
+#define MCP_RXB_RX_MASK     0x60
+#define MCP_RXB_BUKT_MASK   (1<<2)
+
+/*
+** Bits in the TXBnCTRL registers.
+*/
+#define MCP_TXB_TXBUFE_M    0x80
+#define MCP_TXB_ABTF_M      0x40
+#define MCP_TXB_MLOA_M      0x20
+#define MCP_TXB_TXERR_M     0x10
+#define MCP_TXB_TXREQ_M     0x08
+#define MCP_TXB_TXIE_M      0x04
+#define MCP_TXB_TXP10_M     0x03
+
+#define MCP_TXB_RTR_M       0x40                                        /* In TXBnDLC                   */
+#define MCP_RXB_IDE_M       0x08                                        /* In RXBnSIDL                  */
+#define MCP_RXB_RTR_M       0x40                                        /* In RXBnDLC                   */
+
+#define MCP_STAT_RXIF_MASK   (0x03)
+#define MCP_STAT_RX0IF       (1<<0)
+#define MCP_STAT_RX1IF       (1<<1)
+
+#define MCP_EFLG_RX1OVR     (1<<7)
+#define MCP_EFLG_RX0OVR     (1<<6)
+#define MCP_EFLG_TXBO       (1<<5)
+#define MCP_EFLG_TXEP       (1<<4)
+#define MCP_EFLG_RXEP       (1<<3)
+#define MCP_EFLG_TXWAR      (1<<2)
+#define MCP_EFLG_RXWAR      (1<<1)
+#define MCP_EFLG_EWARN      (1<<0)
+#define MCP_EFLG_ERRORMASK  (0xF8)                                      /* 5 MS-Bits                    */
+
+#define MCP_BxBFS_MASK    0x30
+#define MCP_BxBFE_MASK    0x0C
+#define MCP_BxBFM_MASK    0x03
+
+#define MCP_BxRTS_MASK    0x38
+#define MCP_BxRTSM_MASK   0x07
+
+/*
+ *   Define MCP2515 register addresses
+ */
+#define MCP_RXF0SIDH    0x00
+#define MCP_RXF0SIDL    0x01
+#define MCP_RXF0EID8    0x02
+#define MCP_RXF0EID0    0x03
+#define MCP_RXF1SIDH    0x04
+#define MCP_RXF1SIDL    0x05
+#define MCP_RXF1EID8    0x06
+#define MCP_RXF1EID0    0x07
+#define MCP_RXF2SIDH    0x08
+#define MCP_RXF2SIDL    0x09
+#define MCP_RXF2EID8    0x0A
+#define MCP_RXF2EID0    0x0B
+#define MCP_BFPCTRL     0x0C
+#define MCP_TXRTSCTRL   0x0D
+#define MCP_CANSTAT     0x0E
+#define MCP_CANCTRL     0x0F
+#define MCP_RXF3SIDH    0x10
+#define MCP_RXF3SIDL    0x11
+#define MCP_RXF3EID8    0x12
+#define MCP_RXF3EID0    0x13
+#define MCP_RXF4SIDH    0x14
+#define MCP_RXF4SIDL    0x15
+#define MCP_RXF4EID8    0x16
+#define MCP_RXF4EID0    0x17
+#define MCP_RXF5SIDH    0x18
+#define MCP_RXF5SIDL    0x19
+#define MCP_RXF5EID8    0x1A
+#define MCP_RXF5EID0    0x1B
+#define MCP_TEC            0x1C
+#define MCP_REC            0x1D
+#define MCP_RXM0SIDH    0x20
+#define MCP_RXM0SIDL    0x21
+#define MCP_RXM0EID8    0x22
+#define MCP_RXM0EID0    0x23
+#define MCP_RXM1SIDH    0x24
+#define MCP_RXM1SIDL    0x25
+#define MCP_RXM1EID8    0x26
+#define MCP_RXM1EID0    0x27
+#define MCP_CNF3        0x28
+#define MCP_CNF2        0x29
+#define MCP_CNF1        0x2A
+#define MCP_CANINTE        0x2B
+#define MCP_CANINTF        0x2C
+#define MCP_EFLG        0x2D
+#define MCP_TXB0CTRL    0x30
+#define MCP_TXB1CTRL    0x40
+#define MCP_TXB2CTRL    0x50
+#define MCP_RXB0CTRL    0x60
+#define MCP_RXB0SIDH    0x61
+#define MCP_RXB1CTRL    0x70
+#define MCP_RXB1SIDH    0x71
+
+
+#define MCP_TX_INT          0x1C                                    /* Enable all transmit interrup ts  */
+#define MCP_TX01_INT        0x0C                                    /* Enable TXB0 and TXB1 interru pts */
+#define MCP_RX_INT          0x03                                    /* Enable receive interrupts        */
+#define MCP_NO_INT          0x00                                    /* Disable all interrupts           */
+
+#define MCP_TX01_MASK       0x14
+#define MCP_TX_MASK        0x54
+
+/*
+ *   Define SPI Instruction Set
+ */
+#define MCP_WRITE           0x02
+
+#define MCP_READ            0x03
+
+#define MCP_BITMOD          0x05
+
+#define MCP_LOAD_TX0        0x40
+#define MCP_LOAD_TX1        0x42
+#define MCP_LOAD_TX2        0x44
+
+#define MCP_RTS_TX0         0x81
+#define MCP_RTS_TX1         0x82
+#define MCP_RTS_TX2         0x84
+#define MCP_RTS_ALL         0x87
+
+#define MCP_READ_RX0        0x90
+#define MCP_READ_RX1        0x94
+
+#define MCP_READ_STATUS     0xA0
+
+#define MCP_RX_STATUS       0xB0
+
+#define MCP_RESET           0xC0
+
+
+/*
+ *   CANCTRL Register Values
+ */
+#define MCP_NORMAL     0x00
+#define MCP_SLEEP      0x20
+#define MCP_LOOPBACK   0x40
+#define MCP_LISTENONLY 0x60
+#define MODE_CONFIG     0x80
+#define MODE_POWERUP    0xE0
+#define MODE_MASK       0xE0
+#define ABORT_TX        0x10
+#define MODE_ONESHOT    0x08
+#define CLKOUT_ENABLE   0x04
+#define CLKOUT_DISABLE  0x00
+#define CLKOUT_PS1      0x00
+#define CLKOUT_PS2      0x01
+#define CLKOUT_PS4      0x02
+#define CLKOUT_PS8      0x03
+
+
+/*
+ *   CNF1 Register Values
+ */
+#define SJW1            0x00
+#define SJW2            0x40
+#define SJW3            0x80
+#define SJW4            0xC0
+
+
+/*
+ *   CNF2 Register Values
+ */
+#define BTLMODE         0x80
+#define SAMPLE_1X       0x00
+#define SAMPLE_3X       0x40
+
+
+/*
+ *   CNF3 Register Values
+ */
+#define SOF_ENABLE      0x80
+#define SOF_DISABLE     0x00
+#define WAKFIL_ENABLE   0x40
+#define WAKFIL_DISABLE  0x00
+
+
+/*
+ *   CANINTF Register Bits
+ */
+#define MCP_RX0IF       0x01
+#define MCP_RX1IF       0x02
+#define MCP_TX0IF       0x04
+#define MCP_TX1IF       0x08
+#define MCP_TX2IF       0x10
+#define MCP_ERRIF       0x20
+#define MCP_WAKIF       0x40
+#define MCP_MERRF       0x80
+
+
+/*
+ *  Speed 8M
+ */
+#define MCP_8MHz_1000kBPS_CFG1 (0x00)  
+#define MCP_8MHz_1000kBPS_CFG2 (0xC0)  /* Enabled SAM bit     */
+#define MCP_8MHz_1000kBPS_CFG3 (0x80)  /* Sample point at 75% */
+
+#define MCP_8MHz_500kBPS_CFG1 (0x00)
+#define MCP_8MHz_500kBPS_CFG2 (0xD1)   /* Enabled SAM bit     */
+#define MCP_8MHz_500kBPS_CFG3 (0x81)   /* Sample point at 75% */
+
+#define MCP_8MHz_250kBPS_CFG1 (0x80)   /* Increased SJW       */
+#define MCP_8MHz_250kBPS_CFG2 (0xE5)   /* Enabled SAM bit     */
+#define MCP_8MHz_250kBPS_CFG3 (0x83)   /* Sample point at 75% */
+
+#define MCP_8MHz_200kBPS_CFG1 (0x80)   /* Increased SJW       */
+#define MCP_8MHz_200kBPS_CFG2 (0xF6)   /* Enabled SAM bit     */
+#define MCP_8MHz_200kBPS_CFG3 (0x84)   /* Sample point at 75% */
+
+#define MCP_8MHz_125kBPS_CFG1 (0x81)   /* Increased SJW       */
+#define MCP_8MHz_125kBPS_CFG2 (0xE5)   /* Enabled SAM bit     */
+#define MCP_8MHz_125kBPS_CFG3 (0x83)   /* Sample point at 75% */
+
+#define MCP_8MHz_100kBPS_CFG1 (0x81)   /* Increased SJW       */
+#define MCP_8MHz_100kBPS_CFG2 (0xF6)   /* Enabled SAM bit     */
+#define MCP_8MHz_100kBPS_CFG3 (0x84)   /* Sample point at 75% */
+
+#define MCP_8MHz_80kBPS_CFG1 (0x84)    /* Increased SJW       */
+#define MCP_8MHz_80kBPS_CFG2 (0xD3)    /* Enabled SAM bit     */
+#define MCP_8MHz_80kBPS_CFG3 (0x81)    /* Sample point at 75% */
+
+#define MCP_8MHz_50kBPS_CFG1 (0x84)    /* Increased SJW       */
+#define MCP_8MHz_50kBPS_CFG2 (0xE5)    /* Enabled SAM bit     */
+#define MCP_8MHz_50kBPS_CFG3 (0x83)    /* Sample point at 75% */
+
+#define MCP_8MHz_40kBPS_CFG1 (0x84)    /* Increased SJW       */
+#define MCP_8MHz_40kBPS_CFG2 (0xF6)    /* Enabled SAM bit     */
+#define MCP_8MHz_40kBPS_CFG3 (0x84)    /* Sample point at 75% */
+
+#define MCP_8MHz_33k3BPS_CFG1 (0x85)   /* Increased SJW       */
+#define MCP_8MHz_33k3BPS_CFG2 (0xF6)   /* Enabled SAM bit     */
+#define MCP_8MHz_33k3BPS_CFG3 (0x84)   /* Sample point at 75% */
+
+#define MCP_8MHz_31k25BPS_CFG1 (0x87)  /* Increased SJW       */
+#define MCP_8MHz_31k25BPS_CFG2 (0xE5)  /* Enabled SAM bit     */
+#define MCP_8MHz_31k25BPS_CFG3 (0x83)  /* Sample point at 75% */
+
+#define MCP_8MHz_20kBPS_CFG1 (0x89)    /* Increased SJW       */
+#define MCP_8MHz_20kBPS_CFG2 (0xF6)    /* Enabled SAM bit     */
+#define MCP_8MHz_20kBPS_CFG3 (0x84)    /* Sample point at 75% */
+
+#define MCP_8MHz_10kBPS_CFG1 (0x93)    /* Increased SJW       */
+#define MCP_8MHz_10kBPS_CFG2 (0xF6)    /* Enabled SAM bit     */
+#define MCP_8MHz_10kBPS_CFG3 (0x84)    /* Sample point at 75% */
+
+#define MCP_8MHz_5kBPS_CFG1 (0xA7)     /* Increased SJW       */
+#define MCP_8MHz_5kBPS_CFG2 (0xF6)     /* Enabled SAM bit     */
+#define MCP_8MHz_5kBPS_CFG3 (0x84)     /* Sample point at 75% */
+
+/*
+ *  speed 16M
+ */
+#define MCP_16MHz_1000kBPS_CFG1 (0x00)
+#define MCP_16MHz_1000kBPS_CFG2 (0xCA)
+#define MCP_16MHz_1000kBPS_CFG3 (0x81)    /* Sample point at 75% */
+
+#define MCP_16MHz_500kBPS_CFG1 (0x40)     /* Increased SJW       */
+#define MCP_16MHz_500kBPS_CFG2 (0xE5)
+#define MCP_16MHz_500kBPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_16MHz_250kBPS_CFG1 (0x41)
+#define MCP_16MHz_250kBPS_CFG2 (0xE5)
+#define MCP_16MHz_250kBPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_16MHz_200kBPS_CFG1 (0x41)     /* Increased SJW       */
+#define MCP_16MHz_200kBPS_CFG2 (0xF6)
+#define MCP_16MHz_200kBPS_CFG3 (0x84)     /* Sample point at 75% */
+
+#define MCP_16MHz_125kBPS_CFG1 (0x43)     /* Increased SJW       */
+#define MCP_16MHz_125kBPS_CFG2 (0xE5)
+#define MCP_16MHz_125kBPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_16MHz_100kBPS_CFG1 (0x44)     /* Increased SJW       */
+#define MCP_16MHz_100kBPS_CFG2 (0xE5)
+#define MCP_16MHz_100kBPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_16MHz_80kBPS_CFG1 (0x44)      /* Increased SJW       */
+#define MCP_16MHz_80kBPS_CFG2 (0xF6)
+#define MCP_16MHz_80kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_16MHz_50kBPS_CFG1 (0x47)      /* Increased SJW       */
+#define MCP_16MHz_50kBPS_CFG2 (0xF6)
+#define MCP_16MHz_50kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_16MHz_40kBPS_CFG1 (0x49)      /* Increased SJW       */
+#define MCP_16MHz_40kBPS_CFG2 (0xF6)
+#define MCP_16MHz_40kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_16MHz_33k3BPS_CFG1 (0x4E)
+#define MCP_16MHz_33k3BPS_CFG2 (0xE5)
+#define MCP_16MHz_33k3BPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_16MHz_20kBPS_CFG1 (0x53)      /* Increased SJW       */
+#define MCP_16MHz_20kBPS_CFG2 (0xF6)
+#define MCP_16MHz_20kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_16MHz_10kBPS_CFG1 (0x67)      /* Increased SJW       */
+#define MCP_16MHz_10kBPS_CFG2 (0xF6)
+#define MCP_16MHz_10kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_16MHz_5kBPS_CFG1 (0x3F)
+#define MCP_16MHz_5kBPS_CFG2 (0xFF)
+#define MCP_16MHz_5kBPS_CFG3 (0x87)       /* Sample point at 68% */
+
+/*
+ *  speed 20M
+ */
+#define MCP_20MHz_1000kBPS_CFG1 (0x00)
+#define MCP_20MHz_1000kBPS_CFG2 (0xD9)
+#define MCP_20MHz_1000kBPS_CFG3 (0x82)     /* Sample point at 80% */
+
+#define MCP_20MHz_500kBPS_CFG1 (0x40)     /* Increased SJW       */
+#define MCP_20MHz_500kBPS_CFG2 (0xF6)
+#define MCP_20MHz_500kBPS_CFG3 (0x84)     /* Sample point at 75% */
+
+#define MCP_20MHz_250kBPS_CFG1 (0x41)     /* Increased SJW       */
+#define MCP_20MHz_250kBPS_CFG2 (0xF6)
+#define MCP_20MHz_250kBPS_CFG3 (0x84)     /* Sample point at 75% */
+
+#define MCP_20MHz_200kBPS_CFG1 (0x44)     /* Increased SJW       */
+#define MCP_20MHz_200kBPS_CFG2 (0xD3)
+#define MCP_20MHz_200kBPS_CFG3 (0x81)     /* Sample point at 80% */
+
+#define MCP_20MHz_125kBPS_CFG1 (0x44)     /* Increased SJW       */
+#define MCP_20MHz_125kBPS_CFG2 (0xE5)
+#define MCP_20MHz_125kBPS_CFG3 (0x83)     /* Sample point at 75% */
+
+#define MCP_20MHz_100kBPS_CFG1 (0x44)     /* Increased SJW       */
+#define MCP_20MHz_100kBPS_CFG2 (0xF6)
+#define MCP_20MHz_100kBPS_CFG3 (0x84)     /* Sample point at 75% */
+
+#define MCP_20MHz_80kBPS_CFG1 (0xC4)      /* Increased SJW       */
+#define MCP_20MHz_80kBPS_CFG2 (0xFF)
+#define MCP_20MHz_80kBPS_CFG3 (0x87)      /* Sample point at 68% */
+
+#define MCP_20MHz_50kBPS_CFG1 (0x49)      /* Increased SJW       */
+#define MCP_20MHz_50kBPS_CFG2 (0xF6)
+#define MCP_20MHz_50kBPS_CFG3 (0x84)      /* Sample point at 75% */
+
+#define MCP_20MHz_40kBPS_CFG1 (0x18)
+#define MCP_20MHz_40kBPS_CFG2 (0xD3)
+#define MCP_20MHz_40kBPS_CFG3 (0x81)      /* Sample point at 80% */
+
+
+#define MCPDEBUG        (0)
+#define MCPDEBUG_TXBUF  (0)
+#define MCP_N_TXBUFFERS (3)
+
+#define MCP_RXBUF_0 (MCP_RXB0SIDH)
+#define MCP_RXBUF_1 (MCP_RXB1SIDH)
+
+#define MCP2515_SELECT()   digitalWrite(MCPCS, LOW)
+#define MCP2515_UNSELECT() digitalWrite(MCPCS, HIGH)
+
+#define MCP2515_OK         (0)
+#define MCP2515_FAIL       (1)
+#define MCP_ALLTXBUSY      (2)
+
+#define CANDEBUG   1
+
+#define CANUSELOOP 0
+
+#define CANSENDTIMEOUT (200)                                            /* milliseconds                 */
+
+/*
+ *   initial value of gCANAutoProcess
+ */
+#define CANAUTOPROCESS (1)
+#define CANAUTOON  (1)
+#define CANAUTOOFF (0)
+
+#define CAN_STDID (0)
+#define CAN_EXTID (1)
+
+#define CANDEFAULTIDENT    (0x55CC)
+#define CANDEFAULTIDENTEXT (CAN_EXTID)
+
+#define MCP_STDEXT   0                                                  /* Standard and Extended        */
+#define MCP_STD      1                                                  /* Standard IDs ONLY            */
+#define MCP_EXT      2                                                  /* Extended IDs ONLY            */
+#define MCP_ANY      3                                                  /* Disables Masks and Filters   */
+
+#define MCP_20MHZ    0
+#define MCP_16MHZ    1
+#define MCP_8MHZ     2
+
+#define CAN_4K096BPS 0
+#define CAN_5KBPS    1
+#define CAN_10KBPS   2
+#define CAN_20KBPS   3
+#define CAN_31K25BPS 4
+#define CAN_33K3BPS  5
+#define CAN_40KBPS   6
+#define CAN_50KBPS   7
+#define CAN_80KBPS   8
+#define CAN_100KBPS  9
+#define CAN_125KBPS  10
+#define CAN_200KBPS  11
+#define CAN_250KBPS  12
+#define CAN_500KBPS  13
+#define CAN_1000KBPS 14
+
+#define CAN_OK             (0)
+#define CAN_FAILINIT       (1)
+#define CAN_FAILTX         (2)
+#define CAN_MSGAVAIL       (3)
+#define CAN_NOMSG          (4)
+#define CAN_CTRLERROR      (5)
+#define CAN_GETTXBFTIMEOUT (6)
+#define CAN_SENDMSGTIMEOUT (7)
+#define CAN_FAIL       (0xff)
+
+#define CAN_MAX_CHAR_IN_MESSAGE (8)
+
+#endif
+/*********************************************************************************************************
+  END FILE
+*********************************************************************************************************/

+ 2 - 2
SE/stuff/P5_Automation_can-dev-res-working-1930/_Slave_Ports_broadcast_func.h

@@ -351,10 +351,10 @@ void TASK_TYPE_T_Broadcast_state_LOW(Slave_Ports_Status_T* Slave_Ports_Status_A,
                     Serial.print(Slave_Ports_Status_A[i].IS_Local_A);
                     Serial.print(Slave_Ports_Status_A[i].IS_Local_A);
                     Serial.print("] ");  Serial.print("[DELETE PORT?]");
                     Serial.print("] ");  Serial.print("[DELETE PORT?]");
                     
                     
-                    if((Slave_Ports_Status_A[i].Broadcast_state - (TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 1000) ) < 0 ) //( TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 1000 )
+                    if((Slave_Ports_Status_A[i].Broadcast_state - (TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 2000) ) < 0 ) //( TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 1000 )
                         Slave_Ports_Status_A[i].IS_gone_A = IS_gone_TRUE ;
                         Slave_Ports_Status_A[i].IS_gone_A = IS_gone_TRUE ;
                      
                      
-                   //  INT_SAFE_DECREMENT_TO_LIMIT(Broadcast_state_TO_REFRESH,  Slave_Ports_Status_A[i].Broadcast_state,(TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 1000)  );
+                    INT_SAFE_DECREMENT_TO_LIMIT(Broadcast_state_TO_REFRESH,  Slave_Ports_Status_A[i].Broadcast_state,(TASK_TYPE_T_Slave_Ports_broadcast____time_min_run_MIN_A_INCREMENT_A / 2000)  );
                     
                     
                     
                     
                 
                 

+ 2 - 0
SE/stuff/P5_Automation_can-dev-res-working-1930/___loop/__main_loop_end.h

@@ -121,12 +121,14 @@ if(ARDUINO_LOOP_LATENCY_COUNTER__MAIN_END(ARDUINO_LOOP_LATENCY__MAIN_END_A, ARDU
                  
                  
                  
                  
                    #if defined(HAS_TFT_ILI9163C)
                    #if defined(HAS_TFT_ILI9163C)
+                    #if defined(USE_MESSAGE_OLD)
                             DISPLAY__print_menu( DISPLAY_A ,DISPLAY_T_ARDUINO_ATTR_ARRAY_A , DISPLAY_PHYSICAL_CHAR_A, 
                             DISPLAY__print_menu( DISPLAY_A ,DISPLAY_T_ARDUINO_ATTR_ARRAY_A , DISPLAY_PHYSICAL_CHAR_A, 
                                       1,  //DISPLAY_MENU_ITEM_INDEX_T DISPLAY_MENU_ITEM_INDEX_A
                                       1,  //DISPLAY_MENU_ITEM_INDEX_T DISPLAY_MENU_ITEM_INDEX_A
                                       time,time + ARDUINO_LOOP_LATENCY_DISPLAY_MENU//time_seq_id_A, (time_seq_id_A + 5000) 
                                       time,time + ARDUINO_LOOP_LATENCY_DISPLAY_MENU//time_seq_id_A, (time_seq_id_A + 5000) 
                                       ,Slave_Ports_Status_A 
                                       ,Slave_Ports_Status_A 
                                        );
                                        );
                     #endif
                     #endif
+                    #endif
                     
                     
               #else 
               #else 
                 
                 

+ 1 - 0
SE/stuff/P5_Automation_can-dev/P5_Automation_can-dev.xpr

@@ -7,6 +7,7 @@
     <projectTree name="P5_Automation_can-dev.xpr">
     <projectTree name="P5_Automation_can-dev.xpr">
         <folder name="Arduino">
         <folder name="Arduino">
             <folder path="../../../../Arduino/"/>
             <folder path="../../../../Arduino/"/>
+            <folder path="../P5_Automation-library-dev/"/>
         </folder>
         </folder>
         <folder path="../../../../Arduino/queue_test/"/>
         <folder path="../../../../Arduino/queue_test/"/>
         <folder path="../P5_Automation_can-dev-2/"/>
         <folder path="../P5_Automation_can-dev-2/"/>