This commit is contained in:
JonatanRek 2019-11-28 08:34:50 +01:00
commit 4229c44678
11 changed files with 505 additions and 29 deletions

View File

@ -1,3 +1,4 @@
//Includes
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
@ -20,16 +21,25 @@ DHT DHTs(pinDHT, DHT11);
void setup() {
Serial.begin(9600);
while (!Serial) continue;
delay(10);
Serial.println('\n');
//Show start up Configuration
Serial.println("HW: " + String(hwId));
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
Serial.print("MAC address:\t");
Serial.println(WiFi.macAdress());
pinMode(LIGHTPIN, INPUT);
}
void loop() {
//Start Conection to wifi
WiFi.begin(ssid, pasw);
checkConnection();
//HTTP CLIENT
HTTPClient http;
http.begin(url);
http.begin(url); //Begun HTTP Request
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
DHTs.begin();
@ -38,6 +48,7 @@ void loop() {
StaticJsonDocument<265> doc;
doc["token"] = hwId;
//Read and Handle DHT values
float tem = DHTs.readTemperature();
float hum = DHTs.readHumidity();
Serial.println("TEMP" + String(tem) + ";HUMI" + String(hum));
@ -50,6 +61,7 @@ void loop() {
doc["values"]["humi"]["unit"] = "%";
}
//Handle Photo Rezistor Values
doc["values"]["light"]["value"] = analogRead(LIGHTPIN);
doc["values"]["light"]["unit"] = "";
@ -59,16 +71,17 @@ void loop() {
Serial.print("JSON: ");
Serial.println(jsonPayload);
int httpCode = http.POST(jsonPayload);
int httpCode = http.POST(jsonPayload); //Get Http response code
String httpPayload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(httpPayload) + ""); //Print request response payload
DeserializationError error = deserializeJson(doc, httpPayload);
DeserializationError error = deserializeJson(doc, httpPayload); //Get deserialization Error if exists
//configuration setup
String hostName = doc["device"]["hostname"];
int sleepTime = doc["device"]["sleepTime"];
String ipAddress = doc["device"]["ipAddress"];
String state = doc["state"];
if (state != "succes") {
@ -78,25 +91,37 @@ void loop() {
unsuccessfulRounds = 0;
}
WiFi.hostname(hostName);
//Set static ip
IPAddress staticIpAddress;
IPAddress subnetIpAddress(192,168,0,1);
IPAddress gatewayIpAddress(255, 255, 255, 0);
if (staticIpAddress.fromString(ipAddress)) {
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
Serial.print("STATIC IP address:\t");
Serial.println(WiFi.localIP());
}
WiFi.hostname(hostName); //Set HostName
http.end(); //Close connection
WiFi.disconnect(); //Disconect from WIFI
Serial.println("DISCONECTED FROM WIFI");
WiFi.disconnect();
if(unsuccessfulRounds == 5) {
if(unsuccessfulRounds == 5) { //after 5 unsucessful request restart ESP
Serial.println("RESTARTING ESP");
ESP.restart()
}
if (sleepTime > 0) { //if deep sleepTime > 0 use deep sleep
Serial.println("GOING TO SLEEP FOR " + String(sleepTime));
if (sleepTime > 0) {
ESP.deepSleep((sleepTime * 60) * 1000000, RF_DEFAULT);
} else {
delay(5000);
}
}
//checking if connection is working
bool checkConnection() {
int count = 0;
Serial.print("Waiting for Wi-Fi connection");

View File

@ -0,0 +1,92 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = "";
const char* pasw = "";
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
const char* hwId = "";
int lastState = 0;
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
// WI-FI CONECTING
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pasw);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
delay(1000);
digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
delay(1000);
}
Serial.println("\nCONECTED TO WIFI");
Serial.println("IP: " + String(WiFi.localIP()));
}
bool buttonState = digitalRead(SONOFF_BUT);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
String requestJson = "{";
requestJson += "\"tocken\":\"" + String(hwId) + "\"";
if (buttonState == true) {
requestJson += ",";
requestJson += "\"on/off\":{";
requestJson += "\"value\":\"" + String(~lastState) + "\",";
requestJson += "\"unit\":\"\"";
requestJson += "}";
}
while(buttonState == true) {
delay(50); // keeps a small delay
}
requestJson += "}";
Serial.println("JSON: " + requestJson);
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
string hostname = doc["hostname"];
WiFi.hostname(hostname);
int state = doc["state"];
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, HIGH); // Turn the LED on by making the voltage LOW
}
lastState = state;
delay(1000);
}

View File

@ -0,0 +1,94 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = "";
const char* pasw = "";
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
const char* hwId = "";
int lastState = 0;
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
// WI-FI CONECTING
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pasw);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
delay(1000);
digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
delay(1000);
}
Serial.println("\nCONECTED TO WIFI");
Serial.println("IP: " + String(WiFi.localIP()));
}
bool buttonState = digitalRead(SONOFF_BUT);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
String requestJson = "{";
requestJson += "\"tocken\":\"" + String(hwId) + "\"";
if (buttonState == true) {
requestJson += ",";
requestJson += "\"on/off\":{";
requestJson += "\"value\":\"" + String(~lastState) + "\",";
requestJson += "\"unit\":\"\"";
requestJson += "}";
}
while(buttonState == true) {
delay(50); // keeps a small delay
}
requestJson += "}";
Serial.println("JSON: " + requestJson);
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
string hostname = doc["device"]["hostname"];
sleepTime = doc["device"]["sleepTime"];
WiFi.hostname(hostname);
int state = doc["state"];
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
digitalWrite(SONOFF_LED, HIGH); // Turn the LED on by making the voltage LOW
}
lastState = state;
delay(1000);
}

View File

@ -0,0 +1,94 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = " ";
const char* pasw = "";
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
const char* hwId = "";
int lastState = 0;
int reconectAtemptsMax = 10; //time to wait before restart
//Constant
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
delay(10);
Serial.println('\n');
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");
int i = 0;
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++i); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
}
void loop() {
StaticJsonDocument<200> jsonContent;
jsonContent["token"] = hwId;
if (!digitalRead(SONOFF_BUT)){
jsonContent["values"]["on/off"]["value"] = (int) !lastState;
if (!lastState == 1) {
digitalWrite(SONOFF, HIGH)
} else if (!lastState == 0){
digitalWrite(SONOFF, LOW)
}
while(!digitalRead(SONOFF_BUT)) {
delay(100);
}
}
String requestJson = "";
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
http.end();
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
deserializeJson(jsonContent, payload);
String hostname = jsonContent["device"]["hostname"];
int state = jsonContent["value"];
WiFi.hostname(hostname);
if (state != lastState){
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
}
}
lastState = state;
}

View File

@ -0,0 +1,136 @@
//Includes
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Variables
const char* ssid = " ";
const char* pasw = "";
const char* hwId = "";
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
int unsuccessfulRounds = 0; //time to wait before restart
int lastState = 0;
//Pins
#define SONOFF 12
#define SONOFF_LED 13
#define SONOFF_BUT 0
void setup() {
Serial.begin(9600);
while (!Serial) continue;
delay(10);
Serial.println('\n');
Serial.println("HW: " + String(hwId));
pinMode(SONOFF, OUTPUT);
pinMode(SONOFF_LED, OUTPUT);
pinMode(SONOFF_BUT, INPUT);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pasw);
checkConnection();
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
}
void loop() {
StaticJsonDocument<200> jsonContent;
jsonContent["token"] = hwId;
if (!digitalRead(SONOFF_BUT)){
jsonContent["values"]["on/off"]["value"] = (int) !lastState;
if (!lastState == 1) {
digitalWrite(SONOFF, HIGH)
} else if (!lastState == 0){
digitalWrite(SONOFF, LOW)
}
while(!digitalRead(SONOFF_BUT)) {
delay(100);
}
}
String requestJson = "";
serializeJson(jsonContent, requestJson);
Serial.println("JSON: " + requestJson);
//HTTP CLIENT
HTTPClient http;
http.begin(server);
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
int httpCode = http.POST(requestJson);
String payload = http.getString(); //Get the response payload
http.end();
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
Serial.println("HTTP BODY: " + String(payload) + ""); //Print request response payload
deserializeJson(jsonContent, payload);
String hostname = jsonContent["device"]["hostname"];
int state = jsonContent["value"];
DeserializationError error = deserializeJson(doc, httpPayload);
//configuration setup
String hostName = doc["device"]["hostname"];
String ipAddress = doc["device"]["ipAddress"];
String state = doc["state"];
if (state != "succes") {
unsuccessfulRounds++;
Serial.println("UNSUCCESSFUL ROUND NUMBER " + unsuccessfulRounds + "FROM 5");
} else if (state == "succes") {
unsuccessfulRounds = 0;
}
//Set static ip
IPAddress addr;
if (addr.fromString(ipAddress)) {
IPAddress ip(addr);
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
}
WiFi.hostname(hostName);
if(unsuccessfulRounds == 5) {
Serial.println("RESTARTING ESP");
ESP.restart()
}
if (state != lastState){
if (state == 1 && lastState == 0) {
Serial.println("ON");
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
} else {
Serial.println("OFF");
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
}
}
lastState = state;
}
bool checkConnection() {
int count = 0;
Serial.print("Waiting for Wi-Fi connection");
while ( count < 30 ) {
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("Connected!");
return (true);
}
delay(500);
Serial.print(".");
count++;
}
Serial.println("Timed out.");
return false;
}

View File

@ -189,6 +189,7 @@ if ($values != null || $values != "") {
$jsonAnswer = [
'device' => [
'hostname' => $hostname,
'ipAddress' => $device['ip_address'],
],
'state' => 'succes',
];
@ -223,6 +224,7 @@ if ($values != null || $values != "") {
'device' => [
'hostname' => $device['name'],
'sleepTime' => $device['sleep_time'],
'ipAddress' => $device['ip_address'],
],
'state' => 'succes',
'value' => $subDeviceLastReordValue

View File

@ -23,9 +23,11 @@ class DeviceManager{
}
public function create ($name, $token) {
$defaultRoom = RoomManager::getDefaultRoomId();
$device = array (
'name' => $name,
'token' => $token,
'room_id' => $defaultRoom,
);
try {
Db::add ('devices', $device);

View File

@ -0,0 +1,18 @@
<?php
/**
*
*/
class NetvorkManager
{
function __construct()
{
// code...
}
function validateIp($ip = '0.0.0.0'){
if (!filter_var($ip, FILTER_VALIDATE_IP)){
return false;
}
}
}

View File

@ -2,6 +2,11 @@
class RoomManager{
public static $rooms;
function getDefaultRoomId() {
$defaultRoom = Db::loadOne("SELECT id FROM rooms WHERE default = 1");
return $defaultRoom['id'];
}
function getAllRooms () {
$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
return $allRoom;

View File

@ -62,15 +62,22 @@
<div class="label">Token:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['token']; ?>" disabled>
</div>
<?php //TODO: firmware tipe send to api?>
<h4 class="mb-4"><?php $LANGMNG->echo('t_networkSetting'); ?></h4>
<div class="field">
<div class="label">Type:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['type']; ?>" disabled>
</div>
<?php //TODO: add Static Ip Functionality?>
<div class="field">
<div class="label">IP:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['ip']; ?>" disabled>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['ip']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<div class="field">
<div class="label">Subnet:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['subnet']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<div class="field">
<div class="label">Gateway:</div>
<input class="input" type="text" name="deviceToken" value="<?php echo $DEVICE['gateway']; ?>" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$" disabled>
</div>
<?php if ($DEVICE['userIsAdmin']) { ?>
<?php if (!in_array($SUBDEVICE['type'], ['on/off', 'door', 'water'])) { ?>

View File

@ -157,6 +157,7 @@ class Home extends Template
'room' => $deviceData['room_id'],
'token' => $deviceData['token'],
'type' => $deviceData['type'],
'ip' => $deviceData['ip_address'],
'sleepTime' => $deviceData['sleep_time'],
'approved' => $deviceData['approved'],
'permission' => $permissionArray,