Мой проект умного дома "iHouse"

elik745i
Offline
Зарегистрирован: 08.04.2012

Evg-Chugunov пишет:

Эзернет шилд заказан и где то идет. Просто экран первым пришел, хотел побаловаться пока))

 

Понятно :)

Последняя версия прошивки я удалил экран, так как нужно было место для дополнительного кода, который позволяет регистрировать стандартные датчики охранных систем.

Умный дом становится еще умнее и полезнее ))))

elik745i
Offline
Зарегистрирован: 08.04.2012

Последние несколько дней внедрял вебинтерфейс звонилки и функцию отправки СМСок через интерфейс умного дома, все получилось!

Ждите видео.

Valerii_K
Valerii_K аватар
Offline
Зарегистрирован: 15.08.2016

elik745i пишет:

220 переменный ток - трансформатор - выпрямитель - резисторный делитель - аналоговая нога дуины - вычисление напряжения сети

датчик тока - аналоговая нога дуины - вычисление тока

перемножение - мощность - просто? можно брать семплы и по сложной схеме вычислять вплоть до кос фи!

Добрый день! А можно пожалуйста поподробнее, марки, схемки, ссылки где заказывали детали? Очень заинтересовал проект.

elik745i
Offline
Зарегистрирован: 08.04.2012

Сборка на бумажном макете, помогает определить оптимальное расположение электронных компонентов намного лучше, чем в 3Д.

20161127_175135.jpg

20161127_191651.jpg

20161127_191659.jpg

20161127_191705.jpg

 

elik745i
Offline
Зарегистрирован: 08.04.2012

Valerii_K пишет:

elik745i пишет:

220 переменный ток - трансформатор - выпрямитель - резисторный делитель - аналоговая нога дуины - вычисление напряжения сети

датчик тока - аналоговая нога дуины - вычисление тока

перемножение - мощность - просто? можно брать семплы и по сложной схеме вычислять вплоть до кос фи!

Добрый день! А можно пожалуйста поподробнее, марки, схемки, ссылки где заказывали детали? Очень заинтересовал проект.

 

Все есть тут в 3м посту, пишите что конкретно хотите отвечу.

SanyaKreks
Offline
Зарегистрирован: 28.11.2016

Всем Добрый день. ТС огромное спасибо за проделанную работу.

Теперь вопросик на засыпку Такая железка подойдёт?

SanyaKreks
Offline
Зарегистрирован: 28.11.2016

ттх

GSM A6 module:
– dimensions of 22.8 16.8 2.5mm;
– Operating temperature -30 to + 80 ;
– Operating Voltage 3.3V-4.2V;
– Power voltage> 3.4V;
– Standby average current 3ma less;
– support the GSM / GPRS four bands, including 850,900,1800,1900MHZ;
– Sensitivity <-105;
– support voice calls;
– support SMS text messaging;
– Support GPRS data traffic, the maximum data rate, download 85.6Kbps, upload 42.8Kbps;
– Supports standard GSM07.07,07.05 AT commands and extended commands Ai Thinker;
– supports two serial ports, a serial port to download an AT command port;
– command supports the standard AT and TCP / IP command interface;
– support digital audio and analog audio support for HR, FR, EFR, AMR speech coding;
– Support 2G 3G 4G mobile card Unicom card
– support ROHS, FCC, CE, CTA certification;
– the SMT 42PIN package;

Module Pin Flag:
VCC_IN: Power Supply Input 5V -9V
GND: power ground
U_TXD: A6 module to send (TTL level)
U_RXD: A6 receiving module (TTL level)
RS232_TX: 232 serial port
RS232_RX: 232 serial port to receive
HTXD: Serial Interface Upgrade
HRXD: Serial Interface Upgrade
MIC- \ MIC +: microphone input
REC + \ REC-: Speaker output
INT: Control module is used to enter a low-power mode, high back
Out into the low
PWR: power button,> 1.9V more than 2s to boot
(Module hardware to do the processing, power is automatically turned on, eliminating the need for wiring trouble)

EN: MP1584 power chip enable pin, pulled enable power chip, low enabled, this pin can be used as module reset pin enable

просто лежит в магазе за углом за 450 рубликов

 

elik745i
Offline
Зарегистрирован: 08.04.2012

SanyaKreks пишет:

Всем Добрый день. ТС огромное спасибо за проделанную работу.

Теперь вопросик на засыпку Такая железка подойдёт?

Подойдет, только АТ команды надо будет вправить, неуверен, что у них они совпадают с SİM800L

elik745i
Offline
Зарегистрирован: 08.04.2012

Послал плату на производство ))

emil55
Offline
Зарегистрирован: 13.11.2016

Удачи!

elik745i
Offline
Зарегистрирован: 08.04.2012

emil55 пишет:
Удачи!

благодарю

elik745i
Offline
Зарегистрирован: 08.04.2012

Добавил функцию звонилки с отправкой СМС, работаю над контактами...

phone.png

 

SportMaster
SportMaster аватар
Offline
Зарегистрирован: 02.03.2016

elik745i, Ваш сайт не работает - может выложите свои наработки на гугл или яндекс диск?

Спасибо!

emil55
Offline
Зарегистрирован: 13.11.2016

Можно там использовать 5В 8к реле-модул месте 12В?

elik745i
Offline
Зарегистрирован: 08.04.2012

Где там? )))

elik745i
Offline
Зарегистрирован: 08.04.2012

SportMaster пишет:

elik745i, Ваш сайт не работает - может выложите свои наработки на гугл или яндекс диск?

Спасибо!

Да, временно решил его прикрыть пока

Что вас интересует? Написал ведь, все есть в 3м посте...

elik745i
Offline
Зарегистрирован: 08.04.2012

Немного фоток обновлений интерфейса, добавил поставку системы умного дома на охрану:

1.png

2.png

3.png

4.png

5.png6.png

7.png

 

Далее буду работать над системой интеллектуальной экономии Электро Энергии в доме.

 

arDubino
Offline
Зарегистрирован: 12.01.2017

добавишь кнопку "Выключить все"?!! :)))

emil55
Offline
Зарегистрирован: 13.11.2016

Если можно добавьте hc12_comm.ino

elik745i
Offline
Зарегистрирован: 08.04.2012

elik745i
Offline
Зарегистрирован: 08.04.2012

emil55 пишет:
Если можно добавьте hc12_comm.ino

https://yadi.sk/d/9nxc3apl39QNgp

elik745i
Offline
Зарегистрирован: 08.04.2012
elik745i
Offline
Зарегистрирован: 08.04.2012

Видео демонстрации охранных функций:

https://youtu.be/JU4LYbrFWOo

Anton_Kos87
Offline
Зарегистрирован: 07.03.2014

когда выложите последний скетч с оханой?

elik745i
Offline
Зарегистрирован: 08.04.2012

Anton_Kos87 пишет:

когда выложите последний скетч с оханой?

 

Пока не планирую...работа  еще идет...

awladimer
Offline
Зарегистрирован: 13.02.2017

Добрый день! Хороший проэкт!!! тоже пытаюсь использовать ваш проэкт.

У меня почемуто вот такая ошибка неподскажите?

universalwebserver_v1.0_HC12_ENCnoSer.ino: In function 'void SetDevs()':
universalwebserver_v1.0_HC12_ENCnoSer:1153: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1154: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1237: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1238: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1257: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1258: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1279: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1280: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1300: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1301: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
in C++98 'swoff' must be initialized by constructor, not by '{...}'

elik745i
Offline
Зарегистрирован: 08.04.2012

awladimer пишет:

Добрый день! Хороший проэкт!!! тоже пытаюсь использовать ваш проэкт.

У меня почемуто вот такая ошибка неподскажите?

universalwebserver_v1.0_HC12_ENCnoSer.ino: In function 'void SetDevs()':
universalwebserver_v1.0_HC12_ENCnoSer:1153: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1154: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1237: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1238: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1257: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1258: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1279: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1280: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1300: error: in C++98 'swoff' must be initialized by constructor, not by '{...}'
universalwebserver_v1.0_HC12_ENCnoSer:1301: error: in C++98 'swon' must be initialized by constructor, not by '{...}'
in C++98 'swoff' must be initialized by constructor, not by '{...}'

 

Вы через что загружаете, где компиллируете?

awladimer
Offline
Зарегистрирован: 13.02.2017

elik745i пишет:

Вы через что загружаете, где компиллируете?

через Arduino IDE 1.6.5

elik745i
Offline
Зарегистрирован: 08.04.2012

awladimer пишет:

elik745i пишет:

Вы через что загружаете, где компиллируете?

через Arduino IDE 1.6.5

попробуйте скачать последнюю версию (1.8.1) ардуино  IDE, установить на ней требуемые библиотеки и откомпиллировать еще раз, у меня все типтом, да и не только у меня...

awladimer
Offline
Зарегистрирован: 13.02.2017

elik745i пишет:

awladimer пишет:

elik745i пишет:

Вы через что загружаете, где компиллируете?

через Arduino IDE 1.6.5

попробуйте скачать последнюю версию (1.8.1) ардуино  IDE, установить на ней требуемые библиотеки и откомпиллировать еще раз, у меня все типтом, да и не только у меня...

всё я разобрался скачал иде 1.6.12 файл скомпилировался и загрузился. Но страница неоткрывается использую мега2560+W5100 больше ничего неподключал. Да и компилятор выводит вот это

Используем библиотеку EasyTransfer в папке: C:\Sketches\iHouseArduinoIDE\libraries\EasyTransfer (legacy)
Используем библиотеку Adafruit-GFX-Library-master версии 1.1.5 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Adafruit-GFX-Library-master
Используем библиотеку Adafruit-ST7735-Library-master версии 1.0.0 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Adafruit-ST7735-Library-master
Используем библиотеку rc-switch-master в папке: C:\Sketches\iHouseArduinoIDE\libraries\rc-switch-master (legacy)
Используем библиотеку arduino_uip-master версии 1.04 из папки: C:\Sketches\iHouseArduinoIDE\libraries\arduino_uip-master
Используем библиотеку Time-master версии 1.5 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Time-master
Используем библиотеку EEPROM версии 2.0 из папки: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\EEPROM
Используем библиотеку SPI версии 1.0 из папки: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI
Используем библиотеку SD версии 1.0.8 из папки: C:\Sketches\iHouseArduinoIDE\libraries\SD

Скетч использует 59 300 байт (23%) памяти устройства. Всего доступно 253 952 байт.
Глобальные переменные используют 5 843 байт (71%) динамической памяти, оставляя 2 349 байт для локальных переменных. Максимум: 8 192 байт.
Invalid version found: 1.04
Invalid version found: 1.04
 

это критично или нет?

файлы на флеш закинул. Флеш fat32

щас еще попробую 1.8.1

elik745i
Offline
Зарегистрирован: 08.04.2012

awladimer пишет:

elik745i пишет:

awladimer пишет:

elik745i пишет:

Вы через что загружаете, где компиллируете?

через Arduino IDE 1.6.5

попробуйте скачать последнюю версию (1.8.1) ардуино  IDE, установить на ней требуемые библиотеки и откомпиллировать еще раз, у меня все типтом, да и не только у меня...

всё я разобрался скачал иде 1.6.12 файл скомпилировался и загрузился. Но страница неоткрывается использую мега2560+W5100 больше ничего неподключал. Да и компилятор выводит вот это

Используем библиотеку EasyTransfer в папке: C:\Sketches\iHouseArduinoIDE\libraries\EasyTransfer (legacy)
Используем библиотеку Adafruit-GFX-Library-master версии 1.1.5 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Adafruit-GFX-Library-master
Используем библиотеку Adafruit-ST7735-Library-master версии 1.0.0 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Adafruit-ST7735-Library-master
Используем библиотеку rc-switch-master в папке: C:\Sketches\iHouseArduinoIDE\libraries\rc-switch-master (legacy)
Используем библиотеку arduino_uip-master версии 1.04 из папки: C:\Sketches\iHouseArduinoIDE\libraries\arduino_uip-master
Используем библиотеку Time-master версии 1.5 из папки: C:\Sketches\iHouseArduinoIDE\libraries\Time-master
Используем библиотеку EEPROM версии 2.0 из папки: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\EEPROM
Используем библиотеку SPI версии 1.0 из папки: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI
Используем библиотеку SD версии 1.0.8 из папки: C:\Sketches\iHouseArduinoIDE\libraries\SD

Скетч использует 59 300 байт (23%) памяти устройства. Всего доступно 253 952 байт.
Глобальные переменные используют 5 843 байт (71%) динамической памяти, оставляя 2 349 байт для локальных переменных. Максимум: 8 192 байт.
Invalid version found: 1.04
Invalid version found: 1.04
 

это критично или нет?

файлы на флеш закинул. Флеш fat32

щас еще попробую 1.8.1

Проверьте правильность задания IP адреса в скетче, первые 3 блока должны совпадать с вашей домашней сеткой, подключите спикер, он должен пропищать в начале инициализации скетча после проверок наличия правильных файлов на флешке, также в скетче много вкладок для дебаггинга, они начинаются на Serial.println , раскомментируйте их и диагностируйте через сериал монитор что не так. 

Обычно либо IP задается не верно, либо проблемы с флешкой.

Еще посоветую проверить стандартный скетч для вебсервера, он должен быть включен в стандартную библиотеку езернет в ардуино ИДЕ

Минимально ардуины и езернетшилда достаточно для просто проверки...

удачи

awladimer
Offline
Зарегистрирован: 13.02.2017

[/quote]

Проверьте правильность задания IP адреса в скетче, первые 3 блока должны совпадать с вашей домашней сеткой, подключите спикер, он должен пропищать в начале инициализации скетча после проверок наличия правильных файлов на флешке, также в скетче много вкладок для дебаггинга, они начинаются на Serial.println , раскомментируйте их и диагностируйте через сериал монитор что не так. 

Обычно либо IP задается не верно, либо проблемы с флешкой.

Еще посоветую проверить стандартный скетч для вебсервера, он должен быть включен в стандартную библиотеку езернет в ардуино ИДЕ

Минимально ардуины и езернетшилда достаточно для просто проверки...

удачи

[/quote]

Спасибо установил 1.8.1 скомпилировалось всё отлично без ошибок но сайта нет, флеш нормальная FAT32 оборудование рабочее шил AMC работает отлично IP тоже правильный. даже незнаю уже где копать.

да кстати

Transmitting package: Device ID: 10001 Destination ID: 65535 Packet ID: 0 Command: 198 Data: 1
Request sent to device#-1
Transmitting package: Device ID: 10001 Destination ID: 65535 Packet ID: 0 Command: 198 Data: 1
Request sent to device#-1
 

щас попробую разкоментировать сериал

elik745i
Offline
Зарегистрирован: 08.04.2012

Если шилд работает, если кардридер работает (проверьте, чтобы файл index.htm был в корневом каталоге), то все должно работать...

awladimer
Offline
Зарегистрирован: 13.02.2017

elik745i пишет:

Если шилд работает, если кардридер работает (проверьте, чтобы файл index.htm был в корневом каталоге), то все должно работать...

Заработал оказывается нужно было разкоментировать W5100

//W5100
//#include <EthernetUdp.h>
//#include <Ethernet.h>

//ENC28J60 & SDCARD Reader
#include <UIPEthernet.h>

теперь открывается пишет

File Not Found!

файл index.htm в корневом каталоге мне кажется нужно гдето раскоментировать sd карту под шилд W5100

elik745i
Offline
Зарегистрирован: 08.04.2012
/*
    iHome MEGA SHIELD UWS_v1.8
    Installation:
   1) Connect all hardwire as per drawing and use pinmapping below as reference
   2) Clear EEPROM using Clear_EEPROM sketch in workfolder
   3) Config HC12 transceiver using HC12_COMM sketch in the
      workfolder: first set both serial communications to 9600bod speed,
      setup channel 1 and UART of the radio to 2400bot, then change sketch to
      2400bod UART speeds and test to confirm that module is setup properly.
      Use HC12 manual as reference.
   4) Configure SIM800L UART speed to 19200
   5) Make sure your MEGA supports watchdog feature, if not then comment all
      watchdog features in this sketch, otherwise read how to burn bootloader which supports it!
   6) Upload this sketch, connect LAN, makesure IP address of the server has the same mask as yours


//-----------------------------------------------------------  EEPROM MEMORY DISTRIBUTION: ARDUINO MEGA 4096 bytes ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   
   ADDRESS:           0,1                    2 - 40                  42 - 60             64,65                           66 - 98               99-102                  103-106                  110-310                      311                             312,313               314 - 454

   DATA TYPE:         Unsigned int           Unsigned int            Byte                unsigned int < 42000         Local Switch State    Total power meter          Stage power meter        Fixed Code Devices         Security Status [1 byte]          Security Code[int]    Security System 10 MobNumbers
   DATA STORED:       1x Unique Device ID    20x Remote Devices      iHouse ReqNumber    Keeloq Counter               32 Bytes              unsigned long(4bytes)      unsigned long(4bytes)    100EA int(2bytes)          1 - Disarmed;                     2 bytes               International! 10 x 14 bytes
                                                                                                                                                                                                                           2 - Armed;
                                                                                                                                                                                                                           3 - Alarm Activated
//------------------------------------------------------------EEPROM MEMORY DISTRIBUTION: ARDUINO MEGA 4096 bytes -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ADDRESS:           455 - 1169                                 2191 - 2392                     2393 - 2594                   2595 - 2796                        2797                2799                    2801                 2803                     2805
                   1170 - 2190  
           phone address book entry:                     Fixed code device zone         Fixed code device description       Fixed code device status     1byte delayed arm    1byte delayed siren    1byte siren on off     1byte Siren Level   1byte send SMS function
           50 numbers 50 x 14 = 700 bytes                100 devices 100bytes           1byte x 100 devices                 1byte x 100 devices          seconds max 200      seconds max 200
           50 names - 20characters x 50bytes
           1000 bytes


//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   Enjoy.
   Current version designed to work with iHome v1.5.6! For different setup some features needs to be reprogrammed, such as:
   1) Registration number of iHome remote devices (rgrd) setup:
                                                                Backup Power Generator control          - 7,
                                                                Gate Operation                          - 8,
                                                                Backup Power Generator gas valve       - 10,
                                                                Water Tank Level -
                                                                Sewage Level -
   Visit www.voltrans.az for support.
   created by Elik745i
   date last updated 19.01.2017
*/

//#include <SoftwareSerial.h>
#include <EasyTransfer.h>
////tft:
//#include <Adafruit_GFX.h>         // Core graphics library
//#include <Adafruit_ST7735.h>      // Hardware-specific library

#include <avr/wdt.h>              //watchdog
#include <RCSwitch.h>             // For remote control, security system sensors...
#include <Keeloq.h>               //Use Keeloq encryption for sensitive equipment control, gate, door e.t.c.

//W5100
#include <EthernetUdp.h>
#include <Ethernet.h>
#include <TimeLib.h>
#include <EEPROM.h>
#include <Vcc.h>
#include <SPI.h>
#include <SD.h>

//--------------------------------------PHONE FUNCTIONS VARIABLES------------------------------------------------------------
byte gsmCode = 0; //Reply from GSM


//---------------------------------------------------------------------------------------------------------------------------

//-------------------------------------Current measurement variables---------------------------------------------------------
const unsigned long sampleTime = 10000UL;                                       // sample over 100ms, it is an exact number of cycles for both 50Hz and 60Hz mains
const unsigned long numSamples = 25UL;                                          // choose the number of samples to divide sampleTime exactly, but low enough for the ADC to keep up
const unsigned long sampleInterval = sampleTime / numSamples;                   // the sampling interval, must be longer than then ADC conversion time
//const int adc_zero = 522;                                                     // relative digital zero of the arudino input from ACS712 (could make this a variable and auto-adjust it)
int adc_zero[16];                                                               //autoadjusted relative digital zero array

//------------------------------------Arduino voltage measurement variables---------------------------------------------------
const float VccCorrection = 5 / 5;                                              // Measured Vcc by multimeter divided by reported Vcc
float ardV;
Vcc vcc(VccCorrection);

//----------------------------------------------Keeloq Variables -------------------------------------------------------------
Keeloq k(0x01512345, 0x63612345);                                              //keeloq keys, change them for your iHouse!!!
unsigned int keeloqC = 34000;                                                  // unsigned long can't make more than that, sync this with receiver!


//-------------------------------------------------RCSWITCH-------------------------------------------------------------------
RCSwitch mySwitch = RCSwitch();

#define DevQ  10

int Dev[DevQ];
int Tup[DevQ];
int Volt[DevQ];
int gVolt[DevQ];
int grVolt[DevQ];
int Temp[DevQ];
int TempD[DevQ];
byte Lit[DevQ];
byte Gaslev[DevQ];
byte Curr[DevQ];
byte Vstat[DevQ];                                                              //valve, curtain, dc motor
byte Gstat[DevQ];
byte Sw1[DevQ];
byte Sw2[DevQ];
byte Sw3[DevQ];
byte Sw4[DevQ];
byte Sw5[DevQ];
byte Sw6[DevQ];
byte Sw7[DevQ];
byte Sw8[DevQ];
byte Hum[DevQ];
byte Press[DevQ];
byte Gyro[DevQ];
byte Alarm[DevQ];
byte rgrd[DevQ];
byte wLev[DevQ];

//---------------------------------------------------------------------------------------------Arduino MEGA Pin Mapping-------------------------------------------------------------------------------------------------------------------------------------------
//#define       //tft_RST         0    // you can also connect this to the Arduino reset
// in which case, set this #define pin to 0!
#define        dsTemp         2     //DS18B20 temperature sensor                             
//#define      fanDetec         3     //molex1
#define      SDenable         4     //W5100
#define      radio2Tx         5     //433.92 TX
#define         siren        12     //siren contact
#define      radio2Rx         3     //433.92 RX
#define          buzz         7     //D13 Buzzer PIN
#define       Eenable        10     //W5100 
#define         simRx        14     //TX3 SIM800L TX
#define         simTx        15     //RX3 SIM800L RX
#define       radioRx        18     //TX1   -> (HC12 RX)
#define       radioTx        19     //RX1   -> (HC12 TX)  
#define      radioSET        20     //HC12 SET 

#define          FAN1        34     //Fan ON/OFF                      
//#define       //tft_LED        45     //PWM

//#define        //tft_DC        48     ////tft A0
//#define        //tft_CS        49     //22
#define           SS         53     //MEGA SS pin

#define          Gpin        61     //A7 Grid Voltage detect
//#define          Vpin        56     //A2 Accum Voltage Detect
#define          Cpin        57     //A3 Grid Current detect
#define          Jpin        58     //A4 Generator Voltage detect
#define          Kpin        59     //A5 Generator Current detect
#define          Lpin        60     //A6 Analog Reseved 1
#define          Mpin        61     //A7 Analog Reseved 2
#define          keyb        67     //A13 keyboard

// Fixed code remote sensors:
// 4 button keyfob values:
#define kfb1   21808   //top left button
#define kfb2   21772   //top right button
#define kfb3   12345   //bottom left button
#define kfb4   12345   //bottom right button


// pins interfaced to switches
// const byte sw_arr[] = {6, 7, 8, 9, 11, 12, 13, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46};
//------------------------R1  R2  R3  R4  R5  R6  R7   R8   R9  R10   R11   R12   R13   R14   R15   R16  R17  R18  R19  R20  R21  R22  R23  R24  R25  R26  R27  R28  R29  R30  R31  R32
   const byte sw_arr[] = {26, 24, 22, 25, 27, 29, 33,  35,  37,  39,   41,   43,   32,   30,    28,  21,  42,  40,  38,  36,   8,   9,  11,  45,  16,  17,  44,  46,  31,  23,  13,  47};  //Relays,  Change 45 to 6 for propper shield!!!
//if for particular relay ON is logic signal 0, then put 1
const boolean invert_arr[] = { 0,  0,  0,  0,  0,  0,  0,   0,   0,    0,     0,   0,     0,     0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0};

const byte curr_arr[] = {54,    57,  58,  59,  60,  63,  64,  65,  66,  67,  68,  69,  62,  56,  55};                                                                     //Current sensors of first 15 relays.
//Currents A0,    A3,  A4,  A5,  A6,  A9, A10, A11, A12, A13, A14, A15,  A8,  A2,  A1
float curr_coef[] = {0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03};                                                           //Current sensor's res

float cSense[16];  

//---------------------------------------------------------Analog pins-------------------------------
const byte anal_arr[] = {61, 54, 58, 57};                                                                                                                                 //61(A7) - voltage detect, 54(A0) - current detect, 58(A4) - generator current, 57(A3) Solar Panels current

boolean LED_state[33];                                                                                                                                                    // stores the states of the LEDs

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


//-----------------------------------------------------------SIM800L--------------------------------------------------------------------------------------------

String currStr = "";                                                                                                                                                       // String to store receivedSMS
boolean isStringMessage = false;                                                                                                                                           // received is message indicator
boolean switchStateSms;                                                                                                                                                    // Switch state operated by SMS
byte sigqua;                                                                                                                                                               //calculated signal strength in % change to int if not working properly!

//------------------------------------------------------TFT SCREEN----------------------------------------------------------------------------------------------

//Adafruit_ST7735 //tft = Adafruit_ST7735(//tft_CS,  //tft_DC, //tft_RST);                           //uncomment if used

//---------------------------------------------------GRID PARAMETERS VARIABLES----------------------------------------------------------------------------------
float gridV;                  //grid Voltage
float tpm;                    //total power meter
float spm;                    //stage power meter
float Vcoef = 0.00482;        // Measure voltage by multimeter and divide to Read analog data (i.e. 4.14/835)
float Vgcoef  = 589;          // Grid  Voltage coefficient
//float Cgcoef  = 0;          // Grid  Current coefficient
float SLVcoef = 0;            // Solar Voltage coefficient
float SLCcoef = 0;            // Solar Current coefficient


/*-------------------------------------------INFO-------------------------------------------------------------
   Not all pins on the Mega and Mega 2560 support change interrupts, so only the following
   can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64),
   A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
-------------------------------------------------------------------------------------------------------------*/

const unsigned int deviceID = 10001;  //Unique Device ID
int destinationID; //Controling device.

//#define webfbuf      512                                                          //webfile read buffer from sdcard
//byte buf1[webfbuf];                                                               //webfile read buffer

//#define DEV_BUF_SZ   6
//char lcd_buf_1[DEV_BUF_SZ] = {0};                                                 // buffer to save Registered Device

//#define DEV_BUF_SZ2   9
//char lcd_buf_2[DEV_BUF_SZ2] = {0};                                                // buffer to save register remote device

//#define DEV_BUF_SZ3   6                                                           //refresh(askDevice) data from remote device up to 99999 devices
//char lcd_buf_5[DEV_BUF_SZ3] = {0};

//#define DEV_BUF_SZ4   7
//char lcd_buf_6[DEV_BUF_SZ4] = {0};                                                //Delete fixed remote device number


//#define DEV_BUF_SZ5   14
//char lcd_buf_7[DEV_BUF_SZ5] = {0};                                                //Phone Number for Voice Call
 
#define maxSeqPhone  3
char seqPhone[maxSeqPhone][14] ={0};                                              //Matrix to store Security Phone Numbers
       
//#define DEV_BUF_SZ6   136
//char lcd_buf_8[DEV_BUF_SZ6] = {0};                                                //14 characters Sms number + 120 character Text

//#define DEV_BUF_SZ8   14
//char lcd_buf_10[DEV_BUF_SZ8] = {0};                                               //Sequrity Phone Numbers pulled from AJAX

#define maxAddrPhone  50
//char addrPhone[maxAddrPhone][14] ={0};                                              //Matrix to store Addressbook Phone Numbers

char lcd_buf_3[6] = {0};                                                          //remote device id
char lcd_buf_4[4] = {0};                                                          //remote device iHome number up to 254 devices
char smsphnum[15] = {0};                                                          //sms phone number
 
 String alertStr = "1";                                                           //Alert message sent to web interface, "1" means show nothing

//-----------------------------------------------------------------

//OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

unsigned int unique_device_id = 0;    //create object
const float Vcrit = 3.5;              //critical battery voltage
const float Vmin = 3.7;               //critical battery voltage
const float Vfull = 4.9;              //critical battery voltage

String valveStat;
//float volt;
//float gvolt;
float temp;
float curr;
int gasLev;
byte wlev;
byte runStat;
int light;

byte vstat;
byte devm = 0;
byte clr = 20;   //Clear memory timer


//Ethernet----------------------------
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 200);

char rootFileName[] = "index.htm";

EthernetServer server(80);

File myFile;
//requests buufer, if less - might be delay problems processing xml requests!
#define BUFSIZ2 300
char clientline[BUFSIZ2];
char *filename;


boolean CLR_state[1] = {0}; // stores the states of the LEDs
boolean MET_state;          //stores meter state

unsigned long previousMillis = 0;
const int interval = 500;
int buz;
int z;
int s;

//SECURITY VARIABLES------------------------------------------------------
byte alarmK;          //Alarm sound
byte alarmSS = 1;     //Arm/Disarm Security System
String alarmString;   //Alarm Sensor Name String
String SeqSensor = "0";     //Activated sensor value
int alarmC = 0;       //Security code
byte sirenVol = 0;    //Siren Volume
byte sirenOn = 0;     //Siren On/Off
byte smsOn = 0;       //Send SMS Function
//------------------------------------------------------------------------

boolean fcr;
const byte frtr = 15;
byte frt = 15;

byte printK;
byte req = 0;
byte gsms = 0;         //send sms reply trigger
byte rgs;
byte ik;

boolean rdd;          //receive data soft interrupt
//Time----------------------------------------------------
unsigned long previousMillis2 = 0;
unsigned long previousMillis4 = 0;
unsigned long currentMillis;
const int t1 = 1000;
const int t4 = 500;    //reset receive softinterrupt
//Received Devices Running time:
byte secD;
byte minutesD;
byte hoursD;
byte daysD;
//System Running Time
byte secS;
byte minutesS;
byte hoursS;
byte daysS;
String uptime;
String timeString;

//EasyTransfer objects:
//SoftwareSerial radio(radioRx, radioTx);
EasyTransfer ET;
struct SEND_DATA_STRUCTURE {  //data structure, same for all iHome devices, shouldn't exceed 26 bite!
  unsigned int device_id;
  unsigned int destination_id;
  unsigned long packet_id;      //encrypted data
  byte command;
  int data;
};
SEND_DATA_STRUCTURE mydata;

//time servers--------------------------------
// NTP Servers:
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov
const int timeZone = +4;     // Central European Time
EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets


//--------------------------------------------------------------------------------------SETUP-----------------------------------------------------------------------------------------------
void setup() {
  Serial.begin(19200);                   // Debugging only
  Serial.println("iHome MEGA shield sv_1.7");
      
//---------------------------------------------------RECALL DATA FROM EEPROM------------------------------------------------------------------
//------------------------------SECURITY STATUS---------------------------------------------------
  //alarmSS = 1;                           //override security system   
  //EEPROM.put(311, alarmSS);
  
  alarmSS = EEPROM.get(311, alarmSS);
  if (alarmSS == 0) {
    alarmSS = 1;
  }
  if (alarmSS == 2) {
    Serial.println("Security is ARMED");
    SSArm(1);
  } else if (alarmSS == 1){
    Serial.println("Security is DISARMED");
    SSArm(0);
  }
  else if (alarmSS == 3){
    Serial.println("Security Siren Triggered!");
    Siren(1);
  }

//------------SECURITY CODE---------------------------------------------
    
    alarmC =  EEPROM.get(312, alarmC);
    Serial.println("Security Code is: " + String(alarmC));
    
//------------SECURITY PHONE NUMBERS------------------------------------

for( byte i=0; i < maxSeqPhone; i++){
  int p = i*14+314;  
  for( byte z = 0; z<=14; z++){ 
      int n = p+z;
      char k;
      seqPhone[i][z] = EEPROM.get(n, k);        
    } 
    Serial.println("Sequrity Phone Number#" + String(i+1) + ": " + seqPhone[i]); 
  }

//------------------Siren Vol----------------------------------------//
sirenOn  = EEPROM.get(2801,sirenOn);
//------------------Siren Vol----------------------------------------//
sirenVol = EEPROM.get(2803,sirenVol);
//------------------SMS function----------------------------------------//
smsOn    = EEPROM.get(2805,smsOn);
 //------------------------------------------------------------------------------------------------------------------------------------------------   

//Ethernet-------------------------------------------------------------------
  /*
      Serial.println("SD CS " + String(SD_CHIP_SELECT_PIN));
      Serial.println("MOSI " + String(SPI_MOSI_PIN) );
      Serial.println("MISO " + String(SPI_MISO_PIN) );
      Serial.println("SCK " + String(SPI_SCK_PIN) );
  */
  // disable Ethernet chip
  pinMode(Eenable, OUTPUT);
  digitalWrite(Eenable, HIGH);

  pinMode(SDenable, OUTPUT);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  byte sdd = 0;
  // initialize SD card----------------------
  //Serial.println("Initializing SD card...");
  if (!SD.begin(SDenable)) {
    tone(buzz, 1000, 200);
    //Serial.println("ERROR - SD card initialization failed!");
    sdd = 1;
    noTone(buzz);
    return;    // init failed

  }
  //Serial.println("SUCCESS - SD card initialized.");
  // check for index.htm file

  if (!SD.exists("index.htm")) {
    //Serial.println("ERROR - Can't find index.htm file!");
    sdd = 2;
    return;  // can't find index file
  }

//----------------------------------------------------------------------------------------------  

  //Serial.println("SUCCESS - Found index.htm file.");
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
  //Serial.print("server is at: ");
  //Serial.println(Ethernet.localIP());

  delay(500);

  //RC-Switch
  mySwitch.enableReceive(radio2Rx - 2);  // Receiver on interrupt 0 => that is pin #2

  //Recover Devices array stored in the memory (EEPROM starting from address 2)-----

  devDataRecover();

  // //tft
  //pinMode(//tft_LED, OUTPUT);
  //analogWrite(//tft_LED, 150);
  ////tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  // Use this initializer (uncomment) if you're using a 1.44" //tft
  ////tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

  //Serial.println("Initialized");
  ////tft, for //tft draw examples please check out graphicstest sketch in the Adafruit ST7735 library...
  ////tft.fillScreen(ST7735_BLACK);
  ////tft.setCursor(0, 0);
  ////tft.setTextColor(ST7735_GREEN);
  ////tft.setTextSize(1);
  ////tft.println("iHome Version 1.6beta");
  ////tft.setTextColor(ST7735_BLUE);
  ////tft.setCursor(0, 140);
  ////tft.println("for updates please   visit:www.voltrans.az");
  if (sdd == 1) {
    ////tft.setTextColor(ST7735_RED);
    ////tft.setCursor(0, 30);
    ////tft.print("ERROR - SD card initialization failed!");
    return;
  }
  if (sdd == 2) {
    ////tft.setTextColor(ST7735_RED);
    ////tft.setCursor(0, 30);
    ////tft.print("ERROR - Can't find index.htm file!");
    return;
  }
  //tft.setTextColor(ST7735_WHITE);
  //tft.setCursor(0, 20);
  //tft.print("SD card initialized!");
  //tft.setCursor(0, 30);
  //tft.print("Found index.htm file.");
  //tft.setCursor(0,40);
  //tft.println("server is at: ");
  //tft.setCursor(25,60);
  //tft.println(Ethernet.localIP());
  delay(300);

  //Time----------------------------------
  //Serial.println("TimeNTP");
  //Serial.print("IP number assigned by DHCP is ");
  //Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  //Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);

  //GSM--------------------------------
  Serial3.begin(19200);
  // Настраиваем приём сообщений с других устройств
  // Между командами даём время на их обработку
  gsmSignal();
  Serial3.print("AT+CMGDA=\"DEL ALL\"\n");  //Delete all SMSs from simcard memory
  delay(100);
  Serial3.print("AT+CMGF=1\r");            //SMS messages in text format
  delay(100);
  Serial3.print("AT+CLIP=1\r");           //Caller Identity 1-ON 0-OFF
  delay(100);
  Serial3.print("AT+CPBS=\"SM\"\r");      //Phonebook Memory Storage SM - SIM
  delay(100);
  digitalClockDisplay();
  //set time
  Serial3.print("AT+CCLK=" + timeString); //Set up time
  delay(300);

  //Radio module HC-12 begin
  Serial1.begin(2400);
  ET.begin(details(mydata), &Serial1);

  //Keeloq counter setup:
  unsigned int cr;
  if (EEPROM.get(64, cr) > keeloqC || EEPROM.get(64, cr) == 0) {

    EEPROM.put(64, keeloqC);
  }

  EEPROM.get(64, keeloqC);  //get counter from the memory
  //Serial.println("Counter: " + String(keeloqC));
  // Setting Up Device ID
  //Serial.print("Device ID... ");

  //unique_device_id=EEPROMReadInt(0);
  unique_device_id = EEPROM.get(0, unique_device_id);

  if (unique_device_id != deviceID) {
    //Serial.print("N/A, updating... ");

    //unique_device_id=random(10000, 60000);
    unique_device_id = deviceID;
    //EEPROMWriteInt(0, unique_device_id);
    EEPROM.put(0, unique_device_id);
  }

  //Serial.println(unique_device_id);

  deleteSMS();
  //tone(buzz,3400,200);
  //Current--------------------------------------------------
  for (byte cu = 0; cu <= 14; cu++) {
    adc_zero[cu] = determineVQ(curr_arr[cu]); //Quiscent output voltage - the average voltage ACS712 shows with no load (0 A)
    //Serial.println("Current Sensor's zero adc#" + String(cu+1) + ": "+ adc_zero[cu]);
  }

  //RECALL POWER METERS
  tpm = EEPROM.get(99, tpm);
  spm = EEPROM.get(103, spm);
  // RECALL LOCAL SWITCH STATES:
  for (byte kj = 0; kj <= 31; kj++) {
    pinMode( sw_arr[kj], OUTPUT);
    boolean switchSTATE = EEPROM.get(66 + kj, switchSTATE);
    LED_state[kj] = switchSTATE;
    if (invert_arr[kj]) {
      digitalWrite(sw_arr[kj], !switchSTATE);
    } else {
      digitalWrite(sw_arr[kj], switchSTATE);
    }
    delay(30);
  }
  
  wdt_enable(WDTO_8S);
    
  tone(buzz, 3400, 200);
  //Serial.println("Ready.");
}

void loop()
{
  currentMillis = millis();

  if (rdd == 0) {

    if (currentMillis - previousMillis2 >= t1) {
      previousMillis2 = currentMillis;
      upTime();
      //datalog();
      arduinoVolt();
      //Serial.println("Arduino Voltage: " + String(ardV,3) + "V");
      gridV = analogRead(anal_arr[0]) * ardV / 1023 * Vgcoef;       // Grid Voltage
      //Serial.println("Grid Voltage: " + String(gridV,1) + "V");
      currA();

      //Fix Code Registration counter:
      if (fcr) {
        //Serial.println("Register Fix Code Device within: " + String(frt) + "Sec.");
        frt--;
        if (frt == 0) {
          frt = frtr;
          alertStr = "Didn't detect any FixCode device signal!";
          fcr = false;
        }
      }
      //---------------
    }
    wdt_reset();
    etherNet();
    rcSwitch();
  }
  alarm();
  wdt_reset();
  receiveComd();
  receiveSMS();
  etherNet();

  if (currentMillis - previousMillis2 >= t4) {
    previousMillis4 = currentMillis;
    rdd = 0;
  }
  if (rgs >= 1) {
    RemGenStart();
  }

}

//Log the data:
void datalog() {
  String dstString = "";
  for (byte dst = 0; dst <= 14; dst++) {
    dstString += "," + String(cSense[dst]);
  }
  String dataString = uptime + "," + (gridV / 10) + "," + dstString;
  WriteToLog("datalog.txt", dataString);
}

//current measurements
void currA() {
  for (byte ca = 0; ca <= 14; ca++) {
    cSense[ca] = (readCurrent(curr_arr[ca], ca));
    //Serial.println("Current:" +String(cSense,3) + " Amps");
  }
}

int determineVQ(byte PIN) {
  //Serial.print("estimating avg. quiscent voltage:");
  long VQ = 0;
  //read 5000 samples to stabilise value
  for (int i = 0; i < 50; i++) {
    VQ += analogRead(PIN);
    delay(1);//depends on sampling (on filter capacitor), can be 1/80000 (80kHz) max.
  }
  VQ /= 50;
  //Serial.print(map(VQ, 0, 1023, 0, 5000));Serial.println(" mV");
  return int(VQ);
}

float readCurrent(byte PIN, byte arr)
{
  unsigned long currentAcc = 0;
  unsigned int count = 0;
  unsigned long prevMicros = micros() - sampleInterval ;
  while (count < numSamples)
  {
    if (micros() - prevMicros >= sampleInterval)
    {
      int adc_raw = analogRead(PIN) - adc_zero[arr];
      currentAcc += (unsigned long)(adc_raw * adc_raw);
      ++count;
      prevMicros += sampleInterval;
    }
  }
  //float rms = sqrt((float)currentAcc/(float)numSamples) * ((ardV/curr_coef[arr]) / 1024.0);    // 0.03V for 130A ACS755 sensor x=ardV/0.03
  float rms = sqrt((float)currentAcc / (float)numSamples) * ((5 / curr_coef[arr]) / 1024.0); // 0.03V for 130A ACS755 sensor x=ardV/0.03
  return rms;
  //Serial.println(rms);
}
//System voltage
void arduinoVolt() {
  ardV = vcc.Read_Volts();
  //float p = vcc.Read_Perc(VccMin, VccMax);
}
//Keeloq
void keeloqSecure() {
  keeloqC--;                                       // substract counter number
  //Serial.println("Count:" +String(keeloqC));
  //Serial.println("ID:" +String(deviceID));
  unsigned long rid = keeloqC * 100000 + deviceID;
  //Serial.println("Count + ID:" +String(rid));
  mydata.packet_id = k.encrypt(rid);
  EEPROM.put(64, keeloqC);                          // сохраняем int в EEPROM
}

void rcSwitch() {
  if (mySwitch.available()) {

    int      value = mySwitch.getReceivedValue();
    byte bitlength = mySwitch.getReceivedBitlength();
    byte  protocol = mySwitch.getReceivedProtocol();
    if (value == 0) {
      //Serial.print("Unknown encoding");
    }
    else {
      /*
        //Serial.print("Received ");
        //Serial.print( value );
        //Serial.print(" / ");
        //Serial.print( bitlength );
        //Serial.print("bit ");
        //Serial.print("Protocol: ");
        //Serial.println( protocol );
      */
      byte ik;
      byte vik;
      if (protocol == 1) {
        if (bitlength == 24) {
//Fix code registration------------------------------------------------------------------------------------------------------------------------------------------------------:
          if (fcr == true && frt > 0) {
            for (byte count = 0; count <= 100; count++) {
              int fixcodereg = EEPROM.get(count * 2 + 110, fixcodereg);
              if (fixcodereg == value) {
                //Serial.println("Device already registered at EEPROM address: " + String(count * 2 + 110) + ", value:" + fixcodereg + ", try different device!");
                String seqStr = "Device already registered at EEPROM address: " + String(count * 2 + 110) + ", value:" + fixcodereg + ", try different device!";
                WriteToLog("seqlog.txt", seqStr);
                alertStr = seqStr;
                fcr = false;
                frt = frtr;
                break;
              }
              if (fixcodereg == 0) {
                EEPROM.put(count * 2 + 110, value);
                //Serial.println("Fix Code Device: " + String(value) + " At EEPROM ADDRESS: " + (count * 2 + 110) + " Registered!");
                String seqStr = "Fix Code Device: " + String(value) + " At EEPROM ADDRESS: " + (count * 2 + 110) + " Registered!";
                WriteToLog("seqlog.txt", seqStr);
                alertStr = seqStr;
                fcr = false;
                frt = frtr;
                break;
              }
            }
          }
          //Start Generator: open valve RDRG 10, once it's open - go to start generator sequence
          if (value == kfb1) {
            RemGenStart();
          }

          else if (value == kfb2) {
            RemGenShut();
          }

          //Security System fixed code devices
          if (alarmSS == 2) {
            for (byte ifg = 0; ifg <= 100; ifg++) {
              int ifgp = EEPROM.get(ifg * 2 + 110, ifgp);
              if (value == ifgp) {
                //door sensor#1
                //tft.fillRect(0,90,128,40, ST7735_BLACK);
                //tft.setCursor(0, 90);
                //tft.setTextColor(ST7735_GREEN);
                //tft.println("Door Sensor#1");
                Siren(1);
                alarmString =  "Security Sensor: " + String(value) + "Activated!";
                WriteToLog("seqlog.txt", alarmString);
                //Serial.println(alarmString);
                SeqSensor = value;
                //alertStr = alarmString;
                if(smsOn == 1){
                sendSMS(alarmString);
                }
                break;
              }
            }
          }
        }
      }
    }
    mySwitch.resetAvailable();
  }

}

//Generator control--------------------------------------------------------------

void RemGenStart() {
  byte genid;
  if (rgs == 0) {
    //tft.fillRect(0,58,128,60, ST7735_BLACK);
    //tft.setCursor(0, 70);
    //tft.setTextColor(ST7735_GREEN);
    //tft.println("Starting Generator:");
    //tft.setCursor(0, 80);
    //tft.setTextColor(ST7735_GREEN);
    //tft.print("Gas Valve ");

    for (ik = 0; ik <= DevQ; ik++) {
      if (rgrd[ik] == 10) {
        destinationID = Dev[ik];
        //tft.print(destinationID);
        //tft.print(" :");
        break;
      }
    }
    openValve();
    rgs = 1;
  }
  if (Vstat[ik] == 1 && rgs == 1) {
    rgs = 2;
    ////tft.setCursor(100, 80);
    //tft.setTextColor(ST7735_GREEN);
    //tft.println("OPEN");
    //tft.print("Starting Generator ");
    for (ik = 0; ik <= DevQ; ik++) {
      if (rgrd[ik] == 7) {
        destinationID = Dev[ik];
        genid = ik;
        //tft.println(destinationID);
        break;
      }
    }
    startGen();
  }
  if (Gstat[genid] == 1 && rgs == 2) {
    rgs = 0;
    //tft.print("Generator is Running! ");
  }
  if (Gstat[genid] == 3 && rgs == 2) {
    rgs = 0;
    //tft.fillRect(0,58,128,50, ST7735_BLACK);
    //tft.setCursor(0, 70);
    //tft.setTextColor(ST7735_BLUE);
    //tft.print("Generator Failed to Start! ");
  }

}

void RemGenShut() {
  rgs = 0;
  //tft.fillRect(0,58,128,60, ST7735_BLACK);
  //tft.setCursor(0, 70);
  //tft.setTextColor(ST7735_RED);
  //tft.print("Stopping Generator ");
  for (ik = 0; ik <= DevQ; ik++) {
    if (rgrd[ik] == 7) {
      destinationID = Dev[ik];
      //tft.println(destinationID);
      break;
    }
  }
  shutGen();
  //tft.setCursor(0, 90);
  //tft.setTextColor(ST7735_RED);
  //tft.print("Closing Gas Valve ");
  for (ik = 0; ik <= DevQ; ik++) {
    if (rgrd[ik] == 10) {
      destinationID = Dev[ik];
      //tft.println(destinationID);
      break;
    }
  }
  closeValve();

}

void startGen() {

  mydata.command = 171;
  mydata.data = 1;
  transmitData();
  //Serial.println("Transmitting packet \"Generator ON\"");
  //Serial.println("DONE");
}

void shutGen() {

  mydata.command = 171;
  mydata.data = 2;
  transmitData();
  //Serial.println("Transmitting packet \"Generator OFF\"");
  //Serial.println("DONE");
}

//Operationg Gate
void gateOper(byte mzk) {

  for (byte ik = 0; ik <= DevQ; ik++) {
    if (rgrd[ik] == 8) {
      destinationID = Dev[ik];
    }
  }
  switch (mzk) {
    case 1:
      mydata.command = 1;
      mydata.data = 1;
      transmitData();
      break;
    case 2:
      mydata.command = 2;
      mydata.data = 1;
      transmitData();
      break;
case3:
      mydata.command = 3;
      mydata.data = 1;
      transmitData();
      break;
  }
}

void lightOper(byte mzs) {
  switchStateSms = LED_state[mzs - 1];
  digitalWrite(sw_arr[mzs - 1], !switchStateSms);
  LED_state[mzs - 1] = !switchStateSms;
  EEPROM.put(66 + (mzs - 1), !switchStateSms);
}

EthernetClient client;


void etherNet()
{

  int index = 0;

  client = server.available();

  if (client) {
    //detachInterrupt(0);
    // an http request ends with a blank line

    boolean current_line_is_blank = true;

    // reset the input buffer

    index = 0;

    while (client.connected()) {

      if (client.available()) {

        char c = client.read();
        /*readString.toCharArray(clientline,BUFSIZ);*/
        // Сбросить соединение, если пришел непонятный символ от клиента.

        //Например, наблюдались зависания от браузера

        // Safary (IPad 2), который посылал "непонятные" символы

        if ( c == 0x0A || c == 0x0D ) goto aa;

        if ( c < 0x20 || c > 0x7E ) break;

aa:

        // Если символ от клиента правильный, записываем его в буфер

        // Если идет чтение не новой строки, то продолжаем ее символы записывать в буфер.

        if (c != '\n' && c != '\r') {

          clientline[index] = c;

          index++;

          // �дем на продолжение считывать новый символ.

          continue;

        }

        // Заканчиваем строку символом 0, если следующая строка новая (получили  \n или \r )

        clientline[index] = 0;

        filename = 0;

        // Распечатываем прочитанную строку.--------------------------------

//Serial.println(clientline);

        // Look for substring such as a request to get the root file

        if (strstr(clientline, "GET / ") != 0) {

          filename = rootFileName;

        }

        if (strstr(clientline, "ajax_inputs") != 0 && rdd != 1) {
          // send rest of HTTP header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/xml");
          client.println("Connection: keep-alive");
          client.println();
          SetDevs();
          // send XML file containing input states
          XML_response(client);
          //Serial.println("AJAX Responce sent");
        }

        else if (strstr(clientline, "GET /") != 0) {

          // this time no space after the /, so a sub-file

          if (!filename) filename = clientline + 5; // look after the "GET /" (5 chars)

          // a little trick, look for the " HTTP/1.1" string and

          // turn the first character of the substring into a 0 to clear it out.

          (strstr(clientline, " HTTP"))[0] = 0;

          // print the file we want

          //Serial.println(filename);

          myFile = SD.open(filename);


          if (!myFile) {

            client.println("HTTP/1.1 404 Not Found");

            client.println("Content-Type: text/html");

            client.println();

            client.println("<h2>File Not Found!</h2>");

            break;

          }

          client.println("HTTP/1.1 200 OK");
          //Serial.println("Opened!");

          if (strstr(filename, ".htm") != 0)

            client.println("Content-Type: text/html");

          else if (strstr(filename, ".css") != 0)

            client.println("Content-Type: text/css");

          else if (strstr(filename, ".png") != 0)

            client.println("Content-Type: image/png");

          else if (strstr(filename, ".jpg") != 0)

            client.println("Content-Type: image/jpeg");

          else if (strstr(filename, ".gif") != 0)

            client.println("Content-Type: image/gif");

          else if (strstr(filename, ".svg") != 0)

            client.println("Content-Type: image/svg+xml");

          else if (strstr(filename, ".ttf") != 0)

            client.println("Content-Type: application/x-font-ttf");

          else if (strstr(filename, ".woff") != 0)

            client.println("Content-Type: application/x-font-woff");

          else if (strstr(filename, ".3gp") != 0)

            client.println("Content-Type: video/mpeg");

          else if (strstr(filename, ".pdf") != 0)

            client.println("Content-Type: application/pdf");

          else if (strstr(filename, ".js") != 0)

            client.println("Content-Type: application/x-javascript");

          else if (strstr(filename, ".xml") != 0)

            client.println("Content-Type: application/xml");

          else

            client.println("Content-Type: text");

          client.println();

          //----------------------------------------------
          if (myFile)
          {
            wdt_disable();
            
            byte buf1[512];                        //web buffer if working unstable reduce to 512!
            
            while (1) {
              int n = myFile.available();
              if (n == 0) break;
              //if (n > webfbuf) n = webfbuf;
              if (n > 512) n = 512;
              myFile.read(buf1, n);
              client.write(buf1, n);
            }
          }

          myFile.close();
          wdt_enable(WDTO_8S);
        }
        else {

          // everything else is a 404

          client.println("HTTP/1.1 404 Not Found");

          client.println("Content-Type: text/html");

          client.println();

          client.println("<h2>File Not Found!</h2>");

        }

        break;

      }

    }

    // give the web browser time to receive the data

    delay(1);

    client.stop();
    //attachInterrupt(0, receiveComd, CHANGE);
  }
}






//---------------------------------------Find String in the AJAX request----------------------------/
boolean FindStringInAJAX(char *line1, int len, char *req)
{
  boolean got_text = false;    // text received flag
  char *str_begin;             // pointer to start of text
  char *str_end;               // pointer to end of text
  int str_len = 0;
  int txt_index = 0;
  char *current_line;

  current_line = line1;
  


  
  // get pointer to the beginning of the text
  str_begin = strstr(clientline, req);

  for (int j = 0; j < 1; j++) { // do for 1 lines of text
    if (str_begin != NULL) {
      str_begin = strstr(str_begin, "=");  // skip to the =
      str_begin += 1;                      // skip over the =
      str_end = strstr(str_begin, "&");

      if (str_end != NULL) {
        str_end[0] = 0;  // terminate the string
        str_len = strlen(str_begin);

        // copy the string to the buffer and replace %20 with space ' '
        for (int i = 0; i < str_len; i++) {
          if (str_begin[i] != '%') {
            if (str_begin[i] == 0) {
              // end of string
              break;
            }
            else {
              current_line[txt_index++] = str_begin[i];
              if (txt_index >= (len - 1)) {
                // keep the output string within bounds
                break;
              }
            }
          }
          else {
            // replace %20 with a space
            if ((str_begin[i + 1] == '2') && (str_begin[i + 2] == '0')) {
              current_line[txt_index++] = ' ';
              i += 2;
              if (txt_index >= (len - 1)) {
                // keep the output string within bounds
                break;
              }
            }
          }
        } // end for i loop
        // terminate the string
        current_line[txt_index] = 0;
        got_text = true;
      }
    }
  } // end for j loop

  return got_text;
}


//-----------------------------------------------------------------


void SetDevs(void)
{
  
     //COMPARE SECURITY CODE:
    char lcd_buf_12[5] = {0}; 
    if ( FindStringInAJAX(lcd_buf_12, 5, "&ULKC=")) { 
     int unlockCode = atoi(lcd_buf_12);
     //Serial.println(unlockCode);
     alarmC =  EEPROM.get(312, alarmC);
     //Serial.println(alarmC);

     if(unlockCode == alarmC){
      SSArm(0);
     }
     else{
      alertStr = "Wrong Password!";
     }
    }
//Function if only system is not armed:
if(alarmSS == 1){
  // Local Switches LED1-LED32 ------------------------------------------

  for (byte dv = 1; dv <= 32; dv++) {
    String swoff = {"LED" + (String)dv + "=" + "0"};
    String swon = {"LED" + (String)dv + "=" + "1"};
    char soff[9];
    swoff.toCharArray(soff, 9);
    char* s1off = soff;
    char son[9];
    swon.toCharArray(son, 9);
    char* s1on = son;
    byte switchSTATE;
    if (invert_arr[dv - 1] == true) {
      if (strstr(clientline, s1off) != 0) {
        digitalWrite(sw_arr[dv - 1], HIGH);
        LED_state[dv - 1] = 0;
        switchSTATE = 0;
        EEPROM.put(66 + (dv - 1), switchSTATE);
      }
      if (strstr(clientline, s1on) != 0) {
        digitalWrite(sw_arr[dv - 1], LOW);
        LED_state[dv - 1] = 1;
        switchSTATE = 1;
        EEPROM.put(66 + (dv - 1), switchSTATE);
      }
    } else {
      if (strstr(clientline, s1off) != 0) {
        digitalWrite(sw_arr[dv - 1], LOW);
        LED_state[dv - 1] = 0;
        switchSTATE = 0;
        EEPROM.put(66 + (dv - 1), switchSTATE);
      }
      if (strstr(clientline, s1on) != 0) {
        digitalWrite(sw_arr[dv - 1], HIGH);
        LED_state[dv - 1] = 1;
        switchSTATE = 1;
        EEPROM.put(66 + (dv - 1), switchSTATE);
      }
    }
  } 

  //FailSafe Switch
  if (strstr(clientline, "&ALOF=1")) {
    //Serial.println("Switching all OFF");
    for(byte dv=1; dv<=32; dv++){
        digitalWrite(sw_arr[dv - 1], LOW);
        LED_state[dv - 1] = 0;
        byte switchSTATE = 0;
        EEPROM.put(66 + (dv - 1), switchSTATE);
        delay(200);
    }
  }
  
//Security--------------------------------------------------
  if (strstr(clientline, "&LOCK=1")) {
    Serial.println("SS Armed");
        SSArm(1);
  }
          
//----------------------------------------------------------
  //Register Fixed Code Remote
  if (strstr(clientline, "&FixReg=1")) {
    //Serial.println("Fixed Code Registration Active");
    //String logStr = "Fixed Code Registration Active!"; 
    //WriteToLog("seqlog.txt", logStr);
    fcr = true;
  }

  //Refresh Phone List
  if (strstr(clientline, "&PLRF=1")) {
    Serial.println("Refresh Phone List");
    //XML_response2(client);
    //Serial.println("XML file sent!");
  }

  //Receive GSM reply:
  if (strstr(clientline, "&GSMc=0")) {
    gsmCode = 0;
  }
  if (strstr(clientline, "&GSMc=4")) {
    gsmCode = 4;
  }

  // Clear Memory
  if (strstr(clientline, "CLR=1") != 0) {
    CLR_state[0] = 1;  // save LED state
    clearMem();
  }
  // Clear Meter
  if (strstr(clientline, "MET=1") != 0) {
    MET_state = 1;  // clear meter
    clearMet();
  }
  //------------------------------------------------
   
  //Ask Remote Device
  char lcd_buf_5[6] = {0};
  if (FindStringInAJAX(lcd_buf_5, 6, "&RFRD=")) {        // print the received Device ID for register
    int rfrdevid = atoi(lcd_buf_5);
    tone(buzz, 3500, 50);
    //Serial.print("Ask Remote Device ID: ");
    //Serial.println(rfrdevid);
    askDevice(rfrdevid);

  }

  //Delete fix remote device
  char lcd_buf_6[7] = {0};
  if (FindStringInAJAX(lcd_buf_6, 7, "&FDD=")) {        // print the received Device ID for register
    int delfixremdev = atoi(lcd_buf_6);
    tone(buzz, 3500, 50);
    //Serial.println("Delete Fix Device ID: " + String(delfixremdev));
    int found = 0;
    for (byte frt = 0; frt < 100; frt++) {
      int delfixdev = EEPROM.get(frt * 2 + 110, delfixdev);

      if (delfixdev == delfixremdev) {
        delfixdev = 0;
        byte delfixdesc = 0;
        EEPROM.put(frt * 2 + 110, delfixdev);
        //EEPROM address 2191---------------------------------------------
        EEPROM.put(frt * 2 + 2191, delfixdesc);    //delete zone info
        //EEPROM address 2393---------------------------------------------        
        EEPROM.put(frt * 2 + 2393, delfixdesc);    //delete desc info
        //Serial.println("DONE!");
        WriteToLog("seqlog.txt","Fix Device ID: " + String(delfixremdev) + " Deleted!");
        found = 1;
        break;
      }
    }
    if (found == 0) {
      //Serial.println("Couldn't find such fixcode device!");
    }
  }

  //Edit fix remote device
  char lcd_buf_19[7] = {0};
  if (FindStringInAJAX(lcd_buf_6, 7, "&FDE=")) {        // print the received Device ID for register
    int delfixremdev = atoi(lcd_buf_6);
    tone(buzz, 3500, 50);
    //Serial.println("Delete Fix Device ID: " + String(delfixremdev));
    for (byte frt = 0; frt < 100; frt++) {
      int delfixdev = EEPROM.get(frt * 2 + 110, delfixdev);

      if (delfixdev == delfixremdev) {
        byte delfixdesc = 255;
        //EEPROM address 2191---------------------------------------------
        EEPROM.put(frt * 2 + 2191, delfixdesc);    //delete zone info
        //EEPROM address 2393---------------------------------------------        
        EEPROM.put(frt * 2 + 2393, delfixdesc);    //delete desc info
        //Serial.println("DONE!");
        WriteToLog("seqlog.txt","Fix Device ID: " + String(delfixremdev) + " Editted!");
        break;
      }
    }
  }
  
  //Delete log file
  char lcd_buf_14[2] = {0};
  if (FindStringInAJAX(lcd_buf_14, 2, "&CLFL=")) {        
    byte clfl = atoi(lcd_buf_14);
    tone(buzz, 3500, 50);
    if(clfl == 1){
     Serial.println("Clearing datalog.txt");      
     SD.remove("datalog.txt");
     String logStr = "This is iHome datalog file";
     WriteToLog("datalog.txt", logStr);
    }
    else if(clfl == 5){
     Serial.println("Clearing seqlog.txt");
     SD.remove("seqlog.txt");
     String logStr = "This is iHome sequrity event log file";
     WriteToLog("seqlog.txt", logStr);        
    }
  }
  //Catch delayed Arm EEPROM 2797--------------------------------------------------
  char lcd_buf_15[4] = {0};
  if (FindStringInAJAX(lcd_buf_15, 4, "&ArmD=")) {        
    int clfl = atoi(lcd_buf_15);
    tone(buzz, 3500, 50);
     //Serial.println("Delayed Arm" + String(clfl));      
     EEPROM.put(2797,clfl);
     String logStr = "Set delayed Arm: " + String(clfl) + "sec";
     alertStr = logStr;
     WriteToLog("seqlog.txt", logStr);
  }
  //Catch delayed Disarm EEPROM 2799--------------------------------------------------
  char lcd_buf_16[4] = {0};
  if (FindStringInAJAX(lcd_buf_16, 4, "&DrmD=")) {        
    int clfl = atoi(lcd_buf_16);
    tone(buzz, 3500, 50);
     //Serial.println("Delayed Arm" + String(clfl));      
     EEPROM.put(2799,clfl);
     String logStr = "Set delayed Disarm: " + String(clfl) + "sec";
     alertStr = logStr;    
     WriteToLog("seqlog.txt", logStr);
  }
   
  //Catch Siren ON/OFF EEPROM 2801-----------------------------------------------------------------
  char lcd_buf_21[2] = {0};
  if (FindStringInAJAX(lcd_buf_21, 2, "&SON=")) {        
    byte clfl = atoi(lcd_buf_21);
    sirenOn = clfl;
    tone(buzz, 3500, 50);
     //Serial.println("Siren Volume" + String(clfl));      
     EEPROM.put(2801,clfl);
     String logStr = "Set siren on/off: " + String(clfl);
     //alertStr = logStr;
     WriteToLog("seqlog.txt", logStr);
  } 
  //Catch Siren Volume EEPROM 2803-----------------------------------------------------------------
   char lcd_buf_20[4] = {0};
  if (FindStringInAJAX(lcd_buf_20, 4, "&SVOL=")) {        
    byte clfl = atoi(lcd_buf_20);
    sirenVol = clfl;
    tone(buzz, 3500, 50);
     //Serial.println("Siren Volume" + String(clfl));      
     EEPROM.put(2803,clfl);
     String logStr = "Set siren volume: " + String(clfl) + "%";
     //alertStr = logStr;
     WriteToLog("seqlog.txt", logStr);
  }  
  //Catch SMS ON/OFF EEPROM 2805-----------------------------------------------------------------
  char lcd_buf_22[2] = {0};
  if (FindStringInAJAX(lcd_buf_22, 2, "&SMS=")) {        
    byte clfl = atoi(lcd_buf_22);
    smsOn = clfl;
    tone(buzz, 3500, 50);
     Serial.println("Send SMS function" + String(clfl));      
     EEPROM.put(2805,clfl);
     String logStr = "Set SMS function on/off: " + String(clfl);
     //alertStr = logStr;
     WriteToLog("seqlog.txt", logStr);
  }   
   //Catch register Fix remote code Device Zone------------------------------------------------
  char lcd_buf_17[14] = {0};
  if (FindStringInAJAX(lcd_buf_17, 14, "&FixRSZ=")) { 
    char deviceid[7] = {0};
    char devicezone[9] = {0};
    for(byte g = 0; g<=5;g++){
      deviceid[g] = lcd_buf_17[g];       
    }
    for(byte g = 0; g<=7;g++){
      devicezone[g] = lcd_buf_17[g+6];       
    }    
    int clfl = atoi(deviceid);
    byte clfj = atoi(devicezone);   
    tone(buzz, 3500, 50);
     //Serial.println("Fix Remote Device# " + String(clfl) + "  Zone: " + clfj);
    
     for(byte f = 0; f<=99; f++){
      int halo = EEPROM.get(f* 2 + 110, halo);
      if(halo == clfl){
        EEPROM.put(f* 2 + 2191,clfj);
         String logStr = "Fix Remote Device# " + String(clfl) + "  Zone: " + clfj + " Registered!";
         WriteToLog("seqlog.txt", logStr);
        break;     
      }
    }    
  }   
   //Catch register Fix remote code Device Description------------------------------------------------
  char lcd_buf_18[14] = {0};
  if (FindStringInAJAX(lcd_buf_18, 14, "&FixRSD=")) {        
    char deviceid[7]= {0};
    char devicedesc[9]= {0};
    for(byte g = 0; g<=5;g++){
      deviceid[g] = lcd_buf_18[g];       
    }
    for(byte g = 0; g<=7;g++){
      devicedesc[g] = lcd_buf_18[g+6];       
    }    
    int clfl = atoi(deviceid);
    byte clfj = atoi(devicedesc);
    tone(buzz, 3500, 50);
    //Serial.println("Fix Remote Device# " + String(clfl) + "  Description: " + clfj);      
     for(byte f = 0; f<=99; f++){
      int halo = EEPROM.get(f* 2 + 110, halo);
      if(halo == clfl){
        EEPROM.put(f* 2 + 2393,clfj);
         String logStr = "Fix Remote Device# " + String(clfl) + "  Description: " + clfj + " Registered!";
         WriteToLog("seqlog.txt", logStr);
        break;     
      }
    }
  }

        
   //ADD SECURITY CODE---------------------------------------------------------------------------------:
    char lcd_buf_11[5] = {0};
    if ( FindStringInAJAX(lcd_buf_11, 5, "&SECN=")) { 
     alarmC = atoi(lcd_buf_11);
     Serial.println(alarmC);
     String logStr = "Sequrity Code changed to: " + alarmC;
     WriteToLog("seqlog.txt", logStr);
     EEPROM.put(312, alarmC);
    }
    
  //Register New Remote Device iHouse 3dmap id
  char lcd_buf_2[9] = {0};
  if ( FindStringInAJAX(lcd_buf_2, 9, "&RGRD=")) {         // print the received Device ID for reister
    for (byte th = 0; th <= 4; th++) {
      lcd_buf_3[th] = lcd_buf_2[th];           //lcd_buf_3 = device ID
    }
    for (byte th = 5; th <= 7; th++) {
      lcd_buf_4[th - 5] = lcd_buf_2[th];       //lcd_buf_4 = Remote Device iHouse 3dmap id
    }
    int regdev = atoi(lcd_buf_3);
    byte regdevid = atoi(lcd_buf_4);
    //Serial.print("Register Remote Device ID: ");
    //Serial.print(regdev);
    //Serial.print(" -> iHome 3dmap number: ");
    //Serial.println(regdevid);
    for (byte dv = 0; dv <= DevQ; dv++) {
      if (rgrd[dv] == regdevid) {
        if (Dev[dv] != regdev ) {
          rgrd[dv] = 0;
          //EEPROMWriteInt(dv + 4 + DevQ*4, 0);   //EEPROM address 84, 85, 86 e.t.c.
          unsigned int ers = 0;
          EEPROM.put(DevQ * 2 + 2 + dv, ers);       //EEPROM address 42, 43, 44 e.t.c.
        }
      }
      if (Dev[dv] == regdev ) {
        rgrd[dv] = regdevid;
        //EEPROMWriteInt(dv + 4 + DevQ*4, regdevid); //EEPROM address 84, 85, 86 e.t.c
        EEPROM.put(DevQ * 2 + 2 + dv, regdevid);       //EEPROM address 42, 43, 44 e.t.c.
      }
    }
  }

  //Register New Phone Number in Security System
  char lcd_buf_10[14] = {0};
  if(FindStringInAJAX(lcd_buf_10, 14, "&SSN=")){
    for(byte spn=0; spn <= maxSeqPhone; spn++){
        int spnN = spn*14+314;
        char spnP[14];
        String Str = EEPROM.get(spnN, spnP);
        String Str10 = lcd_buf_10;       
        if(Str == Str10){
          alertStr =  "Number already exist!";
          break;
        }
        else if (Str == 0 && spn != maxSeqPhone){
                            //Serial.println("Writing: EEPROM Address#" + String(spnN) + "; Phone: " + Str10);          
                            EEPROM.put(spnN, lcd_buf_10);
                            break;
                          }
       if(spn == maxSeqPhone){
        alertStr =  "Memory is full!";
       }
        
    }    
  }

//------------------------------------------------------Register Phone Number in the EEPROM memory 455 - 1169 ------------------------------------------------
  char lcd_buf_13[14] = {0};
  if(FindStringInAJAX(lcd_buf_13, 14, "&RGNU=")){
    for(byte spn=0; spn <= maxAddrPhone; spn++){
        int spnN = spn*14+455;
        char spnP[14];
        String Str = EEPROM.get(spnN, spnP);
        String Str10 = lcd_buf_13;       
        if(Str == Str10){
          alertStr =  "Number already exist!";
          break;
        }
        else if (Str == 0 && spn != maxAddrPhone){
                            //Serial.println("Writing: EEPROM Address#" + String(spnN) + "; Phone: " + Str10);          
                            EEPROM.put(spnN, lcd_buf_13);
                            break;
                          }
       if(spn == maxAddrPhone){
        alertStr =  "Memory is full!";
       }
        
    }  
                  
  }
//------------------------------------------------------------------------------------------------------------------------------------------------
    
  //Send SMS text message
  char lcd_buf_8[136] = {0};
   if (FindStringInAJAX(lcd_buf_8, 136, "&SMS=")) {
    //find position of marker $   
    byte pos;
    for(byte z=0;z<=135;z++){
     if(lcd_buf_8[z] == '$'){
      pos = z;
      break;
     }
    }
    //figure out number:   
    for (byte kh = 0; kh <= (pos-1); kh++) {
      smsphnum[kh] = lcd_buf_8[kh];         
    }
    if(pos < 13){
     for(byte jk = (pos); jk<=15; jk++){
      smsphnum[jk] = 0;
     }
    }   
    //find sms text:
    char temes[120]={0};     
    for(byte px=(pos+1); px<=135; px++){
     temes[px-(pos+1)] = lcd_buf_8[px];
    }
    //Serial.println("SMS Num: " + String(smsphnum));
    //Serial.println("SMS Text: " + String(temes));
    //send sms:
    sendPhoneSMS(temes,  smsphnum); 
    delay(100); 
   }  
    
   //Make Voice Call
   char lcd_buf_7[14] = {0};
   if (FindStringInAJAX(lcd_buf_7, 14, "&PHO=")) {         // print the received Phone Number
    //int regdev = atoi(lcd_buf_3);
    //Serial.println("Voice Call: " + String(lcd_buf_7));
    Serial3.print("ATD" + String(lcd_buf_7) + ";\r");
    delay(100);
  }
  
  //Hang the Phone
  if (strstr(clientline, "&HGP=1")) {
    //Serial.println("Hanging the phone");
    Serial3.print("ATH\r");
    delay(100);
  }

  //Clear Security Phone list
  if (strstr(clientline, "&CLSPL=1")) {
       for(byte spn=0;spn<=maxSeqPhone;spn++){
        int spnN = spn*14+314;
        char spnP[14] = {0};
        char Str = EEPROM.put(spnN,spnP);
    } 
    alertStr = "Done!";
  }
    
  //Read SIM Phonebook

  //Register New Device
  char lcd_buf_1[6] = {0};
  if (FindStringInAJAX(lcd_buf_1, 6, "&RGR=")) {         // print the received Device ID for reister
    int devid2 = atoi(lcd_buf_1);
    //Serial.println(devid2);
    if (devid2 != deviceID && devid2 > 10000) {
      mydata.device_id = devid2;
      //Serial.println("New Device Registered: " + (String)mydata.device_id);
      RegDev();
    }
  }


  //valve ------------------------------------------------
  for (byte dv = 0; dv <= (DevQ - 1); dv++) {
    String swoff = {"Valve" + (String)dv + "=" + "0"};
    String swon = {"Valve" + (String)dv + "=" + "1"};
    char soff[9];
    swoff.toCharArray(soff, 9);
    char* s1off = soff;
    char son[9];
    swon.toCharArray(son, 9);
    char* s1on = son;
    if (strstr(clientline, s1off) != 0) {
      destinationID = Dev[dv];
      closeValve();
    }
    if (strstr(clientline, s1on) != 0) {
      destinationID = Dev[dv];
      openValve();
    }
  }

  //Generator ------------------------------------------------
  for (byte dv = 0; dv <= (DevQ - 1); dv++) {
    String swoff = {"Gen" + (String)dv + "=" + "0"};
    String swon = {"Gen" + (String)dv + "=" + "1"};
    char soff[9];
    swoff.toCharArray(soff, 9);
    char* s1off = soff;
    char son[9];
    swon.toCharArray(son, 9);
    char* s1on = son;
    if (strstr(clientline, s1off) != 0) {
      destinationID = Dev[dv];
      shutGen();
    }
    if (strstr(clientline, s1on) != 0) {
      destinationID = Dev[dv];
      startGen();
    }
  }

  //switch ------------------------------------------------

  //switch device 0:
  for (byte sw = 1; sw <= 8; sw++) {
    String swoff = {"Switch" + (String)sw + "=" + "0"};
    String swon = {"Switch" + (String)sw + "=" + "1"};
    char soff[10];
    swoff.toCharArray(soff, 10);
    char* s1off = soff;
    char son[10];
    swon.toCharArray(son, 10);
    char* s1on = son;
    if (strstr(clientline, s1off) != 0) {
      destinationID = Dev[0];
      switchOFF(sw);
    }
    if (strstr(clientline, s1on) != 0) {
      destinationID = Dev[0];
      switchON(sw);
    }
  }

  //switch the rest devices:
  for (byte dv = 0; dv <= (DevQ - 1); dv++) {
    for (byte sw = 1; sw <= 8; sw++) {
      String swoff = {"Switch" + (String)dv + sw + "=" + "0"};
      String swon = {"Switch" + (String)dv + sw + "=" + "1"};
      char soff[11];
      swoff.toCharArray(soff, 11);
      char* s1off = soff;
      char son[11];
      swon.toCharArray(son, 11);
      char* s1on = son;
      if (strstr(clientline, s1off) != 0) {
        destinationID = Dev[dv];
        switchOFF(sw);
      }
      if (strstr(clientline, s1on) != 0) {
        destinationID = Dev[dv];
        switchON(sw);
        }
      }
    }
  }
}

//Clear SD File
void  ClearSDFile(String filename){
   if(SD.exists(filename)){                   // если файл с именем filename существует, то ...
    Serial.println("Deleting " + filename);
    SD.remove(filename);
       File myFile;
       myFile = SD.open(filename, FILE_WRITE );
       myFile.close();
  }else{                                           // иначе ...
    Serial.println("file doesn't exist");
  } 
       
}
 
//Write to SD card
 void  WriteToLog(String filename, String text){
        myFile = SD.open(filename, FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        //Serial.print("Writing to " + filename + "...");
        myFile.println(timeString + " - " + text);
        // close the file:
        myFile.close();
        //Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening " + filename);
      }
 }
 
// send the XML file with analog values, switch status
//  and LED status

void XML_response(EthernetClient cl)
{
  int analog_val;            // stores value read from analog inputs
  int count;                 // used by 'for' loops
  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");
  //GSM Signal:
  cl.print("<gsm>");
  cl.print(sigqua);
  cl.println("</gsm>");
  //uptime:
  cl.print("<upt>");
  cl.print(uptime);
  cl.println("</upt>");
  //VCC:
  cl.print("<vcc>");
  cl.print(ardV);
  cl.println("</vcc>");
  cl.print("<time>");
  cl.print(timeString);
  cl.println("</time>");
  //GSM
  
  cl.print("<gsr>");
  cl.print(gsmCode);
  cl.println("</gsr>");
  
//Sequrity Phone Numbers---------------------------------------------------------
   for(byte spn=0;spn<=9;spn++){
        int spnN = spn*14+314;
        char spnP[14];
        String Str = EEPROM.get(spnN,spnP);
 if(Str != 0){       
    cl.print("<SSN>");
    cl.print(String(spn+1) + ": " + Str);
    cl.println("</SSN>");
 }        
    }
    
//Phone Book Numbers ------------------------------------------------------------    
   for(byte spn=0;spn<=9;spn++){
        int spnN = spn*14+455;
        char spnP[14];
        String Str = EEPROM.get(spnN,spnP);
 if(Str != 0){       
    cl.print("<PBN>");
    cl.print(String(spn+1) + ": " + Str);
    cl.println("</PBN>");
 }        
    }
//-------------------------------------------------------------------------------    
  
    
  // read device IDs
  for (count = 0; count <= (DevQ - 1); count++) { 
    
   if(Dev[count] != 0){
/*
    cl.print("<SSN>");
    cl.print(Dev[count]);
    cl.println("</SSN>");
*/    
    cl.print("<devID>");
    cl.print(Dev[count]);
    cl.println("</devID>");
    // read timeUp
    cl.print("<timeUP>");
    cl.print(Tup[count]);
    cl.println("</timeUP>");
    // read battery voltages
    cl.print("<batV>");
    cl.print(Volt[count]);
    cl.println("</batV>");
    // read generator voltages
    cl.print("<gVolt>");
    cl.print(gVolt[count]);
    cl.println("</gVolt>");
    // read Grid voltages
    cl.print("<grVolt>");
    cl.print(grVolt[count]);
    cl.println("</grVolt>");
    // read analog temperatures
    cl.print("<tempT>");
    cl.print(Temp[count]);
    cl.println("</tempT>");
    // read digital temperatures
    cl.print("<tempTD>");
    cl.print(TempD[count]);
    cl.println("</tempTD>");
    // read lits
    cl.print("<lit>");
    cl.print(Lit[count]);
    cl.println("</lit>");
    // read currents
    cl.print("<curr>");
    cl.print(Curr[count]);
    cl.println("</curr>");
    // read gas levels
    cl.print("<gasL>");
    cl.print(Gaslev[count]);
    cl.println("</gasL>");
    // read valve statuses
    cl.print("<valveS>");
    cl.print(Vstat[count]);
    cl.println("</valveS>");
    // read switch#1 status
    cl.print("<sw1>");
    cl.print(Sw1[count]);
    cl.println("</sw1>");
    // read switch#2 status
    cl.print("<sw2>");
    cl.print(Sw2[count]);
    cl.println("</sw2>");
    // read switch#3 status
    cl.print("<sw3>");
    cl.print(Sw3[count]);
    cl.println("</sw3>");
    // read switch#4 status
    cl.print("<sw4>");
    cl.print(Sw4[count]);
    cl.println("</sw4>");
    // read switch#5 status
    cl.print("<sw5>");
    cl.print(Sw5[count]);
    cl.println("</sw5>");
    // read switch#6 status
    cl.print("<sw6>");
    cl.print(Sw6[count]);
    cl.println("</sw6>");
    // read switch#7 status
    cl.print("<sw7>");
    cl.print(Sw7[count]);
    cl.println("</sw7>");
    // read switch#8 status
    cl.print("<sw8>");
    cl.print(Sw8[count]);
    cl.println("</sw8>");
    // read generator status
    cl.print("<genS>");
    cl.print(Gstat[count]);
    cl.println("</genS>");
    // read water level
    cl.print("<wLev>");
    cl.print(wLev[count]);
    cl.println("</wLev>");
    // read Registered Device ID:
    cl.print("<rgrd>");
    cl.print(rgrd[count]);
    cl.println("</rgrd>"); 
    }  
  }

  //Security:
  cl.print("<secl>");
  cl.print(alarmSS);
  cl.println("</secl>");
 
  cl.print("<senA>");
  cl.print(SeqSensor);
  cl.println("</senA>");

  cl.print("<darm>");
  byte darm;
  EEPROM.get(2797,darm);
  cl.print(darm);  
  cl.println("</darm>");
  
  cl.print("<ddrm>");
  byte ddrm;
  EEPROM.get(2799,ddrm);
  cl.print(ddrm);
  cl.println("</ddrm>");

  cl.print("<sVol>");
  cl.print(sirenVol);
  cl.println("</sVol>");

  cl.print("<sOn>");
  cl.print(sirenOn);
  cl.println("</sOn>");

  cl.print("<sms>");
  cl.print(smsOn);
  cl.println("</sms>");
  
  cl.print("<analog>");
  cl.print(gridV);
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(analogRead(anal_arr[2]) * SLVcoef);
  cl.println("</analog>");
  cl.print("<analog>");
  cl.print(analogRead(anal_arr[3]) * SLCcoef);
  cl.println("</analog>");

  for (count = 0; count <= 14; count++) { // analog arry
    //Serial.println("Analog Input: " +String(anal_arr[count]) + "Value - " + analog_val);
    cl.print("<current>");
    cl.print(cSense[count] * 1000);
    cl.println("</current>");
  }
  
  //alert
  cl.print("<alert>");
  cl.print(alertStr);
  cl.println("</alert>");
  alertStr = "1";
  
  //total power meter
  cl.print("<tmeter>");
  tpm += cSense[0] * gridV / 1200000;
  //Serial.print("Total Power Meter: ");
  //Serial.println(tpm,6);
  cl.print(tpm);
  cl.println("</tmeter>");

  //Stage Power Meter
  cl.print("<meter>");
  spm += cSense[0] * gridV / 1200000;
  //Serial.print("Stage Power Meter: ");
  //Serial.println(spm,6);
  cl.print(spm);
  cl.println("</meter>");

  //read fixed code devices ID from EEPROM
  for (byte counts = 0; counts <= 100; counts++) {
    int FixCodDev = EEPROM.get(counts * 2 + 110, FixCodDev);
    byte FixCodZone = EEPROM.get(counts * 2 + 2191, FixCodZone);                        //read fixed code devices Zone from EEPROM 2191
    byte FixCodDesc = EEPROM.get(counts * 2 + 2393, FixCodDesc);                        //read fixed code devices Description from EEPROM 2393
    byte FixCodStat = EEPROM.get(counts * 2 + 2595, FixCodStat);                        //read fixed code devices Status from EEPROM 2595    
    if (FixCodDev == 0 || FixCodDev == 255 || FixCodDev == 256){
      continue;
    }
      cl.print("<switch>");
      cl.print(FixCodDev);
      cl.println("</switch>");
      cl.print("<switchZ>");
      cl.print(FixCodZone);
      cl.println("</switchZ>"); 
      cl.print("<switchD>");
      cl.print(FixCodDesc);
      cl.println("</switchD>");    
      cl.print("<switchS>");
      cl.print(FixCodStat);
      cl.println("</switchS>");    
  }

  
  // checkbox LED states
  // LED1
  cl.print("<LED>");
  if (LED_state[0]) {
    cl.print("checked");
  }
  else {
    cl.print("unchecked");
  }
  cl.println("</LED>");
  // LED2
  cl.print("<LED>");
  if (LED_state[1]) {
    cl.print("checked");
  }
  else {
    cl.print("unchecked");
  }
  cl.println("</LED>");

  // button LED states

  // LED 1-33
  for (byte led = 2; led <= 31; led++) {
    cl.print("<LED>");
    if (LED_state[led]) {
      cl.print("on");
    }
    else {
      cl.print("off");
    }
    cl.println("</LED>");
  }


  // Clear Mem
  cl.print("<CLR>");
  if ( CLR_state[0] == 1) {
    cl.print(CLR_state[0]);
    clr--;
    //Serial.println("clr = " +(String)clr);
    if (clr <= 0) {
      CLR_state[0] = 0;
      clr = 20;
    }
  }
  else {
    cl.print(CLR_state[0]);
  }
  cl.println("</CLR>");

  //Register FixCode Device
  cl.print("<FCD>");
  cl.print(frt);
  cl.println("</FCD>");

  // Clear Power Meter
  cl.print("<MET>");
  if (MET_state) {
    cl.print(1);
    MET_state = 0;
  }
  else {
    cl.print(0);
  }
  cl.println("</MET>");

  cl.print("</inputs>");
}


void upTime() {
  if (secS < 59) {
    secS++;
    //sysVolt();
    digitalClockDisplay();
  }
  else
  {
    secS = 0;
    datalog();
    //Ask Devices 1ce in a minute:
    if (devm >= (DevQ - 1)) {
      devm = 0;
    }
    if (Dev[devm] != 0) {
      askDevice(Dev[devm]);
    }
    devm++;
    //-----------------------------
    gsmSignal();


    if (minutesS < 59) {
      minutesS++;
    }
    else
    {
      //record power usage once in an hour
      EEPROM.put(103, spm);
      EEPROM.put(99, tpm);

      if (hoursS < 23) {
        minutesS = 0;
        hoursS++;
      }
      else
      {
        minutesS = 0;
        hoursS = 0;
        daysS++;
      }
    }
  }

  uptime = (String)daysS + ":" + (String)hoursS + ":" + (String)minutesS + ":" + (String)secS;

  /*
         //Serial.print("uptime: ");
         //Serial.print(days);
         //Serial.print("days, ");
         //Serial.print(hours);
         //Serial.print("hrs, ");
         //Serial.print(minutes);
         //Serial.print("min, ");
         //Serial.print(sec);
         //Serial.println("sec. ");
  */

}

void askDevice(int k) {

  destinationID = k;
  mydata.command = 198;
  mydata.data = 1;
  transmitData();
  //Serial.println("Request sent to device# " +(String)k);

}

void receiveComd() {
  if (ET.receiveData()) // получили пакет данных, обрабатываем
  {
    rdd = 1;
    if (mydata.destination_id == deviceID)
    {

      RegDev();
      //1-11-----------------------------------------------------------------------
      if (mydata.command == 1) {

        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw1[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw1[m] = 2;
              break;
            }
          }
        }
        if (mydata.data == 5)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw1[m] = 3;
              break;
            }
          }
        }
      }

      if (mydata.command == 2) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw2[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw2[m] = 2;
              break;
            }
          }
        }
        if (mydata.data == 5)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw2[m] = 3;
              break;
            }
          }
        }
      }
      if (mydata.command == 3) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw3[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw3[m] = 2;
              break;
            }
          }
        }
        if (mydata.data == 5)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw3[m] = 3;
              break;
            }
          }
        }
      }
      if (mydata.command == 4) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw4[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw4[m] = 2;
              break;
            }
          }
        }
        if (mydata.data == 5)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw4[m] = 3;
              break;
            }
          }
        }
      }
      if (mydata.command == 5) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw5[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw5[m] = 2;
              break;
            }
          }
        }
      }
      if (mydata.command == 6) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw6[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw6[m] = 2;
              break;
            }
          }
        }
      }
      if (mydata.command == 7) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw7[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw7[m] = 2;
              break;
            }
          }
        }
      }
      if (mydata.command == 8) {
        if (mydata.data == 3)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw8[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 4)
        {
          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Sw8[m] = 2;
              break;
            }
          }
        }
      }



      //56 Valve Status------------------------------------------------------------------------------

      if (mydata.command == 56)
      {
        if (mydata.data == 3)
        {
          valveStat = " Valve Status: CLOSE ";
          if (gsms == 1) {
            sendSMS(valveStat);
            gsms = 0;
          }
          //Serial.println(valveStat);

          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {
              Vstat[m] = 2;
              break;
            }
          }
        }

        if (mydata.data == 4)
        {
          valveStat = " Valve Status: OPEN ";
          if (gsms == 1) {
            sendSMS(valveStat);
            gsms = 0;
          }
          //Serial.println(valveStat);

          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {
              Vstat[m] = 1;
              break;
            }
          }
        }

        if (mydata.data == 5)
        {
          valveStat = " Valve Status: HALF ";
          if (gsms == 1) {
            sendSMS(valveStat);
            gsms = 0;
          }
          //Serial.println(valveStat);

          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {
              Vstat[m] = 3;
              break;
            }
          }
        }

        if (mydata.data == 6)
        {
          valveStat = " Valve Status: NC ";
          if (gsms == 1) {
            sendSMS(valveStat);
            gsms = 0;
          }
          //Serial.println(valveStat);

          //enter data to Vstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {
              Vstat[m] = 4;
              break;
            }
          }
        }
      }
      //71 Temperature ----------------------------------------------------------------------------------------------------------------
      if (mydata.command == 71)
      {
        temp = (float)mydata.data / 100;
        //Serial.print("Temperature: ");
        //Serial.print(temp);
        //Serial.println("*C ");

        //enter data to Temp[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Temp[m] = temp * 100;
            break;
          }
        }
      }

      if (mydata.command == 72)
      {
        temp = (float)mydata.data / 100;
        //Serial.print("Temperature: ");
        //Serial.print(temp);
        //Serial.println("*C ");

        //enter data to Temp[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            TempD[m] = temp * 100;
            break;
          }
        }
      }
      //111 Light ----------------------------------------------------------------------------
      if (mydata.command == 111)
      {
        light = map(mydata.data, 0, 1023, 0, 100);

        //Serial.print("Lit: ");
        //Serial.print(light);
        //Serial.println("%");

        //enter data to Lit[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Lit[m] = light;
            break;
          }
        }
      }
      //141 Battery Voltage ----------------------------------------------------------------------------------------------------------------
      if (mydata.command == 141)
      {
        //Serial.print(" Battery Voltage: ");
        float volt = (float)mydata.data / 100;

        //Serial.print(volt);
        //Serial.println("V ");

        if (volt <= Vmin && volt > Vcrit) {
          //Serial.println("BATTERY VOLTAGE LOW! ");
        }
        if (volt <= Vcrit) {
          //Serial.println("BATTERY VOLTAGE CRITICAL! ");
        }
        if (volt >= Vfull)
        {
          //Serial.println("BATTERY IS FULL! ");
        }

        //enter data to Lit[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Volt[m] = volt * 100;
            break;
          }
        }
      }
      //142 Generator Voltage-------------
      if (mydata.command == 142)
      {
        //Serial.print(" Generator Voltage: ");
        float gvolt = (float)mydata.data * 16.2722 / 100;

        //Serial.print(Gvolt);
        //Serial.println("V ");

        //enter data to gVolt[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            gVolt[m] = gvolt * 100;
            break;
          }
        }
      }
      //142 Grid Voltage-------------
      if (mydata.command == 143)
      {
        //Serial.print(" Generator Voltage: ");
        float grvolt = (float)mydata.data / 100;

        //Serial.print(Gvolt);
        //Serial.println("V ");

        //enter data to gVolt[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            grVolt[m] = grvolt * 100;
            break;
          }
        }
      }
      //151 Current -------------------------------------------------------------------------------
      if (mydata.command == 151)
      {
        curr = (float)mydata.data / 1000;
        //Serial.print("Current: ");
        //Serial.print(curr);
        //Serial.println("Amper");

        //enter data to Lit[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Curr[m] = curr * 1000;
            break;
          }
        }
      }
      //161 Gas Level------------------------------------------------------------------------------
      if (mydata.command == 161)
      {
        gasLev = mydata.data;

        //Serial.print("Gas level: ");
        //Serial.print(gasLev);
        //Serial.println(" % ");

        //enter data to Gaslev[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Gaslev[m] = gasLev;
            break;
          }
        }
      }
      //162 -----------------------------------------------------------------------------
      if (mydata.command == 162 && mydata.data == 1)
      {
        //Serial.println("Battery is charging!");
      }
      //163 RunTime --------------------------------------------------------------------------------------------------------------
      if (mydata.command == 163)
      {
        //Serial.print("TimeUp: ");
        daysD = mydata.data / (24 * 60);
        //Serial.print(day);
        //Serial.print("days,");
        hoursD = (mydata.data - daysD * 24 * 60) / 60;
        //Serial.print(hour);
        //Serial.print("hours,");
        minutesD = mydata.data - (daysD * 24 * 60 + hoursD * 60);

        //Serial.print(minute);
        //Serial.println("min");

        //enter data to Tup[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            Tup[m] = mydata.data;
            break;
          }
        }

      }
      //171 Gen Status -----------------------------------------------------------------------------
      if (mydata.command == 171) {

        if (mydata.data == 4) {

          //send sms back if command came by sms-----------
          if (gsms == 1) {
            sendSMS("GENERATOR IS ON!");
            gsms = 0;
          }
          //enter data to Gstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Gstat[m] = 1;
              break;
            }
          }
        }
        if (mydata.data == 3) {

          //send sms back if command came by sms-----------
          if (gsms == 1) {
            sendSMS("GENERATOR IS OFF!");
            gsms = 0;
          }
          //enter data to Gstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Gstat[m] = 2;
              break;
            }
          }
        }
        if (mydata.data == 5) {

          //send sms back if command came by sms-----------
          if (gsms == 1) {
            sendSMS("GENERATOR Startup Failure!");
            gsms = 0;
            }
          
          //enter data to Gstat[m] array----------------------------
          for (byte m = 0; m <= (DevQ - 1); m++) {
            if ( Dev[m] == mydata.device_id ) {

              Gstat[m] = 3;
              break;
            }
          }
        }
      }
      //173 Water Level -----------------------------------------------------------------------------
      if (mydata.command == 173)
      {
        wlev = mydata.data;                       //wlev ultrasonic sensor data, cocnvert centimeters from top of the tank to percentage, estimate data as tankshape is not taken to account!
        wlev = map(wlev, 0, 150, 100, 0);         //change distance from top to percentage fill
        //Serial.print("Water level: ");
        //Serial.print(wLev);
        //Serial.println(" % ");

        //enter data to wLev[m] array----------------------------
        for (byte m = 0; m <= (DevQ - 1); m++) {
          if ( Dev[m] == mydata.device_id ) {

            wLev[m] = wlev;
            break;
          }
        }
      }
      //199 Alarm Codes---------------------------------------------------------------------------
      if (mydata.command == 199) {

        alarmK = 1;                            //trigger alarmsound

      }


      //Serial.print("Got: ");
      //Serial.print("Device ID: ");
      //Serial.print(mydata.device_id);
      //Serial.print(" Destination ID: ");
      //Serial.print(mydata.destination_id);
      //Serial.print(" Packet ID: ");
      //Serial.print(mydata.packet_id);
      //Serial.print(" Command: ");
      //Serial.print(mydata.command);
      //Serial.print(" Data: ");
      //Serial.print(mydata.data);
      //Serial.println();


    }
    else
    {
      /*
                  //Serial.print("Got Foreign package: ");
                  //Serial.print("Device ID: ");
                  //Serial.print(mydata.device_id);
                  //Serial.print(" Destination ID: ");
                  //Serial.print(mydata.destination_id);
                  //Serial.print(" Packet ID: ");
                  //Serial.print(mydata.packet_id);
                  //Serial.print(" Command: ");
                  //Serial.print(mydata.command);
                  //Serial.print(" Data: ");
                  //Serial.print(mydata.data);
                  //Serial.println();
      */

    }
  }

}

void reportDev() {
  mydata.command = 171;
  mydata.data = 3;
  transmitData();
  //Serial.println("Transmitting packet \"REPORT GEN\"");
  //Serial.println("DONE");
}
//Valve control--------------------------------------------------------------
void openValve() {

  mydata.command = 56;
  mydata.data = 1;
  transmitData();
  //Serial.println("Transmitting packet \"OPEN\"");
  //Serial.println("DONE");
}

void closeValve() {

  mydata.command = 56;
  mydata.data = 2;
  transmitData();
  //Serial.println("Transmitting packet \"CLOSE\"");
  //Serial.println("DONE");
}


//Switch controls------------------------------------------
void switchOFF(byte sd) {
  mydata.command = sd;
  mydata.data = 2;
  transmitData();
  // //Serial.println("Transmitting packet \"Switch LED OFF\" to device:" +(String)destinationID + "Switch#" + (String)sd);
}

void switchON(byte sd) {
  mydata.command = sd;
  mydata.data = 1;
  transmitData();
  //Serial.println("Transmitting packet \"Switch LED ON\" to device:" +(String)destinationID + "Switch#" + (String)sd);
}

void devDataRecover() {
  for (byte m = 1; m <= DevQ; m++) {
    //Dev[(m-1)] = EEPROMReadInt(m*4);
    EEPROM.get(m * 2, Dev[(m - 1)]);               //Get device ids unsigned int from 2,4,6,...40
    //rgrd[(m-1)] = EEPROMReadInt((m+DevQ)*4);
    EEPROM.get(DevQ * 2 + 1 + m, rgrd[(m - 1)]);   //Get their registers from 42,46,...60

    //Serial.print("Registered Devices:" + (String)(m) + " - ");
    //Serial.print(Dev[(m-1)]);
    //Serial.print(" - iHome ID: ");
    //Serial.println(rgrd[(m-1)]);

    delay(100);
  }
}

void transmitData() {
  keeloqSecure();
  mydata.device_id = unique_device_id;
  mydata.destination_id = destinationID;
  mydata.packet_id =  mydata.packet_id;
  mydata.command = mydata.command;
  mydata.data = mydata.data;
  //Serial.print("Transmitting package: ");
  //Serial.print("Device ID: ");
  //Serial.print(mydata.device_id);
  //Serial.print(" Destination ID: ");
  //Serial.print(mydata.destination_id);
  //Serial.print(" Packet ID: ");
  //Serial.print(mydata.packet_id);
  //Serial.print(" Command: ");
  //Serial.print(mydata.command);
  //Serial.print(" Data: ");
  //Serial.print(mydata.data);
  //Serial.println();
  ET.sendData(); 
  rdd = 1;
}


void sendSMS(String text) {
  
for(byte h = 0; h < maxSeqPhone; h++){
 
        if(seqPhone[h][0] == 0){
               continue;
             }
Serial.println("Sending SMS to: " + String(seqPhone[h]));                    
             sendPhoneSMS(text, String(seqPhone[h]));   
            }
}

void sendPhoneSMS(String text, String phone) {
  // //Serial.println("SMS send started");
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  Serial3.println("AT+CMGS=\"" + phone + "\"");
  delay(100);
  Serial3.println(text);
  delay(100);
  Serial3.println((char)26);
  //Serial.println("SMS send finish");
  delay(100);
  deleteSMS();
}

void deleteSMS() {
  //Serial.println("Delete All SMSs");
  Serial3.print("AT+CMGDA=\"DEL ALL\"\n");
  delay(100);
}

void receiveSMS() {
  if (!Serial3.available())
    return;
  char currSymb = Serial3.read();
  if ('\r' == currSymb) {
    if (isStringMessage) {

      tone(buzz, 3500, 200);
      
      for(byte sqp = 0; sqp < maxSeqPhone; sqp++){

        String phone1 = seqPhone[sqp];
        if (currStr.compareTo(phone1)) {
        //Serial.println("Phone number found!");
//---

      if (!currStr.compareTo("Start gen")) {
        //Serial.println("\"Generator ON\" command received over GSM, executing...");
        startGen();
        gsms = 1;

      }
      else if (!currStr.compareTo("Stop gen")) {
        //Serial.println("\"Generator OFF\" command received over GSM, executing...");
        shutGen();
        gsms = 1;
      }
      
      else if (!currStr.compareTo("Report")) {
        
        Serial.println("\"Report Sensors\" command received over GSM, executing...");
        String report;
        for (byte dev = 0; dev <= (DevQ - 1); dev++) {
          if (Dev[dev] != 0) {
            report += "DeviceID: " + (String)Dev[dev] + ",Time Up [mins]: " + (String)Tup[dev] +  ",Battery Voltage [V]: " +
                      (String)Volt[dev] + ",Lit [%]: " + (String)Lit[dev] + ",Current [Amps]: " +
                      (String)Curr[dev] + ",Gas Level [%]: " + (String)Gaslev[dev] + ",Valve Status: " +
                      (String)Vstat[dev] + ",Generator Status: " + (String)Gstat[dev];
          }
        }
        if (Dev[0] == 0) {
          report = "No registered devices yet! Try Later...";
        }
        //Serial.println("Report: " + report);
        sendSMS(report);
        
      }
      
      else if (!currStr.compareTo("Gate operate")) {
        //Serial.println("\"Gate Open/Close\" command received over GSM, executing...");
        gateOper(1);
        sendPhoneSMS("GATE IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Gate door")) {
        //Serial.println("\"Gate Door\" command received over GSM, executing...");
        gateOper(2);
        sendPhoneSMS("GATE DOOR IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Gate curtecy light")) {
        //Serial.println("\"Gate Curtecy Light\" command received over GSM, executing...");
        gateOper(3);
        sendPhoneSMS("GATE CURTECY LIGHT IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Gate light")) {
        //Serial.println("\"Gate Light\" command received over GSM, executing...");
        lightOper(1);
        sendPhoneSMS("GATE LIGHT IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Front light")) {
        //Serial.println("\"Front Light\" command received over GSM, executing...");
        lightOper(2);
        sendPhoneSMS("FRONT LIGHT IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Entry light")) {
        //Serial.println("\"Entry Light\" command received over GSM, executing...");
        lightOper(3);
        sendPhoneSMS("ENTRY LIGHT IS OPERATED!",phone1);
      }
      else if (!currStr.compareTo("Valve open")) {
        //Serial.println("\"Valve Open\" command received over GSM, executing...");
        destinationID = 10002;
        openValve();
        gsms = 1;
      }
      else if (!currStr.compareTo("Valve close")) {
        //Serial.println("\"Valve Close\" command received over GSM, executing...");
        destinationID = 10002;
        closeValve();
        gsms = 1;
      }
      else if (!currStr.compareTo("Alarm on")) {
        //Serial.println("\"Alarm\" command received over GSM, executing...");
        Siren(1);
        sendPhoneSMS("Alarm is ON!",phone1);
      }
      else if (!currStr.compareTo("Alarm off")) {
        //Serial.println("\"Alarm\" command received over GSM, executing...");
        noTone(buzz);
        alarmK = 0;
        Siren(0);
        SSArm(0);
        sendPhoneSMS("Alarm is OFF!",phone1);
      }
      else if (!currStr.compareTo("SS Arm")) {
        //Serial.println("\"SS Arm\" command received over GSM, executing...");
        SSArm(1);
        sendPhoneSMS("Security System Armed!",phone1);
      }
      else if (!currStr.compareTo("SS Disarm")) {
        //Serial.println("\"SS Disarm\" command received over GSM, executing...");
        noTone(buzz);
        SSArm(0);
        sendPhoneSMS("Security System Disarmed!",phone1);
      }
      else if (!currStr.compareTo("Ghost")) {
        //Serial.println("\"Ghost\" command received over GSM, executing...");
         sendPhoneSMS("GHOST MODE IS ON!",phone1);
      }
      else if (!currStr.compareTo("All off")) {
        //Serial.println("\"All off\" command received over GSM, executing...");
        //TBA

        sendPhoneSMS("ALL OFF!",phone1);
        }
//--
        break;
        }else{
            continue;      
             }
        Serial.println("Phone number unknown!");
      }

 //--     
    
      isStringMessage = false;
      //Delete SMS message
      Serial3.print("AT+CMGDA=\"DEL ALL\"\n");
      delay(100);
    } else {
      if (currStr.startsWith("+CMT")) {
        //если текущая строка начинается с "+CMT",
        //то следующая строка является сообщением
        isStringMessage = true;
      }
    if (currStr.startsWith("+CMGS")) {
      //Serial.println("SMS Delivered!");
      gsmCode = 1;  
    }
    if (currStr.startsWith("+CMS ERROR")) {
      //Serial.println("SMS Delivery ERROR!");
      gsmCode = 2;  
    }
    if (currStr.startsWith("NO CARRIER")) {
      //Serial.println("Hanged phone!");
      gsmCode = 3;  
    }    
    
    }
    Serial.println(currStr);
    
//Log in the txt file
WriteToLog("gsmlog.txt", currStr);


    currStr = "";
  } else if ('\n' != currSymb) {
    currStr += String(currSymb);
  }
}

void SSArm(byte armStatus){
  switch(armStatus){
    case 0:
            
            alarmSS = 1;
            //Serial.println("Security System DISARMED!");
            WriteToLog("seqlog.txt", "System Disarmed!");
            Siren(0);
            SeqSensor = "0";
            EEPROM.put(311, alarmSS);
            break;

    case 1:
            alarmSS = 2;
            //Serial.println("Security System ARMED!");
            WriteToLog("seqlog.txt", "System Armed!");
            EEPROM.put(311, alarmSS);
            break;
            
  }
}

void alarm() {
  if (alarmK == 1) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (z != 1) {
        buz = 3200;
        z = 1;
      } else {
        buz = 1000;
        z = 0;
      }
    }
    tone(buzz, buz);
  }

}

void Siren(byte shoot){
    if (shoot == 1) {
      alarmSS = 3;               //siren triggered!
     byte sirenV = map(sirenVol,0,100,0,255); 
    if(sirenOn == 1){
      pinMode(siren,OUTPUT);
      analogWrite(siren,sirenV);
      //Serial.println("Siren ACTIVE!");
    }else{
     pinMode(siren,OUTPUT);
     digitalWrite(siren,LOW);
     //Serial.println("Siren MUTED!"); 
    }
    
    }
    else{
    pinMode(siren,OUTPUT);
    digitalWrite(siren,LOW);
    //Serial.println("Siren OFF!");    
  }
}

void digitalClockDisplay() {
  //Set timeString in the following format: "00/01/01,04:21:27+00"
  timeString = "\"" + (String)day() + "/" + month() + "/" + year() + "," + hour() + ":" + minute() + ":" + second() + "+" + "0" + timeZone + "\"";
  //Serial.println(timeString);
}

void printDigits(int digits) {
  // utility for digital clock display: prints preceding colon and leading 0
  //Serial.print(":");
  //if(digits < 10)
  //Serial.print('0');
  // //Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  //Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      //Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  //Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &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();
}
/*
  void sysVolt(){
                   v = analogRead(Vpin);
                   v = v*Vcoef;              //747 - > 3.723V
              }
*/
void clearMem() {
  //Clear EEPROM Devices and arrays stored data
  for (byte r = 0; r <= DevQ; r++) {
    unsigned int ers = 0;
    EEPROM.put(r + 2, ers);
    byte erz = 0;
    EEPROM.put(DevQ * 2 + 2 + r, erz);
    Dev[r] = 0;
    Tup[r] = 0;
    Volt[r] = 0;
    gVolt[r] = 0;
    grVolt[r] = 0;
    Temp[r] = 0;
    TempD[r] = 0;
    Lit[r] = 0;
    Gaslev[r] = 0;
    Curr[r] = 0;
    Vstat[r] = 0;
    Gstat[r] = 0;
    Sw1[r] = 0;
    Sw2[r] = 0;
    Sw3[r] = 0;
    Sw4[r] = 0;
    Sw5[r] = 0;
    Sw6[r] = 0;
    Sw7[r] = 0;
    Sw8[r] = 0;
    Hum[r] = 0;
    Press[r] = 0;
    Gyro[r] = 0;
    Alarm[r] = 0;
    rgrd[r] = 0;
    wLev[r] = 0;
  }
  CLR_state[0] = 1;  // save LED state
  //Serial.println("Devices Stored in EEPROM Cleared!");
  devDataRecover();
}

//Clear power meter
void clearMet() {
  //Serial.println("Stage Meter reset!");
  spm = 0;
  EEPROM.put(103, spm);
  MET_state = 1;
}

void gsmSignal() {
  String simStr = "";  //simcard availability
  for (byte l = 0; l <= 1; l++) {
    Serial3.print("AT+CSMINS?\r");
    delay(1000);
  }
  do {
    char simSymb = Serial3.read();
    simStr += String(simSymb);
  } while (Serial3.available());
  String simAva = (String)simStr.charAt(24);
  byte gsmsim;  //signal strength from sim800l
  gsmsim = simAva.toInt();
  if (gsmsim == 1) {
    String csqStr = "";  //signal quality
    //Serial.println("Requesting GSM Signal Quality info");
    for (byte l = 0; l <= 1; l++) {
      Serial3.print("AT+CSQ\r");
      delay(1000);
    }
    do {
      char csqSymb = Serial3.read();
      csqStr += String(csqSymb);
    } while (Serial3.available());
    String sigStr = (String)csqStr.charAt(15) + csqStr.charAt(16);
    byte gsmsig;  //signal strength from sim800l
    gsmsig = sigStr.toInt();
    int sigstr;   //calculated signal strength in dBm
    if (gsmsig == 0) {
      sigstr = -115;
    }
    if (gsmsig == 1) {
      sigstr = -111;
    }
    if (gsmsig >= 2 && gsmsig <= 30) {
      sigstr = -110 + ((gsmsig - 2) * 2);
    }
    if (gsmsig > 30 && gsmsig < 99) {
      sigstr = -52 + (gsmsig - 31);
    }
    if (gsmsig == 99) {
      sigstr = 0;
    }
    sigqua = 2 * (sigstr + 100);
    if (sigqua > 0) {
      sigqua = sigqua;
    }
    else {
      sigqua = 0;
    }
    //Serial.println("Signal Strength: " + (String)gsmsig + " ; " + sigstr + "dBm" + " ; " + sigqua + "%");
  }
  else {
    //Serial.println("Simcard is not inserted!");
    sigqua = 200;    //simcard is not inserted properly
  }
}

void RegDev() {
  //Register devices in array Div[m]----------------------------
  for (byte m = 1; m <= DevQ; m++) {
    if ( Dev[m - 1] == 0 ) {

      Dev[m - 1] = mydata.device_id;
      //EEPROMWriteInt(m*4,mydata.device_id);
      EEPROM.put(m * 2, mydata.device_id);
      break;
    }
    if (Dev[m - 1] == mydata.device_id) {
      break;
    }
  }
  //Serial.print("Registered! ");
  //Serial.println(mydata.device_id);
}

Наслаждайтесь!

elik745i
Offline
Зарегистрирован: 08.04.2012

Последний интерфейс выложу попозже...

elik745i
Offline
Зарегистрирован: 08.04.2012

Он выглядит вот так:

awladimer
Offline
Зарегистрирован: 13.02.2017

ура спасибо!!! этот скетч открыл страницу а где можно схему посмотреть?

elik745i
Offline
Зарегистрирован: 08.04.2012

В моем блоге, скоро я выпущу универсальный шилд для умного дома, в котором будет воплощен весь потенциал данной прошивки. Заходите на voltrans.az

elik745i
Offline
Зарегистрирован: 08.04.2012

Работаю над новым интерфейсом:

2017-02-27_01-45-49.thumb.png.6a83be6440376e77b344a8a309df1e97.png

 

elik745i
Offline
Зарегистрирован: 08.04.2012

Теперь на отдельной страничке:

http://www.voltrans.az/?page_id=1969

elik745i
Offline
Зарегистрирован: 08.04.2012
elik745i
Offline
Зарегистрирован: 08.04.2012

Обновил до версии 0.0.2 Теперь работает стабильно и не вылетает, в добавок добавил возможность управлять беспроводными выключателями(пока что при помощи библиотеки RCSwitch, в дальнейшем выключателями LIVOLO) и многое другое!

http://www.voltrans.az/?page_id=1969

sshmel
Offline
Зарегистрирован: 08.02.2017

Далее соединяете все вот по этой схеме:

нет изображения