/*
 WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi Shield (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 5.

 If the IP address of your shield is yourAddress:
 http://yourAddress/H turns the LED on
 http://yourAddress/L turns it off

 This example is written for a network using WPA2 encryption. For insecure
 WEP or WPA, change the Wifi.begin() call and use Wifi.setMinSecurity() accordingly.

 Circuit:
 * WiFi shield attached
 * LED attached to pin 5

 created for arduino 25 Nov 2012
 by Tom Igoe

ported for sparkfun esp32
31.01.2017 by Jan Hendrik Berlin

 */

#include <WiFi.h>

const char *ssid = "MiFibra-F74B";
const char *password = "rKdvwXv2";

NetworkServer server(80);
#include <ModbusIP_ESP8266.h>

//Modbus Registers Offsets
const int SENSOR_IREG = 10;
const int SENSOR_IREG2 = 11;

ModbusIP *mb;
long ts;

void setup() {
  Serial.begin(115200);
  pinMode(5, OUTPUT);  // set the LED pin mode
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP());
  server.begin();
  // ModbusIP mb;
  mb = new ModbusIP();
  mb->server();

  mb->addHreg(SENSOR_IREG);
  mb->addHreg(SENSOR_IREG2);
  mb->addCoil(1);
  mb->addCoil(2);

/*
   mb.server();		//Start Modbus IP
    // Add SENSOR_IREG register - Use addIreg() for analog Inputs
    mb.addHreg(SENSOR_IREG);
    mb.addHreg(SENSOR_IREG2);
    mb.addCoil(1);
    mb.addCoil(2);
*/
    ts = millis();
}
int val = 0;

void loop() {
  mb->task();
   //Read each two seconds
   if (millis() > ts + 10) {
       ts = millis();
       //Setting raw value (0-1024)
       val = val + 2;
       if(val>1024){
        val = 0;
       }
       mb->Hreg(SENSOR_IREG,val);
       mb->Hreg(SENSOR_IREG2,val  /2 );
       mb->Coil(1,val % 2);
       mb->Coil(2,val);
   }
   delay(100);
}
