#include <OneWire.h>                                       		// library for the oneWire digital pins
#include <SPI.h>                                                     	                   	// A Brief Introduction to the Serial Peripheral Interface 
#include <Ethernet.h>                                    		                   	// library for ethernet functions
#include "SPI.h"
//#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

//=============Preferences============
//-------------Pins-------------------
OneWire ds(2);                                                           	   	// declare 1Wire digital pins
//--------------Network-Arduino-------
//static char user[] = "arduino";                                             	// SQL-Nutzer direct link about SQL-Connector
//static char password[] = "pi";                                             	// SQL-Kennwort direct link about SQL-Connector
static IPAddress server_addr(192, 168, 1, 1);                                	// IP-Adresse Server
static byte my_mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x9B, 0xC3 };       // MAC-Adress Arduino 
static IPAddress ip(192, 168, 1, 102);                                          	// IP-Adress Arduino
//const unsigned int t_delay=1000;                                            	// Pausenzeit
EthernetClient client;                                                        		// EthernetClient - Instance build
Connector my_conn;                                                           		// Connector - Instance build
//--------------PhP--Adress-----------
char host[]    = "www.sonds.org";                                            	// Domain from Server
char url[]     = "/Transmit_Data.php";                                        	// Path from the PHP-File
char key[]     = "MEINPASSWORT123";                                           	// Keyword from PHP-File
char c;                                                                       		// Variable for answer from Servers
long Interval  = 5;                                                           		// Upload-Interval
//-------------Settings/Variable------
byte addr_oneWire_next[8];                                                    	// buffer for Address 1Wire
int addr_onewire_counter = 0;                                                 	// Variable to loop the Values for Address from 1Wire
byte addr_oneWire[10][8];                                                     	// Array for oneWire Adress
byte present = 0;                                                             		// counter for return text Server
byte data_oneWire[10][12];                                                    	// Array Values from 1Wire
int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract;   // Variable to convert the Hex-Values into a decimal value
char buffer1[10];                                                             		// buffer to translate the Hex-code from 1wire
char buffer2[10];                                                            		// buffer to translate the Hex-code from 1wire
char minus[2] = "-";                                                          		// charset to translate the hex-code from 1wire 
char point[2] = ",";                                                          		// charset to translate the hex-code from 1wire (german)
char values_float[10][20];                                                    	// values 1wire in °C and decimal
int datapoint = 0;                                                           		// counter for sequence transmit the values 
//-------------Initialize-------------
void setup() 
   {
   Ethernet.begin(my_mac, ip);                                                	// Ethernet start
   Serial.begin(115200);                                                      		// Serial start
   delay(2000);                                                               		// wait for Ethernet and Serial
   Serial.println("Connecting...");
   }
//--------------Controller------------
void loop(void)                                                               		// control-loop
   {
     
   Read_sensors_1wire_adress();                                               	// read adresses from 1wire                                                
   Read_sensors_1wire_data();                                                 	// read value from 1wire and convert in decimal
   Monitor();                                                                 		// print out adress and value on monitor
   delay(2000);                                                               		// wait for read and write data on lcd
                    
   for(datapoint=0; datapoint < addr_onewire_counter ; datapoint++)           // send count winning data from 1wire to Server
      {
      Send_data_php_mysql(datapoint);                                         	// send to server
      delay(2000);                                                            		// wait 2000ms 

       byte maxReads = 10;                                                    		// Seconds
       while ((maxReads-- > 0) && client.connected())                         	// wait and read answer from database
         {
         delay(1000);                                                         		// wait
         while (client.available())                                           
           {
           char response = client.read();
           Serial.print(response);
           }
         }
       client.stop();                                                         		// stop client com.
       Serial.println("Done.");               
       client.flush();                                                        		// client füllen
       
       }
       //delay(60000);                                                          		// walt 1 min to repeat the control loop
    }  

 
void Monitor(){                                                               		// Sende Data on Monitor
    for(int j=0; j<10; j++)                                                                                          
       {
       if(j < addr_onewire_counter)                                           	// with void arrays counter
          {  
          Serial.print("Adress:     ");
          for(int i = 0; i < 10; i++)                                 
             {
             Serial.print(addr_oneWire[j][i], HEX);                           
             Serial.print(" ");
             }
          Serial.print("      Value:      ");
          for(int i = 0; i < 8; i++) 
             {
             Serial.print(data_oneWire[j][i], HEX);
             Serial.print(" ");
             }   
          Serial.print("      ");    
          Serial.print(values_float[j]);
          Serial.print("\n");  
          }          
     }
}						
//===================================
//API : GET /Transmit_Data.php?key=MEINPASSWORT123&mac_addr_arduino=0xmy_mac[0]&sensor_addr=0xaddr_oneWire[datapoint][0]&value_hex=0xdata_oneWire[datapoint][0]&value_direct=0xvalues_float[datapoint][0])  \r\n" HTTP/1.0 Host: www.sonds.org \r\n
//===================================
 
void Send_data_php_mysql(int datapoint)                                        	// Sende data to Database                   
   {  
   if (client.connect(server_addr, 80))                                        	// Verbindung zum Server aufbauen
      {
      Serial.println("Verbunden, Sende Daten...");           
      client.print("GET /Transmit_Data.php");                                  	// Outside connection
      client.print("?key=MEINPASSWORT123");                                    	// key = password Database
      client.print("&mac_addr_arduino=");                                      	// Start transmit Data     
      for(int i = 0; i<6; i++)                               
         {
       // client.print(" 0x");
         client.print(my_mac[i], HEX);
       //  if(i<5)
       //     {
       //     client.print("_"); 
       //    }  
         }   


      client.print("&sensor_addr=");
      for(int i = 0; i<8; i++)
         {
       //  client.print("0x");
         client.print(addr_oneWire[datapoint][i], HEX); 
       //  if(i<7)
       //     {
       //      client.print("_"); 
       //     }  
         }   
      client.print("&value_hex=");
      for(int i = 0; i<12; i++)
         {
       //  client.print("0x");
         client.print(data_oneWire[datapoint][i], HEX);  
       // if(i<11)
       //     {
       //      client.print("_"); 
       //     } 
         }         
      client.print("&value_direct=");
      for(int i = 0; i<6; i++)
         {
       // client.print("0x");
         client.print(values_float[datapoint][i]);
       //  if(i<5)
       //     {
       //      client.print("_"); 
       //     } 
         }    
      client.print("  \r\n");                                                    		// Settings coming....
      client.print("HTTP/1.0");                                                  	// Protocoltyp 
      client.print("Host: www.sonds.org \r\n");                                  	// URL from Database
      client.println();                                                          		// Transmit end !!
      }
      else
      {
      Serial.println(" *_*_*_*_* VERBINDUNG ZUM SERVER KANN NICHT HERGESTELLT WERDEN *_*_*_*_* ");
      }
}
void Read_sensors_1wire_adress()
  {
      addr_onewire_counter = 0;
      for(int j=0; j<10; j++)
      {
         if ( ds.search(addr_oneWire_next))                                     	// adress in
             {
             addr_onewire_counter++;                                            	// counter sensors
             for(int l=0;l<8; l++)
                {
                addr_oneWire[j][l]  = addr_oneWire_next[l];                     	// wirte in Array Adress
                }
             }
             else
                {
                Serial.print("No more addresses.\n");  
                ds.reset_search(); 
                return;  
                }
         }  
  }   

  

void Read_sensors_1wire_data()
  {
   for (int j=0; j<10;j++)
       {
        ds.reset();                                                         		// RESET Com. Don´t touch it... 
        ds.select(addr_oneWire[j]);                                         	// choose datapoint
       
        ds.write(0x44);                                                     // start conversion, with out parasite power on at the pin. ((0x44, 1) = On)
        delay(1000);                                                           // normally you need 750ms, whyever i'm need 1000ms for an constance procedure
        present = ds.reset();
        ds.select(addr_oneWire[j]);    
        ds.write(0xBE);                                                     		// Read Scratchpad  
       
         for (int i = 0; i < 9; i++)                                        		// we need 9 bytes
             {           
             data_oneWire[j][i] = ds.read();
             } 
             
         LowByte = data_oneWire[j][0];
         HighByte = data_oneWire[j][1];
         TReading = (HighByte << 8) + LowByte;
         SignBit = TReading & 0x8000;                                       	// test most sig bit
         if (SignBit)                                                       		// negative
            {
             TReading = (TReading ^ 0xffff) + 1;                            	// 2's comp
            }
         Tc_100 = (6 * TReading) + TReading / 4;                            	// multiply by (100 * 0.0625) or 6.25
         Whole = Tc_100 / 100;                                              		// separate off the whole and fractional portions
         Fract = Tc_100 % 100;
         for(int x=0; x<20; x++) 
            {
            values_float[j][x]='\0';                                        		// Clear Array
            }
         itoa(Whole, buffer1, 10);                                          		// Convert to char
         itoa(Fract, buffer2, 10);      
         if (SignBit)                                                       		// If its negative
            {
            strcat(values_float[j], minus);
            }  
      strcat(values_float[j], buffer1);                                     	// set Char2 after Char1
      strcat(values_float[j], point);
      strcat(values_float[j], buffer2);
      ds.reset();                                                           		// reset oneWire com.      
      } 
  }  

