////////////////////////////////////////////////////////////////////////////////
// Name:       LanEnc28J60-Mega02                                             //
// http://robotigs.com/robotigs/includes/parts_header.php?idpart=313          //
//             Server test of ethernet controller                             //
// Platform:   Arduino Mega 2560                                              //
// Created by: HARB rboek2@gmail.com januari 2019 GPL copyrights              //
// Thanks to:  Library DHT 2011 by Limor Frie, modified 2012 by Tom Igoe      //
// As outputs the following modules are mounted:                              //
// - Standard Arduino Onboard LED (PWM)                                       //
// - 3 color LED (PWM)                                                        //
// - Buzzer activ (dio)                                                       //
// For communications are mounted:                                            //
// - Standard Serial Monitor output                                           //
////////////////////////////////////////////////////////////////////////////////





////////////////////////////////////////////////////////////////////////////////
//3456789112345678921234567893123456789412345678951234567896123456789712345678//
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////





// SET PRECOMPILER OPTIONS *****************************************************
  // Initialse conditional compiling, uncomment to include, comment to exclude -
  // Do comment the next line for runtime versions -----------------------------
  #define RS232                   //Uncomment to include Serial Monitor sections
  //#ifdef RS232     //Only include these lines if the variable has been defined

  // Define the needed header files for the precompiler, no charge if not used -
  #include <UIPEthernet.h>       //ENC28J60 by https://github.com/ntruchsess LAN
  #include <OneWire.h>     // Used for temperature sensor(s)

  // Define precompiler variables, runs faster & doesn`t use RAM ---------------
  // Define PINS ---------------------------------------------------------------
  #define ledRedPin    44         //3 Colour LED, which PWM pin connects RED LED
  #define ledGrePin    45       //3 Colour LED, which PWM pin connects GREEN LED
  #define ledBluPin    46        //3 Colour LED, which PWM pin connects BLUE LED
  #define buzAct       A7          //Define DIO output pin connects ACTIV BUZZER

  //#define SpiMISO      50         //Orange  50 - PB3 -- MISO/PCINT3  SPI pin LAN
  //#define SpiMOSI      51            //Green 51 - PB2 -- MOSI/PCINT2 SPI pin LAN
  //#define SpiSCK       52            //Yellow 52 - PB1 -- SCK/PCINT1 SPI pin LAN
  //#define SpiSS        53               //Blue 53 - PB1 -- SS/PCINT0 SPI pin LAN

  //Define EEPROM variables ----------------------------------------------------
  //Define DATABASE VARIABLES --------------------------------------------------
  //Define VARIABLES -----------------------------------------------------------
  bool        ledOnBoardVal  = LOW;  //You choose HIGH=on or LOW=off LED_BUILTIN
  byte        msWait         = 2;       //Test your patience during the test LED
  byte        brillance      = 0;     //Brightness of any color, to test PWM LED
  uint8_t     mac[6]         = {0x00,0x01,0x02,0x03,0x04,0x05};            //LAN
                    // Ethernet MAC address - must be unique on your network MAC
                    
  // Initialize OBJECTS --------------------------------------------------------
  EthernetServer server(80);                                               //LAN
  EthernetClient client;                                                   //LAN
  OneWire  ds(17);                                                     //DS18B20

  signed long next;
//END OF PRECOMPILER OPTIONS ---------------------------------------------------



void setup() { // **************************************************************
  disable_jtag();         //Disable jtag to free port C, enabled by default JTAG
  Serial.begin(9600);         //Nothing more needed for the Serial Monitor RS232
     
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  pinMode(buzAct, OUTPUT);                    //Set this pin as output to BUZZER
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  pinMode(ledRedPin, OUTPUT);                 //Set this pin as output to redLED
  pinMode(ledBluPin, OUTPUT);                //Set this pin as output to blueLED
  pinMode(ledGrePin, OUTPUT);               //Set this pin as output to greenLED

  //Start objects --------------------------------------------------------------
  Ethernet.begin(mac);              //Create connection  IP address via DHCP LAN
  server.begin();                                    //Start listening at he LAN
  //next = 0;
  
  //Test hardware and software -------------------------------------------------
  test_LEDs();            //PWM fade in and fade out for all 4 LEDs on board LED
  Serial.print  ("Ethernet.localIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print  ("subnetMask:       ");
  Serial.println(Ethernet.subnetMask());
  Serial.print  ("gatewayIP:        ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print  ("dnsServerIP:      ");
  Serial.println(Ethernet.dnsServerIP());
  Serial.print  ("ACTLOGLEVEL:      ");
  Serial.println(ACTLOGLEVEL);
  Serial.print  ("LOG_NONE:         ");
  Serial.println(LOG_NONE);
  
  beep(10);                       //Create a test beep with KY-012 active BUZZER
  Serial.println ("Setup klaar");
  Serial.println  (""); 
} //End of setup ---------------------------------------------------------------




void loop() { //KEEP ON RUNNING THIS LOOP FOREVER  *****************************
  client = server.available();                 //Listen for incoming clients LAN
  if (client)  {  
    Serial.println("-> New Connection\n");
    boolean currentLineIsBlank = true;  //An http request ends with a blank line
    
    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)  {
          client.println("<?xml version='1.0'?>\n<sensordata>");
          Serial.println("   Collecting Sensor Data:");
          TemperaturesToXML();
          client.println("</sensordata>");
          Serial.println("\n   Done Collecting Sensor Data");
          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;
        }
      }
    }

    delay(10);    // give the web browser time to receive the data
    client.stop();                                        //Close the connection
    Serial.println("   Disconnected\n");
  }
  toggle_ledOnBoard();           //Toggles the LED_BUILTIN  ON or OFF onboardLED
} //End of void loop() ----------------------- KEEP ON RUNNING THIS LOOP FOREVER



void TemperaturesToXML(void) {
  byte counter;
  byte present = 0;
  byte sensor_type;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;
  
  ds.reset_search();
  
  while ( ds.search(addr)) {
    client.println("<sensor>");
  
    // Get Serial number
    client.print("  <serial>");
    Serial.print("\n   Sensor     : ");
    
    for( counter = 0; counter < 8; counter++) 
    {
      if (addr[counter]<10) client.print("0");
      client.print(String(addr[counter], HEX));
      client.print(" ");
      
      if (addr[counter]<10) Serial.print("0");
      Serial.print(String(addr[counter], HEX));
      Serial.print(" ");
    }
    Serial.println();
    
    client.println("</serial>");
    
    // Check CRC
    if (OneWire::crc8(addr, 7) != addr[7]) 
    {
        client.println("  <status>Invalid CRC</status>\n</sensor>");
        Serial.println("   ERROR\n");
        return;
    }
    
    client.println("  <status>OK</status>");
    
    // Get Chip type (the first ROM byte indicates which chip)
    client.print("  <chip>");
    
    switch (addr[0]) 
    {
      case 0x10:
        client.println("DS18S20");
        sensor_type = 1;
        break;
      case 0x28:
        client.println("DS18B20");
        sensor_type = 0;
        break;
      case 0x22:
        client.println("DS1822");
        sensor_type = 0;
        break;
      default:
        client.println("undefined</chip>");
        return;
    } 
    client.println("</chip>");
    
    ds.reset();
    ds.select(addr);
    ds.write(0x44);  // start conversion, with regular (non-parasite!) power
    
    delay(1000);     // maybe 750ms is enough, maybe not
    
    present = ds.reset();
    ds.select(addr);    
    ds.write(0xBE);  // Read Scratchpad
    
    // Get Raw Temp Data
    for ( counter = 0; counter < 9; counter++) 
    {           // we need 9 bytes
      data[counter] = ds.read();
    }

/*  
    // Alternative: Get Raw Data, but also send it in the XML
    
    client.print("  <rawdata>");
    if (present<10) client.print("0");
    client.print(String(present, HEX));
    client.print(" ");
    
    for ( counter = 0; counter < 9; counter++) 
    {           // we need 9 bytes
      data[counter] = ds.read();
      if (data[counter]<10) client.print("0");
      client.print(String(data[counter], HEX));
      client.print(" ");
    }
    
    client.println("</rawdata>");
*/

    // Convert the data to actual temperature
    // because the result is a 16 bit signed integer, it should
    // be stored to an "int16_t" type
    int16_t raw = (data[1] << 8) | data[0];
    
    if (sensor_type) 
    {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
    } 
    else 
    {
      // at lower res, the low bits are undefined, so let's zero them
      byte cfg = (data[4] & 0x60);
      
      //// default is 12 bit resolution, 750 ms conversion time
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    }
    
    celsius = (float)raw / 16.0;
    fahrenheit = celsius * 1.8 + 32.0;
    
    client.print("  <celsius>");
    client.print(celsius);
    client.print("</celsius>\n  <fahrenheit>");
    client.print(fahrenheit);
    client.println("</fahrenheit>");
    
    Serial.print("   Temperature: ");
    Serial.print(celsius);
    Serial.print(" C  (");
    Serial.print(fahrenheit);
    Serial.println(" F)");
    
    client.println("</sensor>");
  } 
  
  return;
}


 

void test_LEDs(void){ //PWM fade in and fade out for all 4 LEDs on board *******
  brillance = 0;                 //Brightness of any color, just to test PWM LED
  
  while (brillance<255){
    analogWrite(ledRedPin, brillance);        //Set LED to desired PWM value RED
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledRedPin, brillance);        //Set LED to desired PWM value RED
    brillance--;
    delay (msWait);
  }
  analogWrite(ledRedPin, 0);            //Set LED to desired PWM value = off RED


  while (brillance<255){
    analogWrite(ledGrePin, brillance);      //Set LED to desired PWM value GREEN
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledGrePin, brillance);      //Set LED to desired PWM value GREEN
    brillance--;
    delay (msWait);
  }
  analogWrite(ledGrePin, 0);          //Set LED to desired PWM value = off GREEN

  
  while (brillance<255){
    analogWrite(ledBluPin, brillance);       //Set LED to desired PWM value BLUE
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(ledBluPin, brillance);       //Set LED to desired PWM value BLUE
    brillance--;
    delay (msWait);
  }
  analogWrite(ledBluPin, 0);           //Set LED to desired PWM value = off BLUE
  
  
  while (brillance<255){
    analogWrite(LED_BUILTIN, brillance);  //Set to desired PWM value LED_BUILTIN
    brillance++;
    delay (msWait);
  }
  while (brillance>0){
    analogWrite(LED_BUILTIN, brillance);  //Set to desired PWM value LED_BUILTIN
    brillance--;
    delay (msWait);
  }
  analogWrite(LED_BUILTIN, 0);  //Set LED to desired PWM value = off LED_BUILTIN
} //Exit test_LEDs -------------------------------------------------------------




void beep(uint8_t ms) { //Create a beep with KY-012 active buzzer **************
  digitalWrite(buzAct,HIGH);                                    //Turn buzzer on
  while (ms > 0){                            //Timer of the duration of the beep
    delay(5);                                                //Wait milliseconds
    ms--;                                     //Countdown untill we reached zero
  }            //Timer of the duration of the beep has been counted down to zero
  digitalWrite(buzAct,LOW);        //Turn annoying buzzer off as fast as you can
} //Exit beep ------------------------------------------------------------------




void toggle_ledOnBoard(void){ //Toggles the LED_BUILTIN on-board LED on or off *
  ledOnBoardVal = !ledOnBoardVal;                                 //Toggle value
  digitalWrite(LED_BUILTIN, ledOnBoardVal);     //Set Arduino boards onboard LED
} //Exit toggle_ledBin ---------------------------------------------------------




void disable_jtag(void) { //Disable jtag to free port C, enabled by default ****
#if defined(JTD)                           //Not all AVR controller include jtag
  MCUCR |= ( 1 << JTD );                                //Write twice to disable
  MCUCR |= ( 1 << JTD );                                       //So stutter once
#endif                                            //End of conditional compiling
} //Exit jtag_disable ----------------------------------------------------------




////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO MEGA 2560                                    //
// Board  -Atmel- PIN - IDE - Function          - External Connection    FUNC //
//                                                                            //
// CONNECTIONS RAILS TOP LEFT: DIGITAL PWM<~> ******************************* //
// SCL    -  28 - PC5 -19/A5- ADC5/SCL/PCINT13  - DS1307 SCL orange       TWI //
// SDA    -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  - DS1307 SDA white        TWI //
// AREF   -  31 - REF -     - AREF              -                         REF //

// 13 PWM -  26 - PB7 -  13 - OC0A/OC1C/PCINT17 - LED Arduino LED_BUILTIN PWM //
// 12 PWM -  18 - PB6 -  12 - OC1B/PCINT16      -                         PWM //
// 11 PWM -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  -                         PWM //
// 10 PWM -  16 - PB2 -  10 - SS/OC1B/PCINT2    -                         PWM //
//  9 PWM -  15 - PB1 -   9 - OC1A/PCINT1       -                         PWM //
//  8 PWM -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  -                         DIO //
//                                                                            //
// CONNECTIONS RAILS TOP MIDDLE: DIGITAL PWM<~> ***************************** //
//  7 PWM -  13 - PD7 -   7 - PCINT23/AIN1      -                         PWM //
//  6 PWM -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                         PWM //
//  5 PWM -  11 - PD5 -   5 - PCINT21/OC0B/T1   -                         PWM //
//  4 PWM -   6 - PD4 -   4 - PCINT20/XCK/T0    -                         PWM //
//  3 PWM -   5 - PD3 -   3 - PCINT19/OC2B/INT1 -                         PWM //
//  2 PWM -   4 - PD2 -   2 - PCINT18/INT0      -                         INT //
//  1 TX0 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor          TX0 //
//  0 RX0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial Monitor          RC0 //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 14 TX3 -  13 - PD7 -   7 - PCINT23/AIN1      -                         DIO //
// 15 RX3 -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                         PWM //
// 16 TX2 -  11 - PD5 -   5 - PCINT21/OC0B/T1   -                         TX2 //
// 17 RX2 -   6 - PD4 -   4 - PCINT20/XCK/T0    - DS18B20 green           RX2 //
// 18 TX1 -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - Transmit to ESP01 blue  INT //
// 19 RX1 -   4 - PD2 -   2 - PCINT18/INT0      - Rec from ESP01 yellow   INT //
// 20 SDA -   3 - PD1 -   1 - PCINT17/TXD       - DS1307 white            TWI //
// 21 SCL -   2 - PD0 -   0 - PCINT16/RCD       - DS1307 orange           TWI //
//                                                                            //
// CONNECTIONS RAILS BOTTOM LEFT: POWER ************************************* //
// 5V     -   7 - VCC -     - VCC               -                         VCC //
// RES    -   1 - RES -     - PCINT14/RESET     -                         RES //
// 3.3V   -     -     -     -                   -                             //
// 5V     -     -     -     -                   -                             //
// GND    -     -     -     -                   -                             //
// GND    -     -     -     -                   -                             //
// Vin    -     -     -     -                   -                             //
//                                                                            //
// CONNECTIONS RAILS BOTTOM CENTER: ANALOG IN ******************************* //
// A0     -  23 - PC0 -A0/14- ADC0/PCINT8       -                         ADC //
// A1     -  24 - PC1 -A1/15- ADC1/PCINT9       -                         ADC //
// A2     -  25 - PC2 -A2/16- ADC2/PCINT10      -                         ADC //
// A3     -  26 - PC3 -A3/17- ADC3/PCINT12      -                         ADC //
// A4     -  27 - PC4 -A4/18- ADC4/SDA/PCINT12  -                         TWI //
// A5     -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  -                         TWI //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A08    -  89 - PK0 -     - ADC1 4/PCINT?     - Moisture Capac yellow   ADC //
// A09    -  88 - PK1 -     - ADC15/PCINT?      -                         ADC //
// A10    -  87 - PK2 -     - ADC14/PCINT?      -                         ADC //
// A11    -  86 - PK3 -     - ADC15/PCINT?      -                         ADC //
// A12    -  85 - PK4 -     - ADC14/PCINT?      -                         ADC //
// A13    -  84 - PK5 -     - ADC15/PCINT?      -                         ADC //
// A14    -  83 - PK6 -     - ADC14/PCINT22     -                         ADC //
// A15    -  82 - PK7 -     - ADC15/PCINT23     -                         ADC //
//                                                                            //
// CONNECTIONS RAILS QUER RIGHT ********************************************* //
// Board  -Atmel- PIN - IDE - Function          - External Connection    FUNC //
// 32     -  58 - PC5 -     - DIO               -                         DIO //
// 44     -  40 - PL5 -     - OC5C              - 3 Color led Red         PWM //
// 45     -  39 - PL4 -     - OC5B              - 3 Color led Blue        PWM //
// 46     -  38 - PL3 -     - OC5A              - 3 Color led Green       PWM //
// 47     -  37 - PL2 -     - T5                - DHT22 one-wire white    DIO //
// 48     -  36 - PL1 -     - ICP5              -                         DIO //
// 49     -  35 - PL0 -     - ICP4              -                         DIO //
// 50     -  22 - PB3 -     - MISO/PCINT3       -                         SPI //
// 51     -  21 - PB2 -     - MOSI/PCINT2       -                         SPI //
// 52     -  20 - PB1 -     - SCK/PCINT1        -                         SPI //
// 53     -  19 - PB1 -     - SS/PCINT0         -                         SPI //
// 54     -     - GND -     - GND               -                         GND //
// 55     -     - GND -     - GND               -                         GND //
////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////
//3456789112345678921234567893123456789412345678951234567896123456789712345678//
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
// 0001  0001      1 wateringProg Usr choice: 1=off 2=on 3=auto RELAY1        //
// 0002  0003      2 wateringON If CAPAC reaches this 2byte treshold RELAY1   //
// 0004  0005      2 wateringSecs How many seconds to keep ON RELAY1          //
// 0006  0006      1 Temperature/10 airheater Switch ON RELAY2 (0-25,5)       //
// 0007  0007      1 Temperature/10 airheater Switch OFF RELAY2 (0-25,5)      //
// 0008  0008      1 Usr choice: airheater 1=off 2=on 3=auto RELAY2           //
// 0009  0009      1 Temperature/10 heat coil Switch ON RELAY3 (0-25,5)       //
// 0010  0010      1 Temperature/10 heat coil Switch OFF RELAY3 (0-25,5)      //
// 0011  0011      1 Usr choice: heatcoil 1=off 2=on 3=auto RELAY3            //
// 0012  0012      1 Number of hours around noon GROWLED RELAY4               //
// 0013  0013      1 /Usr choice: growled 1=off 2=on 3=auto RELAY4            //
////////////////////////////////////////////////////////////////////////////////


//345678911234567892123456789312345678941234567895123456789612345678971234567898
////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=0)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////