Arsip untuk Januari, 2018


Assalamu’alaikum Wr. Wb.

setup autostart

setup autostart

 

alamat server slave di ralat di http://appscenter.aio.co.id/weatherlogger/

alamat master logger di http://weatherlogger.ap.ngrok.io/

Oke saya lanjutkan. remind lagi ini adalah seri berantai dari posting berikut ya

  1. https://tarecha.wordpress.com/2015/10/26/project-raspberry-pi/
  2. https://tarecha.wordpress.com/2017/06/05/project-weather-logger-part-1/
  3. https://tarecha.wordpress.com/2017/06/26/project-weather-logger-part-2-tambahan-sensor-tekanan-udara/
  4. https://tarecha.wordpress.com/2017/07/01/project-weather-logger-part-3-komunikasi-udp/
  5. https://tarecha.wordpress.com/2017/07/15/project-weather-logger-part-4-simpan-di-server-mysql/
  6. https://tarecha.wordpress.com/2017/07/24/project-weather-logger-part-5-view-data-dan-export/
  7. https://tarecha.wordpress.com/2017/07/25/project-weather-logger-part-6-plot-graphic/
  8. https://tarecha.wordpress.com/2017/07/29/project-weather-logger-part-7-ngrok-http-tunneling/
  9. https://tarecha.wordpress.com/2017/08/27/project-weather-logger-part-8-ganti-sensor-bme280/
  10. https://tarecha.wordpress.com/2017/09/03/project-weather-logger-part-9-sync-data/

 

udah lama gk posting . langsung saja di rapel deh.

ada 3 bahasan yaitu gmn saat raspi start dia langsung run program nya karena kadang listrik rumah mati dan baru saya run lain setelah pulang, kalau sekarang sih sudah ada ups nya. tapi biar lebih otomatis saja. kedua notifikasi email bila sensor nya gk konek atau diluar threshold suhu yang kita tentukan. ini berguna untuk ruangan yang harus terkontrol suhu dan kelembapan atau tekanannya tapi disini saya pakai suhu saja. ketiga backup semua file nya dan menyimpan ke nas server milik saya. jadi di klik maka akan backup data.

untuk sync nya saya sudah buat sync 2 server. 1 server pabrik 1 server nas saya qnap ada webserver php nya. kebetulan kompatibel. tapi sama seperti dulu kok. tulisan ini akan membosankan buat pengguna awam programming. buat dokumentasi pribadi saja

1. autostart

caranya edit file autostart, ternyata tidak semua bisa di autostart. yang ngrokstart.sh gk berhasil. gtw kenapa. tapi yang penting ambil data dan sync nya jalan gk masalah. filenya ada di gambar dibawah

2.

setup autostart

setup autostart

2. notifikasi email

seperti disampaikan diawal ini untuk ngirim notif email. kode nya tidak serapi yang smart pdu sih karena ini pertama bikin. mau ganti males. yang penting udah jalan

berikut hasilnya

notif email

notif email

import socket
import sys
import datetime
import time
import urllib2
import urllib
import math
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "smartdo*******@gmail.com"
password = "**********"
port = 587
toaddr = ['mtarecha@aio.co.id','agung.tarecha@gmail.com']
mailserver ='smtp.gmail.com'


thresholdbawahsuhu = 25
thresholdatassuhu = 29
emailalertenable = 1
 
UDP_IP = "192.168.3.192"
UDP_PORT = 80
MESSAGE = "d"
urlserver = "http://192.168.3.199/insertdata.php"
key = "****sadasd888****"
namafilecsv = "rawdata6.csv"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
sock.settimeout(10) #dalam 10 detik setelah kirim tunggu data, kalau lewat bypass
data ={}
errordatasensor ='belum pernah NAN'
lasthum = -99999
lasttemp = -99999
lastpress = -99999
lastseennode = datetime.datetime.now()
idnode = 'N1'
i=1
while True:
         
        try :
                print '--------------------------------------------------------'
                print i
                i+=1
                #Set the whole string
                sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
                 
                # receive data from client (data, addr)
                d = sock.recvfrom(1024)
                #pemisahan data dengan karakter "," nanti buat save di mysql
                
                reply = d[0].split(",")
               
                
                curmin = datetime.datetime.now().time().minute
                cursec = datetime.datetime.now().time().second
                #curhour = datetime.datetime.now().time().hour
                curtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                lastseennode = datetime.datetime.now()
                print datetime.datetime.now()
                print 'Nodesensor reply : ' + str(reply) +' at '+curtime

                #kadang dht22 gagal baca dan menghasilkan nan (not a number)
                #jadi kalau gagal gunakan data dari pembacaan sebelumnya
                #untuk amannya kalau data bukan angka maka gunakan data sebelumnya
                #termasuk data dari sensor bmp280               
                if reply[1].replace('.','').isdigit():#dihilangkan koma dan titik lalu dicek apakah nomor saja
                        lasthum=reply[1]            
                        #ini adalah kondisi normal dimana data dibaca benar. 
                else:
                        errordatasensor = 'pernah NAN hum di waktu '+curtime+' '+reply[1]
                        reply[1]=lasthum
                        print 'Ada data NaN di dhthum gunakan last data '+str(lasthum)
                        
                        
                if reply[2].replace('.','').isdigit():
                        lasttemp=reply[2]
                        #ini adalah kondisi normal dimana data dibaca benar.
                        
                else:
                        errordatasensor = 'pernah NAN temp di waktu '+curtime+' '+reply[2]
                        reply[2]=lasttemp
                        print 'Ada data NaN di dhttemp gunakan last data '+str(lasttemp)
                         
                if reply[3].replace('.','').isdigit():
                        lastpress=reply[3]
                        #ini adalah kondisi normal dimana data dibaca benar.
                else:
                        errordatasensor = 'pernah NAN press di waktu '+curtime+' '+reply[3]
                        reply[3]=lastpress
                        print 'Ada data NaN di bmptemp gunakan last data '+str(lastpress)
                        
             

                        
                #cek isi apakah data terakhir benar
                #print 'lastdhthum '+lastdhthum
                #print 'lastdhttemp '+lastdhttemp
                #print 'lastbmptemp '+lastbmptemp
                #print 'lastbmppress '+lastbmppress
                print errordatasensor      
                  
                
                #tiap 10 menit simpan di file csv, karena dalam 10 menit lama
                #untuk mencegah save berulang di menit ke 10 dilihat detiknya
                #selama kurang dari 5 maka di save karena ada sleep 5 detiknya
                idnode = reply[0]
                if (curmin % 10 ==0)and (cursec < 5) : #if 1: #simpan menggunakan php data['k']= key data['iddata'] = 'auto' data['idnode'] = reply[0] data['hum'] = reply[1] data['temp'] = reply[2] data['press'] = reply[3] data['waktu'] = curtime data['sync1'] = 'false' data['sync2'] = 'false' dataformaturl = urllib.urlencode(data) #print dataformaturl requesttoserver = urllib2.urlopen(urlserver,dataformaturl,timeout=5) infosavephp = requesttoserver.read().split("#") #print infosavephp #print '==========================================================================' if(infosavephp[0]=='i')and(infosavephp[1]=='Berhasil Insert'): print 'Informasi Save ke Server : ID '+infosavephp[2]+' '+infosavephp[3] if(infosavephp[0]=='i')and(infosavephp[1]!='Berhasil Insert'):#selain berhasil print 'Gagal Insert Server : '+infosavephp[2] #karena gagal insert maka isi infosavephp[2] adalah sql nya untuk di cek #karena tetap pakai dimana infosavephp[2] harusnya berisi id auto increment maka diganti #untuk di save csv infosavephp[2] = 'No ID' with open(namafilecsv,'a') as file: file.writelines(infosavephp[2]+','+curtime+','+d[0]+'\n') #urutan csv nya iddataterakhir disave, waktu, data d (isi sensor) print 'data disimpan di csv ' +infosavephp[2]+' '+curtime+' '+str(reply) # print '==========================================================================' if emailalertenable : if (float(data['temp']) > thresholdatassuhu) or (float(data['temp']) < thresholdbawahsuhu):
                                        msg = MIMEMultipart()
                                        msg['From'] = fromaddr
                                        msg['To'] = ", ".join(toaddr)
                                        msg['Subject'] = "Weather Logger - Over Threshold Limit"
                                        server = smtplib.SMTP()
                                        server.connect(mailserver,port)                                       
                                        server.ehlo()
                                        server.starttls()                                        
                                        server.login(fromaddr,password)                              
                                        body = "Suhu ada di luar threshold "+ data['temp'] +" Celcius dengan threshold set " + str(thresholdbawahsuhu) +" Celcius hingga "+ str(thresholdatassuhu) +" Celcius pada "+str(curtime)
                                        body += " cek monitoring di http://appscenter.aio.co.id/weatherlogger/grafiklast24hour.php?node=N1"                                        
                                        msg.attach(MIMEText(body, 'plain'))
                                        text = msg.as_string()
                                        pesan = str(server.sendmail(fromaddr, toaddr, text))
                                        if pesan=='{}' :
                                                 print 'berhasil kirim email'
                                        else : 
                                                 print 'gagal kirim email'
                                        server.quit()       


                          
        except urllib2.HTTPError:
                print 'Tidak konek server'
        except urllib2.URLError:
                print 'URL Salah'
                
        except socket.error:
                print 'Tidak konek node'
                curmin = datetime.datetime.now().time().minute
                cursec = datetime.datetime.now().time().second
                #curhour = datetime.datetime.now().time().hour
                curtimelastseen = datetime.datetime.now()
                lastseensience = curtimelastseen - lastseennode                               
                print 'Lastseen Node '+str(lastseennode.strftime('%Y-%m-%d %H:%M:%S'))+ ' is '+str(lastseensience)[:-7]+' ago'
                if (curmin % 30 ==0)and (cursec <span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>< 15) :
                #if True:
                        try :
                                if emailalertenable :                                        
                                        msg = MIMEMultipart()
                                        msg['From'] = fromaddr
                                        msg['To'] = ", ".join(toaddr)
                                        msg['Subject'] = "Weather Logger - Disconnected Node"
                                        server = smtplib.SMTP()
                                        server.connect(mailserver,port)                                       
                                        server.ehlo()
                                        server.starttls()
                                        server.login(fromaddr,password)
                                        body = "Node "+idnode+" tidak konek, Lastseen "+str(lastseennode.strftime('%Y-%m-%d %H:%M:%S'))+ ' is '+str(lastseensience)[:-7]+' ago'
                                        body += " cek monitoring di http://appscenter.aio.co.id/weatherlogger/grafiklast24hour.php?node=N1"                                        
                                        msg.attach(MIMEText(body, 'plain'))
                                        text = msg.as_string()
                                        pesan = str(server.sendmail(fromaddr, toaddr, text))
                                        if pesan=='{}' :
                                                print 'berhasil kirim email'
                                        else : 
                                                print 'gagal kirim email'
                                        server.quit()
                        except Exception as e:
                                print 'Error Message '+ str(e)
                                print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
                                print "General Error Unexpected error:", sys.exc_info()[0]
                                #tidak pernah exit karena kalau tidak konek dilewati dan ngulang
                                #5 detik kemudian
                                #sys.exit()
        except Exception as e:
                print 'Error Message '+ str(e)
                print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
                print "General Error Unexpected error:", sys.exc_info()[0]
        time.sleep(5)

3. backup. backup ini penting.

bisa backup di raspi sendiri atau dibackup di nas. karena saya punya nas maka saya pilih nas saja biar kalau raspinya bermasalah masih punya backup kode
intinya backup mysql nya lalu data2 web dan file python kemudian di zip

script backup

script backup

 

hasilnya akan banyak backup dengan nama waktu backup

proses backup

proses backup

 

 

hasil backup

hasil backup

 

kira2 seperti itu.

terima kasih

wassalamu’alaikum wr. wb.


Assalamu’alaikum Wr. Wb.

mau nulis nih. project yang lama terbengkalai yaitu ketika server cctv saya di pabrik ngehang dan butuh restart power manual sehingga butuh waktu sampai senin datang ke pabrik buat restart. bayangkan berapa jam downtime nya kalau down sejak jum’at malam ? kadang2 downnya sabtu sih. dan memang server yang cctv kadang butuh restart manual power source nya. hal ini yang melatar belakangi saya bikin smart PDU / Power Distribution Unit. oke di pasaran sudah ada sih.. yap merk APC. bisa merestart dengan meremote IP APC tersebut.

fiture remote restart

fiture remote restart.

saya mau  bikin hal yang sama atau lebih baik sedikit dalam segi feature. kalau pdu ini harus di restart dengan mengaksesnya terlebih dahulu. saya mau biki smart PDU dengan fitur

1. autoreset power bila target IP tidak merespon

2. kirim email notifikasi bila target IP telah direset power relaynya

3. simpan log untuk mengentahui catatan PDU restart dan responnya untuk investigasi kemudian hari

 

detailnya sepertinya dalam skema dan code. mungkin kurang menarik ya. tapi buat dokumentasi.

 

notif email

notif email

 

coding arduino node mcu

untuk detail instalasi dll bisa merefer ke node mcu weather logger saya kemarin

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>


WiFiUDP Udp;
byte localUdpPort = 80;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char  replyPacket[255];



//untuk server
const char* ssid = "tarecha";
const char* ssid2 = "aiocyber";
const byte buzzerPin = D8;
const byte relayPin1 = D1;
const byte relayPin2 = D2;
const byte inputPin = D7;
const char* password = "12345678a";
const String aHostname = "N3";
boolean relayStatus1 = HIGH;
boolean relayStatus2 = HIGH;
String infoNode = "";

void setup()
{
  
  pinMode(LED_BUILTIN, OUTPUT);   
  pinMode(relayPin1, OUTPUT);   
  pinMode(relayPin2, OUTPUT); 
  pinMode(buzzerPin, OUTPUT); 
  pinMode(inputPin, INPUT);
  digitalWrite(relayPin1,HIGH);
  digitalWrite(relayPin2,HIGH);
  
  Serial.begin(9600);
  
  Serial.println("start");
  WiFi.begin(ssid, password);
  //WiFi.begin(ssid2);
  //bagian setup wifi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.mode(WIFI_STA);
  WiFi.hostname(aHostname);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");

  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
  infoNode = (String)"Restart reason : " + ESP.getResetReason().c_str() + "\n MAC : " + WiFi.macAddress().c_str() + "\n Hostname : " + WiFi.hostname().c_str() + "\n Signal Stringth : " + WiFi.RSSI() +
             "\n Local IP : " + WiFi.localIP().toString().c_str() + "\n Port : " + localUdpPort + "\n CPU Freq : " + String(ESP.getCpuFreqMHz()) + " MHz\n Sketch Size : " + ESP.getSketchSize()
             + "\n Free Space Sketch Size : " + ESP.getFreeSketchSpace();



  Serial.println(infoNode);


  buzzerlampu();
}
void lampu()
{
   digitalWrite(LED_BUILTIN, LOW); 
   delay(500);  
   digitalWrite(LED_BUILTIN, HIGH); 
   delay(5); 
}
void buzzerlampu()
{
  digitalWrite(LED_BUILTIN, LOW); 
  digitalWrite(buzzerPin, HIGH);   
  delay(500);                      
  digitalWrite(LED_BUILTIN, HIGH);  
  digitalWrite(buzzerPin, LOW); 
  delay(500);   
  digitalWrite(LED_BUILTIN, LOW);
  digitalWrite(buzzerPin, HIGH);
  delay(500);                   
  digitalWrite(LED_BUILTIN, HIGH);  
  digitalWrite(buzzerPin, LOW);
  delay(500);
                     
}




void loop()
{

  
 if (relayStatus1)
 {
   digitalWrite(relayPin1,HIGH);
 }
 else
 {
   digitalWrite(relayPin1,LOW);
 }
 if (relayStatus2)
 {
   digitalWrite(relayPin2,HIGH);
 }
 else
 {
   digitalWrite(relayPin2,LOW);
 }
 requestHandler();

}

void resetR1()
{
  digitalWrite(relayPin1,HIGH);
  delay(1000);
   digitalWrite(relayPin1,LOW);
  delay(10000);
  digitalWrite(relayPin1,HIGH);
  delay(1000);
  
}
void resetR2()
{
   digitalWrite(relayPin2,HIGH);
  delay(1000);
   digitalWrite(relayPin2,LOW);
  delay(10000);
  digitalWrite(relayPin2,HIGH);
  delay(1000);
}

void requestHandler()
{
  int packetSize = Udp.parsePacket();
  String perintah = "";
  if (packetSize)
  {
    // receive incoming UDP packets
    Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
       incomingPacket[len] = 0;
    }
    Serial.printf("UDP packet contents: %s\n", incomingPacket);
    if (incomingPacket[0] == 'a') //get data
    {
      relayStatus1 = LOW;
      perintah = "Matikan Relay 1";
        
    }
    else if (incomingPacket[0] == 'b') //get info sensor
    {
      relayStatus1 = HIGH;
      perintah = "Hidupkan Relay 1";
        
    }
     else if (incomingPacket[0] == 'd') //get info sensor
    {
      relayStatus2 = LOW;
      perintah = "Matikan Relay 2";
        
    }
     else if (incomingPacket[0] == 'e') //get info sensor
    {
      relayStatus2 = HIGH;
      perintah = "Hidupkan Relay 2";
        
    }
         else if (incomingPacket[0] == 'c') //get info sensor
    {
       resetR1();
       perintah = "Reset Relay 1";
        
    }
         else if (incomingPacket[0] == 'f') //get info sensor
    {
      resetR2();
       perintah = "Reset Relay 2";
        
    }
    else if (incomingPacket[0] == 'r') //perintah restart
    {
      perintah = (String)"Terima udp perintah restart dari "+ Udp.remoteIP().toString().c_str();
      perintah.toCharArray(replyPacket, 255);
      Serial.println(perintah);
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      Udp.write(replyPacket);
      Udp.endPacket();
      digitalWrite(buzzerPin, HIGH);    
      digitalWrite(LED_BUILTIN, LOW);    
      delay(10000); 
      ESP.restart();
    }
     else if (incomingPacket[0] == 'i') //get info sensor
    {
      perintah = infoNode;
    }
    else
    {
      perintah = "masuk else";
      
    }
    perintah.toCharArray(replyPacket, 255);
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(replyPacket);
    Udp.endPacket();
    Serial.printf("isi reply packet %s\n", replyPacket);
    buzzerlampu(); //nyalakan lampu biru setiap kirim data

  }


}
<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>

untuk pythonnya berikut. oh ya install dlu pyping ya. silahkan cari cara installnya. habis download packagenya. exstrak. masuk foldernya pakai cmd.
python setup.py install

import socket
import sys
import datetime
import time
import urllib2
import urllib
import math
import smtplib
import pyping
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "email@gmail.com"
password = "coba ya"
port = 587
#toaddr = ['mtarecha@aio.co.id','mwibowo@aio.co.id']
toaddr = ['mtarecha@aio.co.id']
mailserver ='smtp.gmail.com'

# a matikan relay 1
# b hidupkan relay 1
# c reset relay 1
# d matikan relay 2
# e hidupkan relay 2
# f reset relay 2
emailalertenable = True
batasPacketLost = 60 #batas berapa kali time out baru restart
timeoutset = 100 #1000 ms / 1 detik
pingCount = 100
targetIP1 = "192.168.3.199"
targetIP2 = "192.168.3.199"
UDP_IP = "192.168.3.180"
UDP_PORT = 80
pingeveryseconds = 600 #ping tiap 600 detik atau 5 menit memberi kesempatan server ready untuk
#ping lagi setelah 5 menit. kalau terlalu cepat nanti sebelum siap restart terus



print "Power Relay IP :"+ UDP_IP
print "Power Relay Port :", UDP_PORT
print "Target IP 1 : "+ targetIP1
print "Target IP 2 : "+ targetIP2
statusResetPower1 = False
statusResetPower2 = False
statusNodeNotConnected = False
lastseennode = datetime.datetime.now()   

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
sock.settimeout(20) #dalam 10 detik setelah kirim tunggu data, kalau lewat bypass

def kirimPerintah(pesan):     
        sock.sendto(pesan, (UDP_IP, UDP_PORT))
        reply = sock.recvfrom(1024)[0]
        lastseennode = datetime.datetime.now()            
        return 'Nodesensor reply : ' + str(reply) +' at '+curtime

def kirimEmail(isiemail,subject):
        if emailalertenable :
                try :
                        msg = MIMEMultipart()
                        msg['From'] = fromaddr
                        msg['To'] = ", ".join(toaddr)
                        msg['Subject'] = subject
                        server = smtplib.SMTP(mailserver,port)                                        
                        server.login(fromaddr,password)
                        body = isiemail
                        msg.attach(MIMEText(body, 'plain'))
                        text = msg.as_string()
                        pesan = str(server.sendmail(fromaddr, toaddr, text))
                        if pesan=='{}' :
                                 print 'berhasil kirim email : '+isiemail
                        else : 
                                 print 'gagal kirim email'
                        server.quit()
                except Exception as e:
                        print 'Error Message '+ str(e)
                        print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
                        print "General Error Unexpected error:", sys.exc_info()[0]

def saveLog(data):
        with open('logsmartpdu.txt','a') as file:
                file.writelines(data+'\n')
        print 'Berhasil save log : '+data
                               

while True:
         
        try :
                curmin = datetime.datetime.now().time().minute
                cursec = datetime.datetime.now().time().second
                curtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    
                print '--------------------------------------------------------'
                print curtime
                print 'Mulai ping Relay 1 dengan IP : '+targetIP1
                lostIP1 = pyping.ping(targetIP1, timeout=timeoutset, count=pingCount).packet_lost        
                if lostIP1 > batasPacketLost:
                        print kirimPerintah('c')
                        #reset
                        #sleep 300 detik / menit untuk ulang ping lagi dan nunggu waktu server cctv ready                        
                        statusResetPower1 = True
                        emailtext = 'Relay 1 dengan IP '+str(targetIP1)+' ping timeout sebanyak '+str(lostIP1)+' dari '+str(pingCount)+ ' pada '+ curtime +' telah di reset'
                        kirimEmail(emailtext,'Smart PDU - Reset Relay 1')
                        print 'Reset Relay 1'
                        saveLog(emailtext)
                        #time.sleep(300)
                        
                else:
                        #print kirimPerintah('b')
                        print 'Ping IP 1 : '+targetIP1+' OK'
                        #hidupkan
                        if statusResetPower1:
                                emailtext = 'Relay 1 dengan IP '+str(targetIP1)+' sudah aktif normal pada '+curtime
                                kirimEmail(emailtext,'Smart PDU - Relay 1 back to normal')
                                statusResetPower1 = False
                                saveLog(emailtext)
                print 'Mulai ping Relay 2 dengan IP : '+targetIP2
                lostIP2 = pyping.ping(targetIP1, timeout=timeoutset, count=pingCount).packet_lost               
                if lostIP2 > batasPacketLost:
                        print kirimPerintah('f')
                        #reset
                        #sleep 300 detik / menit untuk ulang ping lagi dan nunggu waktu server cctv ready                        
                        statusResetPower2 = True
                        emailtext = 'Relay 2 dengan IP '+str(targetIP2)+' ping timeout sebanyak '+str(lostIP2)+' dari '+str(pingCount)+ ' pada '+ curtime +' telah di reset'
                        kirimEmail(emailtext,'Smart PDU - Reset Relay 2')
                        print 'Reset Relay 2'
                        saveLog(emailtext)
                        #time.sleep(300)
                else:
                        #print kirimPerintah('e')
                        print 'Ping IP 2 : '+targetIP2+' OK'
                        #hidupkan
                        if statusResetPower2:
                                emailtext = 'Relay 2 dengan IP '+str(targetIP2)+' sudah aktif normal pada '+curtime
                                kirimEmail(emailtext,'Smart PDU - Relay 2 back to normal')
                                statusResetPower2 = False
                                saveLog(emailtext)
                                
                if statusNodeNotConnected :
                        emailtext = 'Node Konek Pada '+curtime
                        kirimEmail(emailtext,'Smart PDU - Node back to normal connected')
                        statusNodeNotConnected = False
                        saveLog(emailtext)
                        print emailtext
          
        except urllib2.HTTPError:
                print 'Tidak konek server'
        except urllib2.URLError:
                print 'URL Salah'
                
        except socket.error as a:
                print 'Tidak konek node '+str(a)
                statusNodeNotConnected = True 
                curmin = datetime.datetime.now().time().minute
                cursec = datetime.datetime.now().time().second
                #curhour = datetime.datetime.now().time().hour
                curtimelastseen = datetime.datetime.now()
                lastseensience = curtimelastseen - lastseennode                               
                print 'Lastseen Node '+str(lastseennode.strftime('%Y-%m-%d %H:%M:%S'))+ ' is '+str(lastseensience)[:-7]+' ago'
                if (curmin < 10) :
                
                        try :
                                if emailalertenable :                                        
                                        msg = MIMEMultipart()
                                        msg['From'] = fromaddr
                                        msg['To'] = ", ".join(toaddr)
                                        msg['Subject'] = "Smart Reset PDU - Disconnected Node"
                                        server = smtplib.SMTP(mailserver,port)                                        
                                        server.login(fromaddr,password)
                                        body = "Node "+UDP_IP+" tidak konek, Lastseen "+str(lastseennode.strftime('%Y-%m-%d %H:%M:%S'))+ ' is '+str(lastseensience)[:-7]+' ago'
                                                           
                                        msg.attach(MIMEText(body, 'plain'))
                                        text = msg.as_string()
                                        pesan = str(server.sendmail(fromaddr, toaddr, text))
                                        if pesan=='{}' :
                                                print 'berhasil kirim email : '+body
                                        else : 
                                                print 'gagal kirim email'
                                        server.quit()
                                        saveLog(body)
                        except Exception as e:
                                print 'Error Message '+ str(e)
                                print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
                                print "General Error Unexpected error:", sys.exc_info()[0]
                                #tidak pernah exit karena kalau tidak konek dilewati dan ngulang
                                #5 detik kemudian
                                #sys.exit()
        except Exception as e:
                print 'Error Message '+ str(e)
                print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
                print "General Error Unexpected error:", sys.exc_info()[0]
        time.sleep(pingeveryseconds)