Upload
trinhnguyet
View
217
Download
0
Embed Size (px)
Citation preview
113
LAMPIRAN A
Pada lampiran A, terdapat source code dari program-program yang telah dibuat
oleh penulis, dengan lampiran sebagai berikut:
Source Code Program Berada Pada Raspberry Pi
i. Source Code “databases.py”
#!/usr/bin/python """ membuat koneksi mysql """ import MySQLdb def db_conn() : database = "skripsihanang" host = "192.168.1.109" username = "hanang" password = "1234567" db = MySQLdb.connect(host,username,password,database) return db db_conn = db_conn()
ii. Source Code “pingscript.py”
#!/usr/bin/python import subprocess import os import re import time from database import db_conn match = [] def pingcode(ip) : result = [] ping = subprocess.Popen(["ping","-c","1","-i","1"," W","1",ip],stdout=subprocess.PIPE).stdout.read() result.append(ping) data = result[0] regex = re.findall(r'time=(.*)ms',data) if regex == match : regex = 0 else : regex = float(regex[0]) data = regex if data != 0 : status = 1
114
else : status = 0 return status,data def datasql(ip, tabel, tabel30): db = db_conn cursor = db.cursor() result = pingcode(ip) status = result[0] data = result[1] insert = """INSERT INTO {} VALUES(NOW(),{})""".format(tabel, status) cursor.execute(insert) db.commit() delayping = data / 1000 delay = 2 - delayping _query30 = "INSERT INTO {} VALUES(NOW(),{}) ".format(tabel30,status) selectdata = "SELECT COUNT(waktu) FROM International30" cursor.execute(selectdata) hasil = cursor.fetchall() hasil = zip(*hasil) data = hasil[0][0] if data >= 30: deldata = "DELETE FROM {} ORDER BY DATE(waktu) ASC LIMIT 1".format(tabel30) cursor.execute(deldata) cursor.execute(_query30) db.commit() else : cursor.execute(_query30) db.commit() def proses(ip, tabel, tabel30): while True : datasql(ip, tabel, tabel30) time.sleep(2)
iii. Source Code “intping.py”
#!/usr/bin/python from pingscript import proses import time ip = "103.3.78.105" tabel = "International" tabel30 = "International30" proses(ip, tabel, tabel30)
iv. Source Code “indping.py”
#!/usr/bin/python from pingscript import proses ip = "103.3.78.109" tabel = "indonesia" tabel30 = "indonesia30" proses(ip, tabel, tabel30)
115
v. Source Code “gtwping.py”
#/usr/bin/python from pingscript import proses ip = "103.3.46.254" tabel = "gateway" tabel30 = "gateway30" proses(ip, tabel, tabel30)
vi. Source Code “gooping.py”
#!/usr/bin/python from pingscript import proses ip = "8.8.8.8" tabel = "google" tabel30 = "google30" proses(ip, tabel, tabel30)
vii. Source Code “bandwidthscript.py”
#!/usr/bin/python from database import db_conn import ftplib import time import os import subprocess import re def getfile(filename) : ftp = ftplib.FTP("103.3.46.254") ftp.login("hanang", "HackActivity") ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write) ftp.quit() def readfile(filename) : files = open(filename,'r+') reads = files.read() rx = re.findall(r'rx-bits-per-second:(.*)',reads)
tx = re.findall(r'tx-bits-per-second:(.*)',reads) rxregexnum = 0 rxregexchar = [] txregexnum = 0 txregexchar = [] rxmatch = [] if rx == rxmatch : pass else : rxgetlist = rx[0] rxregexnum = re.findall(r'\d{1,}', rxgetlist) rxregexnum = float(rxregexnum[0]) rxregexchar = re.findall(r'[A-Za-z]', rxgetlist) txgetlist = tx[0] txregexnum = re.findall(r'\d{1,}', txgetlist) txregexnum = float(txregexnum[0]) txregexchar = re.findall(r'[A-Za-z]', txgetlist) mregexchar = ["M", "b", "p", "s"] kregexchar = ["k", "b", "p", "s"] bregexchar = ["b", "p", "s"] nullregexchar = []
116
if rxregexchar == mregexchar : rxbit = rxregexnum elif rxregexchar == kregexchar : rxbit = rxregexnum / 1024 elif rxregexchar == nullregexchar : rxbit = rxregexnum / 1024 elif rxregexchar == bregexchar : rxbit = rxregexnum / 1048576 if txregexchar == mregexchar : txbit = txregexnum elif txregexchar == kregexchar : txbit = txregexnum / 1024 elif txregexchar == nullregexchar: txbit = txregexnum / 1024 elif txregexchar == bregexchar : txbit = txregexnum / 1048576 return rxbit, txbit def mysql(tabeldb,rxbit,txbit,tabeldb30) : db = db_conn _insert = """INSERT INTO %s VALUES (NOW(),%s,%s)"""%(tabeldb,rxbit,txbit) cursor = db.cursor() cursor.execute(_insert) _query30 = "INSERT INTO %s VALUES(NOW(),%s,%s) "%(tabeldb30,rxbit, txbit) selectdata = "SELECT COUNT(waktu) FROM %s"%(tabeldb30) cursor.execute(selectdata) hasil = cursor.fetchall() hasil = zip(*hasil) data = hasil[0][0] if data >= 30: deldata = "DELETE FROM %s ORDER BY DATE(waktu) ASC LIMIT 1"%(tabeldb30) cursor.execute(deldata) cursor.execute(_query30) db.commit() else : cursor.execute(_query30) db.commit() db.commit() def maincode(filename,tabeldb,tabeldb30) : getfile(filename) readfiles = readfile(filename) rxbit = readfiles[0] txbit = readfiles[1] mysql(tabeldb,rxbit,txbit,tabeldb30)
viii. Source Code “ixbw.py”
#!/usr/bin/python from bandwidthscript import maincode from time import sleep while True : filename = "int.txt" tabeldb = "p2pix" tabeldb30 = "p2pix30"
maincode(filename,tabeldb,tabeldb30) sleep(2)
117
ix. Source Code “iixbw.py”
#!/usr/bin/python from bandwidthscript import maincode from time import sleep while True : filename = "ind.txt" tabeldb = "p2piix" tabeldb30 = "p2piix30" maincode(filename,tabeldb,tabeldb30) sleep(2)
x. Source Code “gtwbw.py”
#!/usr/bin/python from bandwidthscript import maincode from time import sleep while True : filename = "gate254.txt" tabeldb = "gtw254" tabeldb30 = "gtw25430" maincode(filename,tabeldb,tabeldb30) sleep(2)
xi. Source Code “temperatur.py”
#!/usr/bin/python3 import os, glob, time, sys, datetime from database import db_conn db = db_conn os.system('sudo modprobe w1-gpio') os.system('sudo modprobe w1-therm') device_folder = glob.glob('/sys/bus/w1/devices/28*') while True : device_file = [] lendevice = len(device_folder) temp_list=[] for i in range(lendevice): folder = device_folder[i] + '/w1_slave' device_file.append(folder) filestemp = open(device_file[i],'r') lines = filestemp.read() gettemp = lines.find('t=') temp = float(lines[gettemp+2:])/1000 if temp >= 0 : if temp <= 40: temp_list.append(temp) else : pass cursor = db.cursor() _query = "INSERT INTO temperatur (waktu,suhu1,suhu2,suhu3) VALUES(NOW(),{},{},{}) ".format(temp_list[0],temp_list[1],temp_list[2]) cursor.execute(_query) db.commit() _query30 = "INSERT INTO temperatur30 (waktu,suhu1,suhu2,suhu3) VALUES(NOW(),{},{},{}) ".format(temp_list[0],temp_list[1],temp_list[2]) selectdata = "SELECT COUNT(waktu) FROM temperatur30" cursor.execute(selectdata)
118
hasil = cursor.fetchall() hasil = zip(*hasil) data = hasil[0][0] if data >= 30: deldata = "DELETE FROM temperatur30 ORDER BY DATE(waktu) ASC LIMIT 1" cursor.execute(deldata) cursor.execute(_query30) db.commit() else : cursor.execute(_query30) db.commit() suhu1 = temp_list[0] suhu2 = temp_list[1] suhu3 = temp_list[2] if suhu1 < 18 or suhu2 < 18 or suhu3 < 18: tempstat = "dingin" elif suhu1 > 27 or suhu2 > 27 or suhu3 > 27: tempstat = "panas" else: tempstat = "aman" files = open("tempresult.txt","w") files.write(tempstat) files.close()
xii. Source Code “getlistrik.py”
#!/usr/bin/python import RPi.GPIO as GPIO import time def readgpio(): GPIO.setmode(GPIO.BCM) channelIN = GPIO.setup(27, GPIO.IN) return channelIN def readvolt(): channel = readgpio() files = open("listrikresult.txt","w") if (GPIO.input(27)) : status = 1 files.write("hidup") else: status = 0 files.write("mati") files.close() return status def sql(): from database import db_conn db = db_conn cur = db.cursor() result = readvolt() selects = "SELECT COUNT(waktu) FROM listrik30" cur.execute(selects) counts = cur.fetchone() len = counts[0] if result == 1: cur.execute("INSERT INTO listrik VALUES(NOW(),1)") if len <= 30: cur.execute("DELETE FROM listrik30 ORDER BY DATE(waktu) ASC LIMIT 1") cur.execute("INSERT INTO listrik30 VALUES(NOW(),1)") else:
119
cur.execute("INSERT INTO listrik30 VALUES(NOW(),1)") elif result == 0: cur.execute("INSERT INTO listrik VALUSE(NOW(),0)") if len <= 30: cur.execute("DELETE FROM listrik30 ORDER BY DATE(waktu) ASC LIMIT 1") cur.execute("INSERT INTO listrik30 VALUES(NOW(),0)") else: cur.execute("INSERT INTO listrik30 VALUES(NOW(),0)") db.commit() while True: readvolt() sql() time.sleep(2)
xiii. Source Code “smsscript.py”
#!/usr/bin/python from database import db_conn from hplist import nohp import time import datetime import MySQLdb import os from sendsms import sendsms def sqlread(tabel): db = db_conn query = "SELECT status FROM {} ORDER BY DATE(waktu) DESC LIMIT 7; ".format(tabel) cursor = db.cursor() cursor.execute(query) getdata = cursor.fetchall() result = zip(*getdata) result = result[0] list = [] for i in range(len(result)): if result[i] == 0: list.append(result[i]) else : pass hasil = len(list) return hasil def waktu(namalink): tanggal = datetime.datetime.now() date = tanggal.strftime('%H:%M:%S %d/%m/%Y') sambung = "Raspberry Report : Jaringan {} Tersambung Kembali Pada Pukul : {}".format(namalink,date) putus = "Rasberry Report : Jaringan {} Putus Pada Pukul : {}".format(namalink,date) return sambung, putus def proses(tabel,namalink,filestatus): listhp = nohp() datasql = sqlread(tabel) statussambung =waktu(namalink)[0] statusputus = waktu(namalink)[1] if datasql >= 7: files = open(filestatus,"r") status = files.readlines() status = status[0] #print status files.close()
120
if status == "terkoneksi" : for i in range(len(listhp)): sendsms(statusputus,listhp[i]) #print "putus" files = open(filestatus,"w") files.write("terputus") files.close() else : #print "masih putus" files = open(filestatus,"w") files.write("terputus") files.close() elif datasql <= 2: files = open(filestatus,"r") status = files.readlines() status = status[0] #print status files.close() if status == "terputus" : for i in range(len(listhp)): sendsms(statussambung,listhp[i]) #print "nyambung" files = open(filestatus,"w") files.write("terkoneksi") files.close() else : #print "Masih nyambung" files = open(filestatus,"w") files.write("terkoneksi") files.close()
xiv. Source Code “intsms.py”
#!/usr/bin/python from smsscript import sqlread, waktu, proses from time import sleep tabeldata = "International30" link = "International" istatus = "/home/pi/intstatus.txt" while True: sqlread(tabeldata) waktu(link) proses(tabeldata,link,istatus) sleep(20)
xv. Source Code “smstemp.py”
#!/usr/bin/python from database import db_conn from sendsms import sendsms from hplist import nohp import time import datetime import MySQLdb import os def sqlread(tabel): db = db_conn query = "SELECT * FROM {};".format(tabel) cur = db.cursor()
121
cur.execute(query) result = cur.fetchall() hasil = zip(*result) waktu = hasil[0][29] suhu1 = int(hasil[1][29]) suhu2 = int(hasil[2][29]) suhu3 = int(hasil[3][29]) values = "{} C sampai {} C".format(suhu1,suhu3) if suhu1 > 27.0 or suhu2 > 27.0 or suhu3 > 27.0: hasiltemp = "panas" elif suhu1 < 18.0 or suhu2 < 18.0 or suhu3 < 18.0: hasiltemp = "dingin" else: hasiltemp = "aman" return hasiltemp, values, waktu def proses(tabel,namalink,filestatus): listhp = nohp() datasql = sqlread(tabel)[0] hasil = sqlread(tabel)[1] tanggal = sqlread(tabel)[2] warnhot = "Warning!! {} Ruang Data Center saat ini yaitu {}.Pukul : {}".format(namalink,hasil,tanggal) warncold = "Warning!! {} Ruang Data Center saat ini yaitu {}.Pukul : {}".format(namalink,hasil,tanggal) safes = "Safe!! {} Data Center saat ini yaitu {}.Pukul : {}".format(namalink,hasil,tanggal) if datasql == "panas": files = open(filestatus,"r") status = files.readlines() status = status[0] #print status files.close() if status != "panas" : for i in range(len(listhp)): sendsms(warnhot,listhp[i]) #print "putus" files = open(filestatus,"w") files.write("panas") files.close() else : #print "masih putus" files = open(filestatus,"w") files.write("panas") files.close() elif datasql == "dingin": files = open(filestatus,"r") status = files.readlines() status = status[0] #print status files.close() if status != "dingin" : for i in range(len(listhp)): sendsms(warncold,listhp[i]) #print "nyambung" files = open(filestatus,"w") files.write("dingin") files.close() else : #print "Masih nyambung" files = open(filestatus,"w") files.write("dingin") files.close() elif datasql == "aman": files = open(filestatus,"r") status = files.readlines() status = status[0] #print status files.close() if status != "aman" :
122
for i in range(len(listhp)): sendsms(safes,listhp[i]) #print "nyambung" files = open(filestatus,"w") files.write("aman") files.close() else : #print "Masih nyambung" files = open(filestatus,"w") files.write("aman") files.close()
xvi. Source Code “temsms.py”
#!/usr/bin/python from smstemp import sqlread, proses from time import sleep tabeldata = "temperatur30" link = "Temperatur" istatus = "/home/pi/tempstatus.txt" while True: sqlread(tabeldata) proses(tabeldata,link,istatus) sleep(30)
xvii. Source Code “smslistrik.py”
#!/usr/bin/python from hplist import nohp from sendsms import sendsms import time import datetime def getstatus(): files = open("/home/pi/listrikresult.txt","r").read() return files def readstatus(): fileread = open("/home/pi/listrikstatus.txt","r").read() return fileread def writestatus(): filewrite = open("/home/pi/listrikstatus.txt","w").write() return filewrite def waktu(): tanggal = datetime.datetime.now() date = tanggal.strftime('%H:%M:%S %d/%m/%Y') return date def isisms(): getfiles = getstatus() jam = waktu() if getfiles == "hidup": status = "Raspberry Report!! Listrik Hidup Pada Pukul {}".format(jam) elif getfiles == "mati":
123
status = "Raspberry Report!! Listrik Mati Pada Pukul {}".format(jam) else: pass return status def proses(): setstatus = getstatus() statusread = readstatus() listhp = nohp() isi = isisms() if setstatus != "": if setstatus != statusread: for j in range(len(listhp)): sendsms(isi,listhp[j]) open("/home/pi/listrikstatus.txt","w").write(setstatus) def mainprog(): while True: proses() time.sleep(20) if __name__ == "__main__": mainprog()
xviii. Source Code “sendsms.py”
#!/usr/bin/python
import MySQLdb
def sendsms(isisms,dest):
datadb = MySQLdb.connect("localhost", "root", "hanang", "gammu_sms")
datacursor = datadb.cursor()
format = "normal"
creator = "gammu"
kelas = "-1"
if format == "normal":
query = "INSERT INTO outbox(DestinationNumber, TextDecoded,
CreatorID, Class) VALUES('%s','%s','%s','%s')"%(dest, isisms, creator, kelas)
datacursor.execute(query)
datadb.commit()
124
xix. Source Code “listhp.py”
#!/usr/bin/python
def nohp():
hanang = "089631031009"
pakgigih = "085289774152"
mashendri = "085766722507"
pakkomar = "0811799961"
paklukman = "087899210125"
ilist = [hanang,pakgigih,mashendri,pakkomar,paklukman]
return ilist
xx. Source Code “sshreportscript.py”
#!/usr/bin/python
import subprocess
import sys
def host():
host = "[email protected]"
return host
def proses(COMMAND):
HOST = host()
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
xxi. Source Code “sshreportharian.py”
#!/usr/bin/python
from sshreportscript import proses
command = "/usr/bin/python /home/hanang/dayreport.py"
proses(command)
125
xxii. Source Code “sshreportmingguan.py”
#!/usr/bin/python
from sshreportscript import proses
command = "/usr/bin/python /home/hanang/weekreport.py"
proses(command)
xxiii. Source Code “sshreportbulanan.py”
#!/usr/bin/python
from sshreportscript import proses
command = "/usr/bin/python /home/hanang/monthreport.py"
proses(command)
xxiv. Source Code “satpam.py”
import os
import re
import time
from directping import pingcode
while True :
pingdb = pingcode("192.168.1.109")
if pingdb == 1:
f = os.popen("ps ax").read()
ix = re.findall(r'/usr/bin/python /home/pi/ixbw.py', f)
iix = re.findall(r'/usr/bin/python /home/pi/iixbw.py', f)
gtw = re.findall(r'/usr/bin/python /home/pi/gtwbw.py', f)
temp = re.findall(r'/usr/bin/python /home/pi/temperatur.py', f)
ixping = re.findall(r'/usr/bin/python /home/pi/intping.py', f)
iixping = re.findall(r'/usr/bin/python /home/pi/indping.py', f)
126
gtwping = re.findall(r'/usr/bin/python /home/pi/gtwping.py', f)
gooping = re.findall(r'/usr/bin/python /home/pi/gooping.py', f)
listrik = re.findall(r'sudo /usr/bin/python
/home/pi/getlistrik.py', f)
intsms = re.findall(r'/usr/bin/python /home/pi/intsms.py', f)
tempsms = re.findall(r'/usr/bin/python /home/pi/tempsms.py', f)
listriksms = re.findall(r'/usr/bin/python /home/pi/smslistrik.py',
f)
gtwmatch = ["/usr/bin/python /home/pi/gtwbw.py"]
if gtw != gtwmatch:
os.system("/usr/bin/python /home/pi/gtwbw.py &")
ixmatch = ["/usr/bin/python /home/pi/ixbw.py"]
if ix != ixmatch:
os.system("/usr/bin/python /home/pi/ixbw.py &")
iixmatch = ["/usr/bin/python /home/pi/iixbw.py"]
if iix != iixmatch:
os.system("/usr/bin/python /home/pi/iixbw.py &")
tempmatch = ["/usr/bin/python /home/pi/temperatur.py"]
if temp != tempmatch:
os.system("/usr/bin/python /home/pi/temperatur.py &")
gtwpingmatch = ["/usr/bin/python /home/pi/gtwping.py"]
if gtwping != gtwpingmatch:
os.system("/usr/bin/python /home/pi/gtwping.py &")
ixpingmatch = ["/usr/bin/python /home/pi/intping.py"]
if ixping != ixpingmatch:
os.system("/usr/bin/python /home/pi/intping.py &")
iixpingmatch = ["/usr/bin/python /home/pi/indping.py"]
if iixping != iixpingmatch:
os.system("/usr/bin/python /home/pi/indping.py &")
127
goopingmatch = ["/usr/bin/python /home/pi/gooping.py"]
if gooping != goopingmatch:
os.system("/usr/bin/python /home/pi/gooping.py &")
listrikmatch = ["sudo /usr/bin/python /home/pi/getlistrik.py"]
if listrik != listrikmatch:
os.system("sudo /usr/bin/python /home/pi/getlistrik.py &")
intsmsmatch = ["/usr/bin/python /home/pi/intsms.py"]
if intsms != intsmsmatch:
os.system("/usr/bin/python /home/pi/intsms.py &")
tempsmsmatch = ["/usr/bin/python /home/pi/tempsms.py"]
if tempsms != tempsmsmatch:
os.system(" /usr/bin/python /home/pi/tempsms.py &")
listriksmsmatch = ["/usr/bin/python /home/pi/smslistrik.py"]
if listriksms != listriksmsmatch:
os.system(" /usr/bin/python /home/pi/smslistrik.py &")
time.sleep(10)
xxv. Source Code “startup.py”
#!/usr/bin/python
import subprocess
import os
import time
with open(os.devnull, "wb") as limbo:
ip = "192.168.1.109"
while True :
128
result = subprocess.Popen(["ping", "-c", "1","-i","1","-
W","1",ip],stdout=limbo, stderr=limbo).wait()
if result :
pass
else :
break
time.sleep(1)
while True :
result = subprocess.Popen(["ping", "-c", "1","-i","1","-
W","1",ip],stdout=limbo, stderr=limbo).wait()
if result :
pass
else :
break
time.sleep(1)
os.system("/usr/bin/python /home/pi/indping.py &")
os.system("/usr/bin/python /home/pi/intping.py &")
os.system("/usr/bin/python /home/pi/gooping.py &")
os.system("/usr/bin/python /home/pi/gtwping.py &")
os.system("/usr/bin/python /home/pi/ixbw.py &")
os.system("/usr/bin/python /home/pi/iixbw.py &")
os.system("/usr/bin/python /home/pi/gtwbw.py &")
os.system("sudo /usr/bin/python /home/pi/getlistrik.py &")
os.system("/usr/bin/python /home/pi/temperatur.py &")
os.system("/usr/bin/python /home/pi/vmstat.py &")
os.system("/usr/bin/python /home/pi/intsms.py &")
os.system("/usr/bin/python /home/pi/tempsms.py &")
os.system("/usr/bin/python /home/pi/smslistrik.py &")
os.system("sudo /etc/init.d/gammu-smsd start &")
os.system("/usr/bin/python /home/pi/satpam.py &")
Source Program Berada Pada mesin databases dan web server
129
xxvi. Source Code “listmail.py”
def mailname():
list = [
]
return list
xxvii. Source Code “dayreport.py”
import MySQLdb as mdb
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
from reportlab.platypus.flowables import Image, PageBreak
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
styles = getSampleStyleSheet()
def getdata(table):
query = "SELECT * FROM %s WHERE DATE(waktu) = DATE(NOW() - INTERVAL 1 DAY)" %
(table)
cur.execute(query)
data = cur.fetchall()
return data
130
def gettanggal():
query1 = "SELECT DATE(NOW() - INTERVAL 1 DAY)"
cur.execute(query1)
tanggal = cur.fetchall()
date = zip(*tanggal)
idate = date[0][0]
return idate
def plot1(data, figid, title, xlabel, ylabel, filename):
x, y = [], []
for record in data:
x.append(record[0])
y.append(record[1])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y)
plt.ylim([-0.25, 1.25])
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
def plot2(data, figid, title, xlabel, ylabel, filename):
x, y1, y2 = [], [], []
for record in data:
x.append(record[0])
y1.append(record[1])
y2.append(record[2])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label = "Receive")
plt.plot(x, y2, label = "Transmite")
plt.legend(loc='upper left')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
131
plt.grid()
savefig(filename)
def plot3(data, figid, title, xlabel, ylabel, filename):
x, y1, y2, y3 = [], [], [], []
for record in data:
x.append(record[0])
y1.append(record[1])
y2.append(record[2])
y3.append(record[3])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label="suhu1")
plt.plot(x, y2, label="suhu2")
plt.plot(x, y3, label="suhu3")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
con = mdb.connect('localhost', 'root', 'hanang', 'skripsihanang')
cur = con.cursor()
gtway = getdata('gateway')
google = getdata('google')
gtw254 = getdata('gtw254')
pingid = getdata('indonesia')
pingit = getdata('International')
listrk = getdata('listrik')
p2pix = getdata('p2pix')
p2piix = getdata('p2piix')
temprt = getdata('temperatur')
dates = gettanggal()
con.close()
plot1(gtway, 1, "Ping Gateway", "Waktu", "Status", "daygateway.png")
132
plot1(google, 2, "Ping Google", "Waktu", "Status", "daygoogle.png")
plot2(gtw254, 3, "Gateway 254", "Waktu", "Bandwidth", "daygtw254.png")
plot1(pingid, 4, "Ping Indonesia", "Waktu", "Status", "dayindonesia.png")
plot1(pingit, 5, "Ping International", "Waktu", "Status", "dayInternational.png")
plot1(listrk, 6, "Listrik", "Waktu", "Status", "daylistrik.png")
plot2(p2pix, 7, "Bandwidth International", "Waktu", "Bandwidth", "dayp2pix.png")
plot2(p2piix, 8, "Bandwidth Indonesia", "Waktu", "Bandwidth", "dayp2piix.png")
plot3(temprt, 9, "Temperatur", "Waktu", "Temperatur", "daytemperatur.png")
def headfoot(canvas):
canvas.setFont('Times-Roman', 14)
canvas.setStrokeColorCMYK(0, 1, 1, 0, 1)
canvas.drawString(2*cm, 28.2*cm, "Sistem Pemantauan")
canvas.drawString(2*cm, 27.7*cm, "Bandwidth, Listrik, Temperatur")
canvas.line(2*cm, 27.6*cm, 15*cm, 27.6*cm)
canvas.line(12*cm, 27.4*cm, 19*cm, 27.4*cm)
canvas.setFont('Courier-Oblique', 14)
canvas.setFillColorCMYK(0.5,0,1,0,1)
canvas.drawString(13.3*cm, 26.9*cm, "Gedung Pusat Data")
canvas.drawString(13.3*cm, 26.5*cm, "Universitas Lampung")
canvas.setStrokeColorCMYK(0, 0, 0, 0.9, 1)
canvas.setLineWidth(0.2*cm)
canvas.line(2*cm, 26.3*cm, 19*cm, 26.3*cm)
canvas.setFont('Times-Roman', 10)
canvas.setFillColorCMYK(0,1,1,0,1)
canvas.drawString(2*cm, 26.7*cm, "Laporan Harian. Tanggal : {}".format(dates))
canvas.line(2*cm, 1.5*cm, 19*cm, 1.5*cm)
canvas.setFillColorCMYK(0, 0.38, 0.64, 0.58, 0)
canvas.setFont('Times-Roman', 9)
canvas.drawString(2*cm, 1*cm, "UPT-Puskom")
def myFirstPage(canvas, doc):
canvas.saveState()
headfoot(canvas)
canvas.setFont('Times-Roman', 9)
133
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def myLaterPages(canvas, doc):
canvas.saveState()
headfoot(canvas)
canvas.setFont('Times-Roman',9)
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def go():
doc = SimpleDocTemplate("laporan_harian.pdf")
story = [Spacer(1,1.5*cm)]
story.append(Image("daygtw254.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("dayp2pix.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("dayp2piix.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("daygateway.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("dayindonesia.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("dayInternational.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("daygoogle.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("daylistrik.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("daytemperatur.png", width=16*cm, height=7*cm))
doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
134
##### Mengirim Email
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
from listmail import mailname
import os
srcmail = "[email protected]"
passmail = "AkuAdalahMesiN2014"
maillist = mailname()
#mailname = "[email protected], [email protected]"
sub = "Laporan Harian"
isi = "Dilampirkan laporan untuk tanggal {}".format(dates)
commaspace = ", "
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = srcmail
msg['To'] = commaspace.join(to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'pdf',
name="laporan_harian{}.pdf".format(dates))
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Dispotition','attachment=laporan_harian.pdf;
filenames="%s"'% os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
135
mailServer.ehlo()
mailServer.login(srcmail, passmail)
mailServer.sendmail(srcmail, to , msg.as_string())
mailServer.close()
def mainprog():
go()
mail(maillist, sub, isi,"laporan_harian.pdf")
mainprog()
xxviii. Source Code “weekreport.py”
import MySQLdb as mdb
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
from reportlab.platypus.flowables import Image, PageBreak
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
styles = getSampleStyleSheet()
def getdata(table):
#query = "SELECT * FROM %s WHERE MONTH(waktu) = MONTH(NOW())" % (table)
query = "SELECT * FROM %s WHERE WEEK(waktu) = WEEK(NOW() - INTERVAL 2 DAY)" %
(table)
cur.execute(query)
data = cur.fetchall()
return data
136
def plot1(data, figid, title, xlabel, ylabel, filename):
x, y = [], []
for record in data:
x.append(record[0])
y.append(record[1])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y)
plt.ylim([-0.25, 1.25])
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
def plot2(data, figid, title, xlabel, ylabel, filename):
x, y1, y2 = [], [], []
for record in data:
x.append(record[0])
y1.append(record[1])
y2.append(record[2])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label = "Receive")
plt.plot(x, y2, label = "Transmite")
plt.legend(loc='upper left')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
def plot3(data, figid, title, xlabel, ylabel, filename):
x, y1, y2, y3 = [], [], [], []
for record in data:
x.append(record[0])
y1.append(record[1])
y2.append(record[2])
137
y3.append(record[3])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label="suhu1")
plt.plot(x, y2, label="suhu2")
plt.plot(x, y3, label="suhu3")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
con = mdb.connect('localhost', 'root', 'hanang', 'skripsihanang')
cur = con.cursor()
gtway = getdata('gateway')
google = getdata('google')
gtw254 = getdata('gtw254')
pingid = getdata('indonesia')
pingit = getdata('International')
listrk = getdata('listrik')
p2pix = getdata('p2pix')
p2piix = getdata('p2piix')
temprt = getdata('temperatur')
con.close()
plot1(gtway, 1, "Ping Gateway", "Waktu", "Status", "gateway.png")
plot1(google, 2, "Ping Google", "Waktu", "Status", "google.png")
plot2(gtw254, 3, "Gateway 254", "Waktu", "Bandwidth", "gtw254.png")
plot1(pingid, 4, "Ping Indonesia", "Waktu", "Status", "indonesia.png")
plot1(pingit, 5, "Ping International", "Waktu", "Status", "International.png")
plot1(listrk, 6, "Listrik", "Waktu", "Status", "listrik.png")
plot2(p2pix, 7, "p2pix", "Waktu", "Bandwidth", "p2pix.png")
plot2(p2piix, 8, "p2piix", "Waktu", "Bandwidth", "p2piix.png")
plot3(temprt, 9, "Temperatur", "Waktu", "Temperatur", "temperatur.png")
138
def headfoot(canvas):
canvas.setFont('Times-Roman', 14)
canvas.setStrokeColorCMYK(0, 1, 1, 0, 1)
canvas.drawString(2*cm, 28.2*cm, "Sistem Pemantauan")
canvas.drawString(2*cm, 27.7*cm, "Bandwidth, Listrik, Temperatur")
canvas.line(2*cm, 27.6*cm, 15*cm, 27.6*cm)
canvas.line(12*cm, 27.4*cm, 19*cm, 27.4*cm)
canvas.setFont('Courier-Oblique', 14)
canvas.setFillColorCMYK(0.5,0,1,0,1)
canvas.drawString(13.3*cm, 26.9*cm, "Gedung Pusat Data")
canvas.drawString(13.3*cm, 26.5*cm, "Universitas Lampung")
canvas.setStrokeColorCMYK(0, 0, 0, 0.9, 1)
canvas.setLineWidth(0.2*cm)
canvas.line(2*cm, 26.3*cm, 19*cm, 26.3*cm)
canvas.setFont('Times-Roman', 10)
canvas.setFillColorCMYK(0,1,1,0,1)
canvas.drawString(2*cm, 26.7*cm, "Laporan Mingguan")
canvas.line(2*cm, 1.5*cm, 19*cm, 1.5*cm)
canvas.setFillColorCMYK(0, 0.38, 0.64, 0.58, 0)
canvas.setFont('Times-Roman', 9)
canvas.drawString(2*cm, 1*cm, "UPT-Puskom")
def myFirstPage(canvas, doc):
canvas.saveState()
headfoot(canvas)
canvas.setFont('Times-Roman', 9)
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def myLaterPages(canvas, doc):
canvas.saveState()
headfoot(canvas)
canvas.setFont('Times-Roman',9)
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
139
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def go():
doc = SimpleDocTemplate("laporan_mingguan.pdf")
story = [Spacer(1,1.5*cm)]
story.append(Image("gtw254.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("p2pix.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("p2piix.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("gateway.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("indonesia.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("International.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("google.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("listrik.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("temperatur.png", width=16*cm, height=7*cm))
doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
##### Mengirim Email
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
from listmail import mailname
140
import os
srcmail = "[email protected]"
passmail = "AkuAdalahMesiN2014"
maillist = mailname()
#mailname = "[email protected], [email protected]"
sub = "Laporan Mingguan"
isi = "Dilampirkan laporan untuk pekan lalu. ubah file menjadi file.pdf untuk
membukanya"
commaspace = ", "
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = srcmail
msg['To'] = commaspace.join(to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'pdf',name="laporan_mingguan.pdf")
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Dispotition','attachment; filenames=%s' %
os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(srcmail, passmail)
mailServer.sendmail(srcmail, to , msg.as_string())
mailServer.close()
def mainprog():
go()
mail(maillist, sub, isi, "laporan_mingguan.pdf")
141
mainprog()
xxix. Source Code “monthreport.py”
import MySQLdb as mdb
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
from reportlab.platypus.flowables import Image, PageBreak
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
styles = getSampleStyleSheet()
def getdata(table):
query = "SELECT * FROM %s WHERE MONTH(waktu) = MONTH(NOW() - INTERVAL 1 MONTH)"
% (table)
cur.execute(query)
data = cur.fetchall()
return data
def plot1(data, figid, title, xlabel, ylabel, filename):
x, y = [], []
for record in data:
x.append(record[0])
y.append(record[1])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y)
plt.ylim([-0.25, 1.25])
plt.xlabel(xlabel)
142
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
def getbulan():
query1 = "SELECT MONTH(NOW() - INTERVAL 1 MONTH)"
cur.execute(query1)
bulan = cur.fetchall()
bulan = [0][0]
query2 = "SELECT YEAR(NOW())"
cur.execute(query2)
tahun = cur.fetchall()
tahun = tahun[0][0]
hasilbulan = "Bulan ke:{}, Tahun {}".format(bulan, tahun)
return hasilbulan
def plot2(data, figid, title, xlabel, ylabel, filename):
x, y1, y2 = [], [], []
for record in data:
x.append(record[0])
y1.append(record[1])
y2.append(record[2])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label = "Receive")
plt.plot(x, y2, label = "Transmite")
plt.legend(loc='upper left')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
def plot3(data, figid, title, xlabel, ylabel, filename):
x, y1, y2, y3 = [], [], [], []
for record in data:
x.append(record[0])
143
y1.append(record[1])
y2.append(record[2])
y3.append(record[3])
plt.figure(figid, figsize=(16, 7))
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.plot(x, y1, label="suhu1")
plt.plot(x, y2, label="suhu2")
plt.plot(x, y3, label="suhu3")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.grid()
savefig(filename)
con = mdb.connect('localhost', 'root', 'hanang', 'skripsihanang')
cur = con.cursor()
gtway = getdata('gateway')
google = getdata('google')
gtw254 = getdata('gtw254')
pingid = getdata('indonesia')
pingit = getdata('International')
listrk = getdata('listrik')
p2pix = getdata('p2pix')
p2piix = getdata('p2piix')
temprt = getdata('temperatur')
con.close()
plot1(gtway, 1, "Ping Gateway", "Waktu", "Status", "monthgateway.png")
plot1(google, 2, "Ping Google", "Waktu", "Status", "monthgoogle.png")
plot2(gtw254, 3, "Gateway 254", "Waktu", "Bandwidth", "monthgtw254.png")
plot1(pingid, 4, "Ping Indonesia", "Waktu", "Status", "monthindonesia.png")
plot1(pingit, 5, "Ping International", "Waktu", "Status", "monthInternational.png")
plot1(listrk, 6, "Listrik", "Waktu", "Status", "monthlistrik.png")
plot2(p2pix, 7, "Bandwidth International", "Waktu", "Bandwidth", "monthp2pix.png")
plot2(p2piix, 8, "Bandwidth Indonesia", "Waktu", "Bandwidth", "monthp2piix.png")
144
plot3(temprt, 9, "Temperatur", "Waktu", "Temperatur", "monthtemperatur.png")
def headfoot(canvas):
canvas.setFont('Times-Roman', 14)
canvas.setStrokeColorCMYK(0, 1, 1, 0, 1)
canvas.drawString(2*cm, 28.2*cm, "Sistem Pemantauan")
canvas.drawString(2*cm, 27.7*cm, "Bandwidth, Listrik, Temperatur")
canvas.line(2*cm, 27.6*cm, 15*cm, 27.6*cm)
canvas.line(12*cm, 27.4*cm, 19*cm, 27.4*cm)
canvas.setFont('Courier-Oblique', 14)
canvas.setFillColorCMYK(0.5,0,1,0,1)
canvas.drawString(13.3*cm, 26.9*cm, "Gedung Pusat Data")
canvas.drawString(13.3*cm, 26.5*cm, "Universitas Lampung")
canvas.setStrokeColorCMYK(0, 0, 0, 0.9, 1)
canvas.setLineWidth(0.2*cm)
canvas.line(2*cm, 26.3*cm, 19*cm, 26.3*cm)
canvas.setFont('Times-Roman', 10)
canvas.setFillColorCMYK(0,1,1,0,1)
canvas.drawString(2*cm, 26.7*cm, "Laporan Bulanan")
canvas.line(2*cm, 1.5*cm, 19*cm, 1.5*cm)
canvas.setFillColorCMYK(0, 0.38, 0.64, 0.58, 0)
canvas.setFont('Times-Roman', 9)
canvas.drawString(2*cm, 1*cm, "UPT-Puskom")
def myFirstPage(canvas, doc):
canvas.saveState()
headfoot(canvas)
canvas.setFont('Times-Roman', 9)
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def myLaterPages(canvas, doc):
canvas.saveState()
145
headfoot(canvas)
canvas.setFont('Times-Roman',9)
canvas.setFillColorCMYK(0, 0, 0, 1, 1)
canvas.drawString(18*cm, 1*cm, "Hal. %d" % (doc.page))
canvas.restoreState()
def go():
doc = SimpleDocTemplate("laporan_bulanan.pdf")
story = [Spacer(1,1.5*cm)]
story.append(Image("monthgtw254.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthp2pix.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthp2piix.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("monthgateway.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthindonesia.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthInternational.png", width=16*cm, height=7*cm))
story.append(PageBreak())
story.append(Spacer(1, 1.5*cm,))
story.append(Image("monthgoogle.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthlistrik.png", width=16*cm, height=7*cm))
story.append(Spacer(1, 0.8*cm,))
story.append(Image("monthtemperatur.png", width=16*cm, height=7*cm))
doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
146
from listmail import mailname
import os
srcmail = "[email protected]"
passmail = "AkuAdalahMesiN2014"
maillist = mailname()
#mailname = "[email protected], [email protected]"
sub = "Laporan Bulanan"
#months = getbulan()
isi = "Dilampirkan laporan bulan lalu. ubah file menjadi file.pdf untuk membukanya"
commaspace = ", "
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = srcmail
msg['To'] = commaspace.join(to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Dispotition','attachment; filenames=%s' %
os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(srcmail, passmail)
mailServer.sendmail(srcmail, to , msg.as_string())
mailServer.close()
def mainprog():
go()
147
mail(maillist, sub, isi, "laporan_bulanan.pdf")
mainprog()
xxx. Source Code “index.py”
#!/usr/bin/python
from hp_indexweb import mainprog
if __name__ == "__main__":
mainprog()
xxxi. Source Code “hp_indexweb.py”
#!/usr/bin/python
from hp_indexscript import htmltop,jstop,jsend, bottom
from hp_getcanvas import canvastop
from hp_plotreallistrik import jsplotlistrik
from hp_plotrealping import jsplotping
from hp_plotrealbandwidth import jsplotbandwidth
from hp_plotrealsuhu import jsplottemperatur
import cgi
import cgitb
cgitb.enable()
form=cgi.FieldStorage()
def listrikplot():
title = "Status Listrik"
canvas = "cvs1"
label = "json.waktulistrik"
148
data = "json.statuslistrik"
getcanvas = canvastop(canvas)
plot = jsplotlistrik(canvas,canvas,data,title,label)
return getcanvas, plot
def intplot():
title = "Status Ping P2P-International (103.3.78.105)"
canvas = "cvs5"
label = "json.waktuint"
data = "json.statusint"
getcanvas = canvastop(canvas)
plot = jsplotping(canvas,canvas,data,title,label)
return getcanvas, plot
def indplot():
title = "Status Ping P2P-Indonesia(103.3.78.109)"
canvas = "cvs6"
label = "json.waktuind"
data = "json.statusind"
getcanvas = canvastop(canvas)
plot = jsplotping(canvas,canvas,data,title,label)
return getcanvas, plot
def gtwplot():
title = "Status Ping BGP Server (103.3.46.254)"
canvas = "cvs7"
label = "json.waktugtw"
data = "json.statusgtw"
getcanvas = canvastop(canvas)
plot = jsplotping(canvas,canvas,data,title,label)
return getcanvas, plot
def gooplot():
title = "Status Ping Google (8.8.8.8)"
canvas = "cvs8"
label = "json.waktugoo"
149
data = "json.statusgoo"
getcanvas = canvastop(canvas)
plot = jsplotping(canvas,canvas,data,title,label)
return getcanvas, plot
def p2pixplot():
title = "Status Bandwidth International"
canvas = "cvs2"
label = "json.waktup2pix"
datarx = "json.rxp2pix"
datatx = "json.txp2pix"
key = "json.labelp2pix"
getcanvas = canvastop(canvas)
plot2 = jsplotbandwidth(canvas,canvas,datarx,datatx,title,key,label)
return getcanvas, plot2
def p2piixplot():
title = "Status Bandwidth Indonesia"
canvas = "cvs3"
label = "json.waktup2piix"
datarx = "json.rxp2piix"
datatx = "json.txp2piix"
key = "json.labelp2piix"
getcanvas = canvastop(canvas)
plot2 = jsplotbandwidth(canvas,canvas,datarx,datatx,title,key,label)
return getcanvas, plot2
def gtw254plot():
title = "Status Bandwidth 103.3.46.254"
canvas = "cvs4"
label = "json.waktugtw254"
datarx = "json.rxgtw254"
datatx = "json.txgtw254"
key = "json.labelgtw254"
getcanvas = canvastop(canvas)
150
plot2 = jsplotbandwidth(canvas,canvas,datarx,datatx,title,key,label)
return getcanvas, plot2
def temperatur():
title = "Status Temperatur Ruang Pusat Data"
canvas = "cvs9"
label = "json.waktutemp"
suhu1 = "json.suhu1temp"
suhu2 = "json.suhu2temp"
suhu3 = "json.suhu3temp"
key = "json.labelsuhu"
getcanvas = canvastop(canvas)
plot = jsplottemperatur(canvas,canvas,suhu1,suhu2,suhu3,title,key,label)
return getcanvas, plot
def setcanvas():
print listrikplot()[0]
print temperatur()[0]
print gtw254plot()[0]
print p2pixplot()[0]
print p2piixplot()[0]
print intplot()[0]
print indplot()[0]
print gtwplot()[0]
print gooplot()[0]
def setplot():
print listrikplot()[1]
print temperatur()[1]
print gtw254plot()[1]
print p2pixplot()[1]
print p2piixplot()[1]
print intplot()[1]
print indplot()[1]
151
print gtwplot()[1]
print gooplot()[1]
def mainprog():
print "Content-type: text/html\n\n"
print htmltop()
setcanvas()
print jstop()
setplot()
print jsend()
print bottom()
xxxii. Source Code “hp_indexscript.py”
#!/usr/bin/python
def htmltop():
tophtml = """
<!DOCTYPE html>
<html>
<head>
<title>Author By : Hanang Priambodo</title>
<meta name="description" content="A basic example of a chart created using
dynamic updates and AJAX" />
<meta name="googlebot" content="NOODP">
<!-- Include the RGraph libraries -->
<script src="libraries/RGraph.common.core.js" ></script>
<script src="libraries/RGraph.line.js" ></script>
<script src="libraries/RGraph.common.dynamic.js" ></script>
<script src="libraries/RGraph.common.effects.js" ></script>
<script src="libraries/RGraph.common.key.js" ></script>
<script src="libraries/jquery.min.js" ></script>
<script>
$(function(){
152
$("#includedContent").load("hp_header.py");
});
</script>
<script>
$(function(){
$("#includedContent1").load("hp_footer.py");
});
</script>
<link href="master.css" rel="stylesheet" type="text/css">
<!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-
->
</head>
<body>
<div id=includedContent></div>
<div align="center">
"""
return tophtml
def jstop():
topjs = """
<script>
window.onload = function ()
{
RGraph.AJAX.getJSON('hp_indexdata.py', draw);
setTimeout(window.onload, 2000)
}
function draw (json)
{
window.__json__ = json;
"""
return topjs
def jsend():
153
endjs = """
}
</script>
"""
return endjs
def bottom():
bottomhtml = """
</div>
<div id=includedContent1></div>
</head>
</body>
</html>
"""
return bottomhtml
xxxiii. Source Code “hp_indexdata.py”
#!/usr/bin/python
from database import db_conn
db = db_conn
import cgi
import cgitb
cgitb.enable()
def dataquery(tabeldb):
cursorquery = db.cursor()
query = """SELECT TIME(waktu), status FROM {} WHERE DATE(waktu)=DATE(NOW())
ORDER BY TIME(waktu) DESC LIMIT 30""".format(tabeldb)
cursorquery.execute(query)
resultquery = cursorquery.fetchall()
waktu = []
154
status = []
for data in resultquery:
_data = resultquery
for i in range(len(_data)) :
_waktu = _data[i][0]
_waktu = str(_waktu)
waktu.append(_waktu)
_status = _data[i][1]
_status = int(_status)
status.append(_status)
return waktu, status
def dataquerybw(tabeldb):
cursorquerybw = db.cursor()
querybw = """SELECT TIME(waktu), rx, tx FROM {} WHERE
DATE(waktu)=DATE(NOW()) ORDER BY TIME(waktu) DESC LIMIT 30""".format(tabeldb)
cursorquerybw.execute(querybw)
resultquerybw = cursorquerybw.fetchall()
waktu = []
rx = []
tx = []
for data in resultquerybw:
_data = resultquerybw
for i in range(len(_data)) :
_waktu = _data[i][0]
_waktu = str(_waktu)
waktu.append(_waktu)
_rx = _data[i][1]
_rx = int(_rx)
rx.append(_rx)
_tx = _data[i][2]
_tx = int(_tx)
tx.append(_tx)
return waktu, rx, tx
def dataquerysuhu(tabeldb):
155
cursorquerybw = db.cursor()
querybw = """SELECT TIME(waktu), suhu1, suhu2, suhu3 FROM {} WHERE
DATE(waktu)=DATE(NOW()) ORDER BY TIME(waktu) DESC LIMIT 30""".format(tabeldb)
cursorquerybw.execute(querybw)
resultquerybw = cursorquerybw.fetchall()
waktu = []
suhu1 = []
suhu2 = []
suhu3 = []
suhu4 = []
for data in resultquerybw:
_data = resultquerybw
for i in range(len(_data)) :
_waktu = _data[i][0]
_waktu = str(_waktu)
waktu.append(_waktu)
_suhu1 = _data[i][1]
_suhu1 = int(_suhu1)
suhu1.append(_suhu1)
_suhu2 = _data[i][2]
_suhu2 = int(_suhu2)
suhu2.append(_suhu2)
_suhu3 = _data[i][3]
_suhu3 = int(_suhu3)
suhu3.append(_suhu3)
return waktu, suhu1, suhu2, suhu3
def listrik():
data = dataquery("listrik30")
_waktu = data[0]
_status = data[1]
return _waktu, _status
def International():
data = dataquery("International30")
_waktu = data[0]
156
_status = data[1]
return _waktu, _status
def indonesia():
data = dataquery("indonesia30")
_waktu = data[0]
_status = data[1]
return _waktu, _status
def gateway():
data = dataquery("gateway30")
_waktu = data[0]
_status = data[1]
return _waktu, _status
def google():
data = dataquery("google30")
_waktu = data[0]
_status = data[1]
return _waktu, _status
def p2pix():
data = dataquerybw("p2pix30")
_waktu = data[0]
_rx = data[1]
_tx = data[2]
_receive = "receive : %s Mbps"%(_rx[0])
_transmite = "transmite : %s Mbps"%(_tx[1])
_keylabel = [ _receive, _transmite]
return _waktu, _rx, _tx, _keylabel
def p2piix():
data = dataquerybw("p2piix30")
_waktu = data[0]
_rx = data[1]
_tx = data[2]
157
_receive = "receive : %s Mbps"%(_rx[0])
_transmite = "transmite : %s Mbps"%(_tx[1])
_keylabel = [ _receive, _transmite]
return _waktu, _rx, _tx, _keylabel
def gtw254():
data = dataquerybw("gtw25430")
_waktu = data[0]
_rx = data[1]
_tx = data[2]
_receive = "receive : %s Mbps"%(_rx[0])
_transmite = "transmite : %s Mbps"%(_tx[1])
_keylabel = [ _receive, _transmite]
return _waktu, _rx, _tx, _keylabel
def temp():
data = dataquerysuhu("temperatur30")
_waktu = data[0]
_suhu1 = data[1]
_suhu2 = data[2]
_suhu3 = data[3]
_labelsuhu1 = "Suhu 1 : %s C"%(_suhu1[0])
_labelsuhu2 = "Suhu 2 : %s C"%(_suhu2[0])
_labelsuhu3 = "Suhu 3 : %s C"%(_suhu3[0])
_labelsuhu = [_labelsuhu1, _labelsuhu2, _labelsuhu3]
return _waktu, _suhu1, _suhu2, _suhu3, _labelsuhu
def getdata():
_listrik = listrik()
waktulistrik = _listrik[0]
statuslistrik = _listrik[1]
_International = International()
waktuint = _International[0]
statusint = _International[1]
158
_indonesia = indonesia()
waktuind = _indonesia[0]
statusind = _indonesia[1]
_gateway = gateway()
waktugtw = _gateway[0]
statusgtw = _gateway[1]
_google = google()
waktugoo = _google[0]
statusgoo = _google[1]
_p2pix = p2pix()
waktup2pix = _p2pix[0]
rxp2pix = _p2pix[1]
txp2pix = _p2pix[2]
labelp2pix = _p2pix[3]
_p2piix = p2piix()
waktup2piix = _p2piix[0]
rxp2piix = _p2piix[1]
txp2piix = _p2piix[2]
labelp2piix = _p2piix[3]
_gtw254 = gtw254()
waktugtw254 = _gtw254[0]
rxgtw254 = _gtw254[1]
txgtw254 = _gtw254[2]
labelgtw254 = _gtw254[3]
_temp = temp()
waktutemp = _temp[0]
suhu1temp = _temp[1]
suhu2temp = _temp[2]
suhu3temp = _temp[3]
labelsuhu = _temp[4]
159
data="{waktulistrik:%s,statuslistrik:%s,waktuint:%s,statusint:%s,waktuind
:%s,statusind:%s,waktugtw:%s,statusgtw:%s,waktugoo:%s,statusgoo:%s,waktup2pix:%s,r
xp2pix:%s,txp2pix:%s,labelp2pix:%s,waktup2piix:%s,rxp2piix:%s,txp2piix:%s,labelp2p
iix:%s,waktugtw254:%s,rxgtw254:%s,txgtw254:%s,labelgtw254:%s,waktutemp:%s,suhu1tem
p:%s,suhu2temp:%s,suhu3temp:%s,labelsuhu:%s}"%(waktulistrik,
statuslistrik,waktuint, statusint,waktuind,statusind, waktugtw,statusgtw,waktugoo,
statusgoo,
waktup2pix,rxp2pix,txp2pix,labelp2pix,waktup2piix,rxp2piix,txp2piix,labelp2piix,wa
ktugtw254,rxgtw254,txgtw254,labelgtw254,waktutemp,suhu1temp,suhu2temp,suhu3temp,la
belsuhu)
return data
def sethtml():
print "Content-type: text/html\n\n"
data = getdata()
print data
if __name__ == "__main__":
sethtml()
xxxiv. Source Code “hp_bandwidth.py”
#!/usr/bin/python
import cgi
import cgitb
print "Content-type: text/html\n\n"
cgitb.enable()
_hanang = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
160
<title>Bandwidth</title>
<script type="text/javascript" src='/libraries/jquerypatch.js'></script>
<script type="text/javascript" src='/libraries/example.js'></script>
<script type="text/javascript" src="/libraries/jquery.min.js"></script>
<script type="text/javascript" src="/libraries/jquery.datepick.js"></script>
<script>
$(function(){
$("#includedContent1").load("hp_footer.py");
});
</script>
<script type="text/javascript">
$(function() {
$('#popupDatepicker').datepick();
$('#popupDatepicker1').datepick();
});
function showDate(date) {
alert('The date chosen is ' + date);
}
</script>
<link type="text/css" href="master.css" rel="stylesheet" type="text/css">
<link type="text/css" href="/libraries/jquery.datepick.css" rel="stylesheet">
</head>
<body>
<header><h1>Sistem Pemantauan</br> Listrik, Bandwidth,dan Temperatur</br> Gedung
Pusat Data</h1></header>
<div class="nav-wrap" align="center">
<ul class="group" id="example-two">
<li><a rel="#900" href="./">Home</a></li>
<li class="current_page_item_two"><a rel="#D40229"
href="hp_bandwidth.py">Bandwidth</a></li>
<li><a rel="#98CEAA" href="hp_listrik.py">Listrik</a></li>
<li><a rel="#1B9B93" href="hp_temperatur.py">Temperatur</a></li>
</ul>
161
</div>
<div align="center">
<form action="hp_bandwidthplot.py">
<label>Tanggal Awal : </label>
<input name="from" type="text" id="popupDatepicker">
<label>Tanggal Akhir : </label>
<input name="to" type="text" id="popupDatepicker1">
<input type="submit" value="plotting">
</form>
</div>
<div id=includedContent1></div>
</body>
</html>
"""
print _hanang
xxxv. Source Code “hp_bandwidthscript.py”
#!/usr/bin/python
"""
Author : Hanang Priambodo
Script utama fetching data ping dan bandwidth dari Mysql
"""
from database import db_conn
db = db_conn
#fetching data ping dari Mysql
def getdataping(statusdata,tabeldb,tglawal,tglakhir):
getcur = db.cursor()
getquery = """SELECT COUNT(status) FROM %s WHERE DATE(waktu) BETWEEN '%s'
AND '%s' AND status=%s"""%(tabeldb,tglawal,tglakhir,statusdata)
getcur.execute(getquery)
getres = getcur.fetchall()
162
getres = getres[0][0]
getres = int(getres)
getdetik = getres * 2
getsecond = getdetik
getmenit = 0
getjam = 0
if getdetik > 60:
getsecond = getdetik % 60
getmenit1 = getdetik /60
getmenit = getmenit1
if getmenit1 > 60:
getmenit = getmenit1 % 60
getjam = getmenit1 / 60
if statusdata == "1":
labels = "Terkoneksi"
else :
labels = "Putus"
getwaktu = "%s : %s Jam %s Menit %s
Detik"%(labels,getjam,getmenit,getsecond)
return getdetik, getwaktu
#Fetching data Bandwidth dari Mysql
def getdatabwlists(fielddb, tabeldb, tglawal, tglakhir):
bwcur0=db.cursor()
bwquery0 = """SELECT {} FROM {} WHERE DATE(waktu) BETWEEN '{}' AND
'{}'""".format(fielddb, tabeldb, tglawal, tglakhir)
bwcur0.execute(bwquery0)
bwres0 = bwcur0.fetchall()
lists = zip(*bwres0)
lists = lists[0]
bw1 = []
bw10 = []
bw20 = []
bw30 = []
bw40 = []
bw50 = []
163
bw60 = []
bw70 = []
bw80 = []
bw90 = []
bw100 = []
bw101 = []
for i in range(len(lists)):
data = lists[i]
if data < 1:
bw1.append(data)
elif data < 10:
bw10.append(data)
elif data < 20:
bw20.append(data)
elif data < 30:
bw30.append(data)
elif data < 40:
bw40.append(data)
elif data < 50:
bw50.append(data)
elif data < 60:
bw60.append(data)
elif data < 70:
bw70.append(data)
elif data < 80:
bw80.append(data)
elif data < 90:
bw90.append(data)
elif data < 100:
bw100.append(data)
else:
bw101.append(data)
data =
[len(bw1),len(bw10),len(bw20),len(bw30),len(bw40),len(bw50),len(bw60),len(bw70),le
n(bw80),len(bw90),len(bw100),len(bw101)]
164
totaldata = sum(data)
label = []
label1 = ["<1 Mbps :","1-9 Mbps :","10-19 Mbps :","20-29 Mbps :", "30-39
Mbps :", "40-49 Mbps :", "50-59 Mbps :", "60-69 Mbps :","70-79 Mbps :","80-89 Mbps
:","90-99 Mbps :",">100 Mbps :"]
for j in range(len(data)):
nilai = data[j] * 100.0 / totaldata
nilai = round(nilai,2)
lab = label1[j]
stick = """{}{}%""".format(lab,nilai)
label.append(stick)
data = "data%s%s:%s"%(tabeldb,fielddb,data)
label = "label%s%s:%s"%(tabeldb,fielddb,label)
return data,label
xxxvi. Source Code “hp_bandwidthweb.py”
#!/usr/bin/python
def tophtml():
htmltop = """
<!DOCTYPE html >
<html>
<title>Author By : Hanang Priambodo</title>
<head>
<link rel="stylesheet" href="master.css" type="text/css"
media="screen" />
<script src="/libraries/RGraph.common.core.js" ></script>
<script src="/libraries/RGraph.common.tooltips.js" ></script>
<script src="/libraries/RGraph.common.dynamic.js" ></script>
<script src="/libraries/RGraph.common.effects.js" ></script>
<script src="libraries/RGraph.drawing.rect.js" ></script>
<script src="/libraries/RGraph.common.key.js" ></script>
<script type="text/javascript" src="/libraries/jquery.min.js"></script> <script src="/libraries/RGraph.pie.js" ></script>
165
<script> $(function(){ $("#includedContent").load("hp_header.py"); }); </script> <script> $(function(){ $("#includedContent1").load("hp_footer.py"); }); </script> <link href="master.css" rel="stylesheet" type="text/css"> <title>Bandwidth</title> <meta name="description" content="Bandwidth" /> </head> <body> """ return htmltop def divhtml(): htmldiv = """ <div id="includedContent"></div> <div align="center"> <h1>Status Koneksi Internet</h1> """ return htmldiv def jsfirst(): plotfirst = """ <script> function drawPie (json) { """ return plotfirst def jsend(): plotend = """ } RGraph.AJAX.getJSON('bandwidthtes.json', drawPie); </script> """ return plotend def divbottom(): bottomdiv = """ <div id="includedContent1"></div> </div> """ return bottomdiv def bottomhtml(): htmlbottom = """ </body> </html> """ return htmlbottom
xxxvii. Source Code “hp_bandwidthplot.py”
#!/usr/bin/python
from hp_bandwidthscript import getdataping,getdatabwlists
166
from hp_bandwidthweb import tophtml, divhtml, jsfirst, jsend, divbottom, bottomhtml
from hp_plotping import plotping
from hp_plotbandwidth import plotbandwidthrx, plotbandwidthtx
from hp_getcanvas import canvasplot
import cgi
import cgitb
def tanggal():
cgitb.enable()
form=cgi.FieldStorage()
#def tanggalawal():
ifrom = form["from"].value
tgl1 = ifrom.split("/")
baris1 = "%s-%s-%s"%(tgl1[2],tgl1[0],tgl1[1])
#def tanggalakhir():
ito = form["to"].value
tgl2 = ito.split("/")
baris2 = "%s-%s-%s"%(tgl2[2],tgl2[0],tgl2[1])
tglawal = baris1
tglakhir = baris2
return tglawal,tglakhir
def tanggalweb():
awal = tanggal()[0]
akhir = tanggal()[1]
web = """<h3>Tanggal %s sampai %s</h3>"""%(awal,akhir)
return web
def getdata(tabel):
tanggalawal = tanggal()[0]
tanggalakhir = tanggal()[1]
datamati = getdataping('0',tabel,tanggalawal, tanggalakhir)
datahidup = getdataping('1',tabel,tanggalawal, tanggalakhir)
167
detikmati = datamati[0]
labelmati = datamati[1]
detikhidup = datahidup[0]
labelhidup = datahidup[1]
_data = "%sdata:[%s,%s]"%(tabel,detikhidup,detikmati)
_label = "%slabel:['%s','%s']"%(tabel,labelhidup,labelmati)
return _data, _label
def dataInternational():
tabels = "International"
data = getdata(tabels)
return data
def dataindonesia():
tabels = "indonesia"
data = getdata(tabels)
return data
def datagateway():
tabels = "gateway"
data = getdata(tabels)
return data
def datagoogle():
tabels = "google"
data = getdata(tabels)
return data
def getdatabw(tabel):
tanggalawal = tanggal()[0]
tanggalakhir = tanggal()[1]
rxbw = getdatabwlists('rx',tabel,tanggalawal, tanggalakhir)
datarx = rxbw[0]
labelrx = rxbw[1]
txbw = getdatabwlists('tx',tabel,tanggalawal, tanggalakhir)
168
datatx = txbw[0]
labeltx = txbw[1]
return datarx, labelrx, datatx, labeltx
def datap2pix():
tabels = "p2pix"
databw = getdatabw(tabels)
return databw
def datap2piix():
tabels = "p2piix"
databw = getdatabw(tabels)
return databw
def datagtw254():
tabels = "gtw254"
databw = getdatabw(tabels)
return databw
def createjson():
dataint=dataInternational()[0]
labelint=dataInternational()[1]
dataind = dataindonesia()[0]
labelind = dataindonesia()[1]
datagtw = datagateway()[0]
labelgtw = datagateway()[1]
datagoo = datagoogle()[0]
labelgoo = datagoogle()[1]
dataixrx = datap2pix()[0]
labelixrx = datap2pix()[1]
dataixtx = datap2pix()[2]
169
labelixtx = datap2pix()[3]
dataiixrx = datap2piix()[0]
labeliixrx = datap2piix()[1]
dataiixtx = datap2piix()[2]
labeliixtx = datap2piix()[3]
datagtw254rx = datagtw254()[0]
labelgtw254rx = datagtw254()[1]
datagtw254tx = datagtw254()[2]
labelgtw254tx = datagtw254()[3]
datajson =
"""{%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s}"""%(dataint,label
int,dataind,labelind,datagtw,labelgtw,datagoo,labelgoo,dataixrx,labelixrx,dataixtx
,labelixtx,dataiixrx,labeliixrx,dataiixtx,labeliixtx,datagtw254rx,labelgtw254rx,da
tagtw254tx,labelgtw254tx)
return datajson
def intgetplot():
title = "Status Ping P2P-International"
canvas = "cvs"
setcanvas = canvasplot(canvas)
data = "json.Internationaldata"
label = "json.Internationallabel"
getplot = plotping(title,canvas,data,label)
return setcanvas,getplot
def indgetplot():
title = "Status Ping P2P-Indonesia"
canvas = "cvs1"
setcanvas = canvasplot(canvas)
data = "json.indonesiadata"
label = "json.indonesialabel"
getplot = plotping(title,canvas,data,label)
return setcanvas, getplot
170
def gtwgetplot():
title = "Status Ping BGP Server"
canvas = "cvs2"
setcanvas = canvasplot(canvas)
data = "json.gatewaydata"
label = "json.gatewaylabel"
getplot = plotping(title,canvas,data,label)
return setcanvas, getplot
def googetplot():
title = "Status Ping Google"
canvas = "cvs3"
setcanvas = canvasplot(canvas)
data = "json.googledata"
label = "json.googlelabel"
getplot = plotping(title,canvas,data,label)
return setcanvas, getplot
def p2pixrxplot():
title = "Status Penggunaan Bandwidth International"
canvas = "cvs4"
setcanvas = canvasplot(canvas)
rx = "json.datap2pixrx"
label = "json.labelp2pixrx"
getplot = plotbandwidthrx(title,canvas,rx,label)
return setcanvas, getplot
def p2pixtxplot():
title = "Status Penggunaan Bandwidth International"
canvas = "cvs4"
tx = "json.datap2pixtx"
label = "json.labelp2pixtx"
getplot = plotbandwidthtx(canvas,tx,label)
return getplot
171
def p2piixrxplot():
title = "Status Penggunaan Bandwidth Indonesia"
canvas = "cvs5"
setcanvas = canvasplot(canvas)
rx = "json.datap2piixrx"
label = "json.labelp2piixrx"
getplot = plotbandwidthrx(title,canvas,rx,label)
return setcanvas, getplot
def p2piixtxplot():
title = "Status Penggunaan Bandwidth International"
canvas = "cvs5"
tx = "json.datap2piixtx"
label = "json.labelp2piixtx"
getplot = plotbandwidthtx(canvas,tx,label)
return getplot
def gtw254rxplot():
title = "Status Penggunaan Bandwidth BGP Server"
canvas = "cvs6"
setcanvas = canvasplot(canvas)
rx = "json.datagtw254rx"
label = "json.labelgtw254rx"
getplot = plotbandwidthrx(title,canvas,rx,label)
return setcanvas, getplot
def gtw254txplot():
title = "Status Penggunaan Bandwidth BGP Server"
canvas = "cvs6"
tx = "json.datagtw254tx"
label = "json.labelgtw254tx"
getplot = plotbandwidthtx(canvas,tx,label)
return getplot
def mainprog():
print "Content-type: text/html\n\n"
172
tanggal()
dataInternational()
dataindonesia()
datagateway()
datagoogle()
_json = createjson()
files = open('bandwidthtes.json','w')
files.write(_json)
files.close()
print tophtml()
print divhtml()
print tanggalweb()
print intgetplot()[0]
print indgetplot()[0]
print gtwgetplot()[0]
print googetplot()[0]
print p2pixrxplot()[0]
print p2piixrxplot()[0]
print gtw254rxplot()[0]
print jsfirst()
print intgetplot()[1]
print indgetplot()[1]
print gtwgetplot()[1]
print googetplot()[1]
print p2pixrxplot()[1]
print p2pixtxplot()
print p2piixrxplot()[1]
print p2piixtxplot()
print gtw254rxplot()[1]
print gtw254txplot()
print jsend()
print divbottom()
print bottomhtml()
if __name__ == "__main__" :
mainprog()
173
xxxviii. Source Code “hp_plotbandwidth.py”
#!/usr/bin/python
def plotbandwidthrx(gettitle,getcanvas, dataplot, labelplot):
getplotrx = """
var pie = new RGraph.Pie('{}', [])
.Set('title', '{}')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Draw()
var pie = new RGraph.Pie('{}', {})
.Set('title', 'Receive')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Set('strokestyle', '#e8e8e8')
.Set('radius',70)
.Set('exploded',10)
.Set('linewidth', 5)
.Set('tooltips', {})
.Set('linewidth', 3)
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 20)
.Set('gutter.top', 25)
.Set('gutter.right', 190)
.Set('key', {})
.Set('key.interactive',true)
.Set('key.position.x',1)
.Set('key.position.y',140)
.Draw()
""".format( getcanvas, gettitle, getcanvas, dataplot, labelplot, labelplot)
174
return getplotrx
def plotbandwidthtx(getcanvastx, dataplottx, labelplottx):
getplottx = """
var pie = new RGraph.Pie('{}', {})
.Set('title', 'Transmite')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Set('strokestyle', '#e8e8e8')
.Set('radius',70)
.Set('exploded',10)
.Set('linewidth', 5)
.Set('tooltips', {})
.Set('linewidth', 3)
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 20)
.Set('gutter.top', 25)
.Set('gutter.left', 190)
.Set('key', {})
.Set('key.interactive',true)
.Set('key.position.x',350)
.Set('key.position.y',140)
.Draw()
""".format( getcanvastx, dataplottx, labelplottx, labelplottx)
return getplottx
xxxix. Source Code “hp_plotping.py”
#!/usr/bin/python
def plotping(gettitle,getcanvas, dataplot, labelplot):
getplot = """
var pie = new RGraph.Pie('{}', {})
175
.Set('title', '{}')
.Set('key', {})
.Set('key.position','gutter')
.Set('key.position.y','75')
.Set('tooltips', {})
.Set('linewidth', 3)
.Set('exploded', [15,])
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('colors', ['#66FF00','red'])
.Set('gutter.top', 75)
.Set('shadow.blur', 20)
.Set('radius', 90)
.Draw()
//RGraph.Effects.Pie.RoundRobin(pie)
""".format(getcanvas, dataplot,gettitle, labelplot,labelplot)
return getplot
xl. Source Code “hp_plotlistrik.py”
#!/usr/bin/python
def plotlistrik():
jsplot = """
var pie = new RGraph.Pie('cvs', json.listrikdata)
.Set('title', 'Status Listrik')
.Set('title.y', 30)
.Set('tooltips', json.labeljam)
.Set('linewidth', 3)
.Set('exploded', [15,])
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('colors', ['#66FF00','red'])
.Set('gutter.top', 75)
176
.Set('shadow.blur', 20)
.Set('key', json.labeljam)
.Set('key.position','gutter')
.Set('key.position.y','75')
RGraph.Effects.Pie.RoundRobin(pie)
"""
return jsplot
xli. Source Code “hp_plotrealbandwidth.py”
#!/usr/bin/python
"""
Script untuk Plotting bandwidith di index.py
"""
def jsplotbandwidth(getcanvas1, getcanvas2,getdata1,getdata2, gettitle, getkey,
getlabel):
plotjs = """
RGraph.Reset(document.getElementById('{}'));
var line1 = new RGraph.Line('{}', {}, {})
.Set('linewidth', [3, 3])
.Set('title', '{}')
.Set('key', {})
.Set('key.background', 'rgba(255,255,255,0.8)')
.Set('key.rounded', true)
.Set('labels', {})
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 15)
.Set('shadow.color', ['gray','green'])
.Set('gutter.left', 75)
.Set('gutter.bottom', 75)
.Set('background.grid.autofit.numvlines', 30)
.Draw();
177
""".format(getcanvas1, getcanvas2,getdata1,getdata2, gettitle,getkey,
getlabel)
return plotjs
xlii. Source Code “hp_plotreallistrik.py”
#!/usr/bin/python
"""
Script Plotting listrik di index.py
"""
def jsplotlistrik(getcanvas1,getcanvas2,getdata,gettitle,getlabel):
plotjs = """
RGraph.Reset(document.getElementById('{}'));
var line = new RGraph.Line('{}', {})
.Set('title', '{}')
.Set('numxticks', 30)
.Set('numyticks', 4)
.Set('ymax', 2)
.Set('ymin', -1)
.Set('ylabels.specific', ['','UP','DOWN',''])
.Set('linewidth', [3, 3])
.Set('labels',{})
.Set('colors',['green'])
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 15)
.Set('gutter.left', 75)
.Set('gutter.bottom', 75)
.Set('background.grid.autofit.numvlines', 30)
.Draw();
""".format(getcanvas1,getcanvas2,getdata,gettitle,getlabel)
return plotjs
178
xliii. Source Code “hp_plotrealping.py”
#!/usr/bin/python
"""
Script Plotting ping di index.py
"""
def jsplotping(getcanvas1,getcanvas2,getdata,gettitle,getlabel):
plotjs = """
RGraph.Reset(document.getElementById('{}'));
var line = new RGraph.Line('{}', {})
.Set('title', '{}')
.Set('numxticks', 30)
.Set('numyticks', 4)
.Set('ymax', 2)
.Set('ymin', -1)
.Set('ylabels.specific', ['','UP','DOWN',''])
.Set('linewidth', [3, 3])
.Set('labels',{})
.Set('colors',['green'])
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 15)
.Set('gutter.left', 75)
.Set('gutter.bottom', 75)
.Set('background.grid.autofit.numvlines', 30)
.Draw();
""".format(getcanvas1,getcanvas2,getdata,gettitle,getlabel)
return plotjs
xliv. Source Code “hp_plotrealsuhu.py”
#!/usr/bin/python
179
"""
Script untuk Plotting temperatur sdi index.py
"""
def jsplottemperatur(getcanvas1, getcanvas2,getdata1,getdata2,getdata3,
gettitle,getkey, getlabel):
plotjs = """
RGraph.Reset(document.getElementById('{}'));
var line1 = new RGraph.Line('{}', {}, {},{})
.Set('linewidth', [3, 3])
.Set('title', '{}')
.Set('key', {})
.Set('key.background', 'rgba(255,255,255,0.8)')
.Set('key.rounded', true)
.Set('labels', {})
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 15)
.Set('shadow.color', ['gray','green'])
.Set('gutter.left', 75)
.Set('gutter.bottom', 75)
.Set('background.grid.autofit.numvlines', 30)
.Draw();
""".format(getcanvas1, getcanvas2,getdata1,getdata2,getdata3, gettitle,
getkey, getlabel)
return plotjs
xlv. Source Code “hp_plottemperatur.py”
#!/usr/bin/python
def plottemp1(getcanvas1, dataplot1, labelplot1):
getplot1 = """
var pie = new RGraph.Pie('{}', [])
180
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Draw()
var pie = new RGraph.Pie('{}', {})
.Set('title', 'Temperatur 1')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Set('strokestyle', '#e8e8e8')
.Set('colors',['yellow','green','red'])
.Set('radius',70)
.Set('exploded',10)
.Set('linewidth', 5)
.Set('tooltips', {})
.Set('linewidth', 3)
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 20)
.Set('gutter.top', 25)
.Set('gutter.right', 380)
.Set('key', {})
.Set('key.interactive',true)
.Set('key.position.x',1)
.Set('key.position.y',270)
.Draw()
""".format( getcanvas1, getcanvas1, dataplot1, labelplot1, labelplot1)
return getplot1
def plottemp2(getcanvas2, dataplot2, labelplot2):
getplot2 = """
var pie = new RGraph.Pie('{}', {})
.Set('title', 'Temperatur 2')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
181
.Set('title.size', 12)
.Set('strokestyle', '#e8e8e8')
.Set('radius',70)
.Set('colors',['yellow','green','red'])
.Set('exploded',10)
.Set('linewidth', 5)
.Set('tooltips', {})
.Set('linewidth', 3)
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 20)
.Set('gutter.top', 25)
.Set('gutter.left', 100)
.Set('gutter.right', 100)
.Set('key', {})
.Set('key.interactive',true)
.Set('key.position.x',200)
.Set('key.position.y',270)
.Draw()
""".format( getcanvas2, dataplot2, labelplot2, labelplot2)
return getplot2
def plottemp3(getcanvas3, dataplot3, labelplot3):
getplot3 = """
var pie = new RGraph.Pie('{}', {})
.Set('title', 'Temperatur 3')
.Set('title.color', '#614427')
.Set('title.font', 'Georgia')
.Set('title.size', 12)
.Set('strokestyle', '#e8e8e8')
.Set('radius',70)
.Set('colors',['yellow','green','red'])
.Set('exploded',10)
.Set('linewidth', 5)
.Set('tooltips', {})
182
.Set('linewidth', 3)
.Set('shadow', true)
.Set('shadow.offsetx', 0)
.Set('shadow.offsety', 0)
.Set('shadow.blur', 20)
.Set('gutter.top', 25)
.Set('gutter.left', 380)
.Set('key', {})
.Set('key.interactive',true)
.Set('key.position.x',410)
.Set('key.position.y',270)
.Draw()
""".format( getcanvas3, dataplot3, labelplot3, labelplot3)
return getplot3
xlvi. Source Code “hp_listrik.py”
#!/usr/bin/python
import cgi
import cgitb
print "Content-type: text/html\n\n"
cgitb.enable()
form=cgi.FieldStorage()
_hanang = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Datepicker</title>
<link type="text/css" href="/libraries/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="/libraries/jquery.min.js"></script>
<script type="text/javascript" src="/libraries/jquery.datepick.js"></script>
183
<script>
$(function(){
$("#includedContent").load("hp_header.py");
});
</script>
<script>
$(function(){
$("#includedContent1").load("hp_footer.py");
});
</script>
<link href="master.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
$(function() {
$('#popupDatepicker').datepick();
$('#popupDatepicker1').datepick();
});
function showDate(date) {
alert('The date chosen is ' + date);
}
</script>
</head>
<body>
<header><h1>Sistem Pemantauan</br> Listrik, Bandwidth,dan Temperatur</br> Gedung
Pusat Data</h1></header>
<div class="nav-wrap" align="center">
<ul class="group" id="example-two">
<li><a rel="#900" href="./">Home</a></li>
<li><a rel="#D40229" href="hp_bandwidth.py">Bandwidth</a></li>
<li class="current_page_item_two"><a rel="#98CEAA"
href="hp_listrik.py">Listrik</a></li>
<li><a rel="#1B9B93" href="hp_temperatur.py">Temperatur</a></li>
</ul>
</div>
184
<div align="center">
<form action="hp_listrikplot.py">
<label>Tanggal Awal : </label>
<input name="from" type="text" id="popupDatepicker">
<label>Tanggal Akhir : </label>
<input name="to" type="text" id="popupDatepicker1">
<input type="submit" value="plotting">
</form>
</div>
<div id=includedContent1></div>
</body>
</html>
"""
print _hanang
xlvii. Source Code “hp_listrikplot.py”
#!/usr/bin/python
import cgi
import cgitb
import re
from database import db_conn
from hp_plotlistrik import plotlistrik
from random import randrange
db= db_conn
print "Content-type: text/html\n\n"
cgitb.enable()
form=cgi.FieldStorage()
#def tanggalawal():
ifrom = form["from"].value
tgl1 = ifrom.split("/")
baris1 = "%s-%s-%s"%(tgl1[2],tgl1[0],tgl1[1])
#def tanggalakhir():
185
ito = form["to"].value
tgl2 = ito.split("/")
baris2 = "%s-%s-%s"%(tgl2[2],tgl2[0],tgl2[1])
#def randomnum():
ranum = randrange(1000,9999,4)
tglawal = str(baris1)
tglakhir = str(baris2)
cur0 = db.cursor()
cur1 = db.cursor()
query0 = """SELECT COUNT(status) FROM listrik WHERE DATE(waktu) BETWEEN DATE('%s')
AND DATE('%s') AND status=0"""%(tglawal,tglakhir)
query1 = """SELECT COUNT(status) FROM listrik WHERE DATE(waktu) BETWEEN DATE('%s')
AND DATE('%s') AND status=1"""%(tglawal,tglakhir)
cur0.execute(query0)
cur1.execute(query1)
res0 = cur0.fetchall()
res1 = cur1.fetchall()
res0 = res0[0][0]
res1 = res1[0][0]
res0 = int(res0)
res1 = int(res1)
detikhidup = res1 * 2
secondhidup = detikhidup
menithidup = 0
jamhidup = 0
if detikhidup > 60:
secondhidup = detikhidup % 60
menithidup1 = detikhidup /60
menithidup = menithidup1
186
if menithidup1 > 60:
menithidup = menithidup1 % 60
jamhidup = menithidup1 / 60
waktuhidup = "%s Jam %s Menit %s Detik"%(jamhidup,menithidup,secondhidup)
detikmati = res0 * 2
secondmati = detikmati
menitmati = 0
jammati = 0
if detikmati > 60:
secondmati = detikmati % 60
menitmati1 = detikmati /60
menitmati = menitmati1
if menitmati1 > 60:
menitmati = menitmati1 % 60
jammati = menitmati1 / 60
waktumati = "%s Jam %s Menit %s Detik"%(jammati,menitmati,secondmati)
_json = "{listrikdata:[%s,%s],listriklabel:['hidup','mati'],labeljam:['Terkoneksi
: %s','Putus : %s']}" % (res1,res0,waktuhidup,waktumati)
files = open('listrikstat.json','w')
files.write(_json)
files.close()
_tophtml = """
<!DOCTYPE html >
<html>
<title>Author By : Hanang Priambodo</title>
<head>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<script src="/libraries/RGraph.common.core.js" ></script>
<script src="/libraries/RGraph.common.tooltips.js" ></script>
<script src="/libraries/RGraph.common.dynamic.js" ></script>
<script src="/libraries/RGraph.common.effects.js" ></script>
<script src="/libraries/RGraph.common.key.js" ></script>
187
<script type="text/javascript" src="/libraries/jquery.min.js"></script>
<script src="/libraries/RGraph.pie.js" ></script>
<script>
$(function(){ $("#includedContent").load("hp_header.py"); }); </script> <script> $(function(){ $("#includedContent1").load("hp_footer.py"); }); </script> <link href="master.css" rel="stylesheet" type="text/css"> <!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]--> <title>Listrik</title> <meta name="description" content="Listrik" /> </head> <body> """ _hanang = """ <div id="includedContent"></div> <div align="center"> <h1>Status kondisi Listrik</h1> """ _web = """<h3>Tanggal %s sampai %s</h3>"""%(tglawal,tglakhir) _lanjut = """ <canvas id="cvs" width="480" height="300" !style="border:1px solid #ccc">[No canvas support]</canvas> <script> function drawPie (json) { """ _jsend = """ } RGraph.AJAX.getJSON('listrikstat.json', drawPie); </script> <div id="includedContent1"></div> </div> </body> </html> """
_bottomhtml = """
</body>
</html>
"""
print _tophtml
print _hanang
print _web
print _lanjut
188
print plotlistrik()
print _jsend
print _bottomhtml
xlviii. Source Code “hp_temperatur.py”
#!/usr/bin/python
import cgi
import cgitb
print "Content-type: text/html\n\n"
cgitb.enable()
_hanang = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Bandwidth</title>
<script type="text/javascript" src='/libraries/jquerypatch.js'></script>
<script type="text/javascript" src='/libraries/example.js'></script>
<script type="text/javascript" src="/libraries/jquery.min.js"></script>
<script type="text/javascript" src="/libraries/jquery.datepick.js"></script>
<script>
$(function(){
$("#includedContent1").load("hp_footer.py");
});
</script>
<script type="text/javascript">
$(function() {
$('#popupDatepicker').datepick();
$('#popupDatepicker1').datepick();
});
function showDate(date) {
alert('The date chosen is ' + date);
}
189
</script>
<link type="text/css" href="master.css" rel="stylesheet" type="text/css">
<link type="text/css" href="/libraries/jquery.datepick.css" rel="stylesheet">
</head>
<body>
<header><h1>Sistem Pemantauan</br> Listrik, Bandwidth,dan Temperatur</br> Gedung
Pusat Data</h1></header>
<div class="nav-wrap" align="center">
<ul class="group" id="example-two">
<li><a rel="#900" href="./">Home</a></li>
<li><a rel="#D40229" href="hp_bandwidth.py">Bandwidth</a></li>
<li><a rel="#98CEAA" href="hp_listrik.py">Listrik</a></li>
<li class="current_page_item_two"><a rel="#1B9B93"
href="hp_temperatur.py">Temperatur</a></li>
</ul>
</div>
<div align="center">
<form action="hp_temperaturplot.py">
<label>Tanggal Awal : </label>
<input name="from" type="text" id="popupDatepicker">
<label>Tanggal Akhir : </label>
<input name="to" type="text" id="popupDatepicker1">
<input type="submit" value="plotting">
</form>
</div>
<div id=includedContent1></div>
</body>
</html>
"""
print _hanang
190
xlix. Source Code “hp_temperaturscript.py”
#!/usr/bin/python
"""
Author : Hanang Priambodo
Script utama fetching data ping dan bandwidth dari Mysql
"""
from database import db_conn
db = db_conn
#Fetching data Bandwidth dari Mysql
def getdatatemperatur(fielddb, tabeldb, tglawal, tglakhir):
tempcur0=db.cursor()
tempquery0 = """SELECT {} FROM {} WHERE DATE(waktu) BETWEEN '{}' AND
'{}'""".format(fielddb, tabeldb, tglawal, tglakhir)
tempcur0.execute(tempquery0)
tempres0 = tempcur0.fetchall()
lists = zip(*tempres0)
lists = lists[0]
tempwarn18 = []
tempsafe = []
tempwarn27 = []
for i in range(len(lists)):
data = lists[i]
if data < 18:
tempwarn18.append(data)
elif data > 27:
tempwarn27.append(data)
else:
tempsafe.append(data)
data = [len(tempwarn18),len(tempsafe),len(tempwarn27)]
totaldata = sum(data)
label = []
191
label1 = ["< 18 C :","Safe :",">27 :"]
for j in range(len(data)):
nilai = data[j] * 100.0 / totaldata
nilai = round(nilai,2)
lab = label1[j]
stick = """{}{}%""".format(lab,nilai)
label.append(stick)
data = "data%s%s:%s"%(tabeldb,fielddb,data)
label = "label%s%s:%s"%(tabeldb,fielddb,label)
return data,label
l. Source Code “hp_temperaturweb.py”
#!/usr/bin/python
def tophtml():
htmltop = """
<!DOCTYPE html >
<html>
<title>Author By : Hanang Priambodo</title>
<head>
<link rel="stylesheet" href="master.css" type="text/css"
media="screen" />
<script src="/libraries/RGraph.common.core.js" ></script>
<script src="/libraries/RGraph.common.tooltips.js" ></script>
<script src="/libraries/RGraph.common.dynamic.js" ></script>
<script src="/libraries/RGraph.common.effects.js" ></script>
<script src="libraries/RGraph.drawing.rect.js" ></script>
<script src="/libraries/RGraph.common.key.js" ></script>
<script type="text/javascript"
src="/libraries/jquery.min.js"></script>
<script src="/libraries/RGraph.pie.js" ></script>
<script> $(function(){ $("#includedContent").load("hp_header.py"); }); </script>
192
<script> $(function(){ $("#includedContent1").load("hp_footer.py"); }); </script> <link href="master.css" rel="stylesheet" type="text/css"> <title>Bandwidth</title> <meta name="description" content="Bandwidth" /> </head> <body> """ return htmltop
def divhtml(): htmldiv = """ <div id="includedContent"></div> <div align="center"> <h1>Status kondisi Temperatur Ruang Pusat Data</h1> """ return htmldiv
def jsfirst(): plotfirst = """ <script> function drawPie (json) { """ return plotfirst def jsend(): plotend = """ } RGraph.AJAX.getJSON('temperatur.json', drawPie); </script> """ return plotend def divbottom(): bottomdiv = """ <div id="includedContent1"></div> </div> """ return bottomdiv def bottomhtml(): htmlbottom = """ </body> </html> """ return htmlbottom
li. Source Code “hp_temperaturplot.py”
#!/usr/bin/python
from hp_temperaturscript import getdatatemperatur
from hp_temperaturweb import tophtml, divhtml, jsfirst, jsend, divbottom, bottomhtml
from hp_plotping import plotping
from hp_plottemperatur import plottemp1, plottemp2, plottemp3
193
from hp_getcanvas import canvasplot
import cgi
import cgitb
def tanggal():
cgitb.enable()
form=cgi.FieldStorage()
#def tanggalawal():
ifrom = form["from"].value
tgl1 = ifrom.split("/")
baris1 = "%s-%s-%s"%(tgl1[2],tgl1[0],tgl1[1])
#def tanggalakhir():
ito = form["to"].value
tgl2 = ito.split("/")
baris2 = "%s-%s-%s"%(tgl2[2],tgl2[0],tgl2[1])
tglawal = baris1
tglakhir = baris2
return tglawal,tglakhir
def getdatatemp(tabel):
tanggalawal = tanggal()[0]
tanggalakhir = tanggal()[1]
temp1 = getdatatemperatur('suhu1',tabel,tanggalawal, tanggalakhir)
datatemp1 = temp1[0]
labeltemp1 = temp1[1]
temp2 = getdatatemperatur('suhu2',tabel,tanggalawal, tanggalakhir)
datatemp2 = temp2[0]
labeltemp2 = temp2[1]
temp3 = getdatatemperatur('suhu3',tabel,tanggalawal, tanggalakhir)
datatemp3 = temp3[0]
labeltemp3 = temp3[1]
return datatemp1, labeltemp1, datatemp2, labeltemp2, datatemp3, labeltemp3
194
def datatemp():
tabels = "temperatur"
datatemp = getdatatemp(tabels)
return datatemp
def createjson():
datatemp1 = datatemp()[0]
labeltemp1 = datatemp()[1]
datatemp2 = datatemp()[2]
labeltemp2 = datatemp()[3]
datatemp3 = datatemp()[4]
labeltemp3 = datatemp()[5]
datajson =
"""{%s,%s,%s,%s,%s,%s}"""%(datatemp1,labeltemp1,datatemp2,labeltemp2,datatemp3,lab
eltemp3)
files = open('temperatur.json','w')
files.write(datajson)
files.close()
def temp1plot():
canvas = "cvs1"
setcanvas = canvasplot(canvas)
temp1 = "json.datatemperatursuhu1"
label = "json.labeltemperatursuhu1"
getplot = plottemp1(canvas,temp1,label)
return setcanvas, getplot
def temp2plot():
canvas = "cvs1"
temp2 = "json.datatemperatursuhu2"
label = "json.labeltemperatursuhu2"
getplot = plottemp2(canvas,temp2,label)
return getplot
195
def temp3plot():
canvas = "cvs1"
temp3 = "json.datatemperatursuhu3"
label = "json.labeltemperatursuhu3"
getplot = plottemp3(canvas,temp3,label)
return getplot
def tanggalweb():
awal = tanggal()[0]
akhir = tanggal()[1]
web = """<h3>Tanggal %s sampai %s</h3>"""%(awal,akhir)
return web
def mainprog():
print "Content-type: text/html\n\n"
tanggal()
datatemp()
createjson()
print tophtml()
print divhtml()
print tanggalweb()
print temp1plot()[0]
print jsfirst()
print temp1plot()[1]
print temp2plot()
print temp3plot()
print jsend()
print divbottom()
print bottomhtml()
if __name__ == "__main__" :
mainprog()
lii. Source Code “hp_getcanvas.py”
#!/usr/bin/python
196
def canvastop(getcanvas):
topcanvas = """
<canvas id="{}" width="600" height="250">[No canvas support]</canvas>
""".format(getcanvas)
return topcanvas
def canvasplot(getcanvas):
topcanvas = """
<canvas id="{}" width="520" height="350" style="border-bottom:1px solid
#ccc">[No canvas support]</canvas>
""".format(getcanvas)
return topcanvas
def canvastemperatur(getcanvas):
topcanvas = """
<canvas id="{}" width="850" height="350" style="border-bottom:1px solid
#ccc">[No canvas support]</canvas>
""".format(getcanvas)
return topcanvas
liii. Source Code “hp_header.py”
#!/usr/bin/python
import cgi
import cgitb
print "Content-type: text/html\n\n"
cgitb.enable()
form=cgi.FieldStorage()
_hanang = """
<!DOCTYPE html>
<html>
<head>
<title>Hanang Priambodo</title>
197
<script src='/libraries/jquerypatch.js'></script>
<script src='/libraries/example.js'></script>
<script src='/libraries/jquery.min.15.js'></script>
<link href="master.css" rel="stylesheet" type="text/css">
</head>
<body>
<header><h1>Sistem Pemantauan<br> Listrik, Bandwidth,dan Temperatur<br>
Gedung Pusat Data</h1></header>
<div class="nav-wrap" align="center">
<ul class="group" id="example-two">
<li class="current_page_item_two"><a rel="#900"
href="./">Home</a></li>
<li><a rel="#D40229" href="hp_bandwidth.py">Bandwidth</a></li>
<li><a rel="#98CEAA" href="hp_listrik.py">Listrik</a></li>
<li><a rel="#1B9B93" href="hp_temperatur.py">Temperatur</a></li>
</ul>
</div>
</body>
</html>
"""
print _hanang
liv. Source Code “hp_footer.py
#!/usr/bin/python
import cgi
import cgitb
print "Content-type: text/html\n\n"
cgitb.enable()
form=cgi.FieldStorage()
198
_hanang = """
<!DOCTYPE html>
<html>
<head>
<title>Hanang Priambodo</title>
<link href="master.css" rel="stylesheet" type="text/css">
</head>
<body>
<div align="center" id="footer">
<label>Created By : Hanang Priambodo</label>
</div>
</body>
</html>
"""
print _hanang
199
LAMPIRAN B
Pada lampiran ini berisikan foto – foto hasil dari tugas akhir yang telah dilakukan.
Foto – foto tersebut diantaranya sebagai berikut :
lv. Ruang Pusat Data Universitas Lampung
200
lvi. Perangkat Raspberry Pi
lvii. Hasil Perancangan Perangkat Keras
201
lviii. Peletakan Sensor Temperatur Dan Modem GSM
Rak IBM Storage
202
Rak Blade Server
Rak BGP Server
203
LAMPIRAN C
lix. Laporan Harian
Laporan harian diambil pada tanggal 21 dan 22 Mei . Laporan dapat dilihat pada
lembar selanjutnya
204
205
206
207
208
209
210
lx. Laporan Mingguan
Laporan mingguan dapat dilihat pada lembar selanjutnya.
211
212
213
214
lxi. Laporan Bulanan
Laporan Bulanan diambil pada Bulan April, Mei, dan Juni . Laporan dapat dilihat
pada lembar selanjutnya.
215
216
217
218
219
220
221
222
223
224
LAMPIRAN D
Sampel data harian Bandwdith International dan Indonesia yang diambil 3 hari
secara acak pada bulan April, Mei, Juni .
225
lxii. Sampel Data Penggunaan Bandwidth International Bulan April
Waktu Penggunaan Bandwidth International Per
Hari (9 April 2014)
Waktu Penggunaan Bandwidth International Per
Hari (17 April 2014)
Waktu Penggunaan Bandwidth International Per
Hari (30 April 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 24 91 8,81 62,27 0 27 94 7,57 43,62 0 25 84 11,76 48,98
1 29 77 6,84 40,92 1 23 89 7,91 49,01 1 29 73 13,43 40,81
2 26 59 6,41 18,71 2 18 74 6,6 41,04 2 24 62 9,43 27,01
3 19 69 8,57 10,37 3 23 61 7,05 32,07 3 24 44 9,65 16,4
4 19 64 5,6 9,98 4 27 68 6,69 27,96 4 33 54 9,53 17,33
5 19 48 4,99 11,73 5 23 85 6,95 29,35 5 28 49 10,54 10,64
6 43 80 5,15 13,1 6 22 62 6,88 23,99 6 34 36 12,62 12,69
7 25 60 6,38 18,85 7 21 86 7 34,46 7 44 99 17,67 44,69
8 25 86 10,8 24,78 8 37 101 11,53 86,59 8 49 101 19,66 86,75
9 24 54 10,37 16,11 9 28 102 14,39 99,72 9 33 102 16,23 97,5
10 30 70 9,89 37,92 10 28 101 15,02 99,71 10 29 101 13,86 98,2
11 19 78 6,65 37,19 11 27 101 15,75 99,43 11 30 101 15,9 98,58
12 21 57 6,95 26,77 12 29 101 14,83 96,2 12 32 101 18,67 97,87
13 25 90 7,92 48,42 13 25 102 16,08 99,05 13 42 101 20,15 97,35
14 19 89 7,56 58,18 14 26 101 15,1 99,2 14 42 102 19,56 98,19
15 24 80 7,84 47,45 15 26 101 14,29 97,49 15 31 101 15,41 98,78
16 30 79 7,54 44,88 16 26 101 11,71 90,88 16 82 101 12,82 93,71
17 19 73 5,79 33 17 25 101 13,02 88,9 17 44 100 16,44 82,11
18 27 71 5,63 35,36 18 23 100 9,53 64,04 18 29 83 9,36 53,5
19 21 79 6,54 46,26 19 18 90 6,94 52,13 19 30 100 7,1 50,34
20 24 71 7,49 46,59 20 26 100 10,02 75,09 20 30 101 11,39 89,76
21 23 82 7,46 47,13 21 24 100 9,59 79,04 21 27 101 10,73 91,72
22 26 95 8,53 48,62 22 26 98 10,17 76,58 22 35 100 10,39 89,17
23 23 95 8,83 63,73 23 26 99 12,21 83,16 23 27 100 10,65 87,39
AVG 24,33333 74,875 7,439167 35,347 AVG 25,16667 92,417 10,70125 69,53 AVG 34,70833 87,375 13,45625 67,8946
226
lxiii. Sampel Data Penggunaan Bandwidth International Bulan Mei
Waktu Penggunaan Bandwidth International Per
Hari (8 Mei 2014)
Waktu Penggunaan Bandwidth International Per
Hari (15 Mei 2014)
Waktu Penggunaan Bandwidth International Per
Hari (26 Mei 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 41 83 11,73 42,02 0 16 88 5,91 42,93 0 39 53 9,2 20,91
1 31 85 6,22 41,76 1 15 91 5,86 40,29 1 23 48 9,29 24,17
2 11 51 0,50 3,79 2 21 78 5,41 37,41 2 20 40 8,84 19,61
3 0 0 0,00 0,00 3 30 67 4,55 26,65 3 21 26 10,37 11,68
4 9 8 0,24 0,07 4 13 45 4,04 19,12 4 21 29 8,84 8,76
5 32 17 3,15 5,53 5 15 34 4,70 14,30 5 21 34 8,5 11,89
6 26 47 3,57 19,55 6 None None None None 6 24 66 9,89 22,65
7 21 87 6,03 35,24 7 None None None None 7 38 99 14,52 53,23
8 37 101 14,76 90,77 8 None None None None 8 31 101 14,66 89,38
9 36 101 15,75 99,20 9 35 100 17,38 91,61 9 28 101 16,08 96,23
10 31 101 13,16 97,67 10 54 101 22,59 96,52 10 31 101 16,76 98,19
11 29 101 15,31 98,77 11 42 101 24,67 97,34 11 30 101 16,7 98,51
12 30 101 16,97 98,50 12 53 101 21,82 96,97 12 27 101 16,09 97,93
13 32 101 14,88 98,16 13 37 101 22,55 95,96 13 32 101 18,47 98,43
14 26 101 11,89 87,84 14 41 101 24,11 97,36 14 39 101 20,02 99,51
15 26 114 13,93 96,66 15 38 101 22,76 98,02 15 44 101 20,02 98,23
16 24 101 11,60 96,76 16 52 101 26,60 90,40 16 32 101 19,1 89,66
17 27 99 9,36 74,97 17 36 99 16,89 75,25 17 29 100 13,21 74,39
18 17 68 8,23 21,96 18 35 89 14,70 55,98 18 31 99 11,76 77,93
19 None None None None 19 63 91 16,90 49,29 19 31 93 11,16 52,82
20 None None None None 20 30 100 16,55 74,63 20 25 97 14,15 68,93
21 None None None None 21 43 101 19,74 65,71 21 27 97 13,87 75,08
22 22 81 6,21 44,84 22 42 100 21,42 82,08 22 29 98 12,46 72,12
23 23 98 8,40 75,22 23 32 98 16,50 78,44 23 39 85 10,77 46,95
AVG 25,2857 78,381 9,137259 58,5366 AVG 35,38095 89,905 15,98362 67,917 AVG 29,66667 82,208 13,53042 62,8
227
lxiv. Sampel Data Penggunaan Bandwidth International Bulan Juni
Waktu Penggunaan Bandwidth International Per
Hari (2 Juni 2014)
Waktu Penggunaan Bandwidth International Per
Hari (10 Juni 2014)
Waktu Penggunaan Bandwidth International Per
Hari (18 Juni 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb)
Jam
Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb)
Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 42 75 23,46936 39,1636 0 40 67 9,400922 36,9315 0 35 89 15,1926 39,356
1 44 68 25,34357 27,9003 1 23 68 8,275145 33,0532 1 56 53 21,64051 23,576
2 34 52 18,09687 21,8765 2 64 65 7,333568 27,2673 2 45 43 18,6133 23,802
3 51 75 16,68892 21,267 3 21 32 4,855063 3,88369 3 54 54 22,35281 27,849
4 36 44 16,15912 15,4594 4 25 29 4,942592 3,37218 4 39 47 22,07907 11,567
5 35 56 19,67073 17,8339 5 22 40 3,655751 13,4845 5 42 50 20,67345 10,991
6 67 99 19,90587 23,1168 6 22 58 6,677919 19,7208 6 44 44 27,43372 22,535
7 50 101 20,87951 58,8888 7 26 99 7,523827 47,0059 7 44 90 26,20395 45,593
8 59 101 25,11768 95,0621 8 28 101 15,09623 96,5843 8 44 101 25,18108 91,039
9 39 101 20,33762 97,4377 9 43 101 16,15847 98,1747 9 34 101 22,44898 97,969
10 31 101 14,23784 97,8471 10 30 101 17,74869 98,3447 10 42 101 25,52052 98,624
11 38 101 18,37814 98,6289 11 39 101 15,16696 98,1798 11 48 101 25,45929 98,598
12 27 102 15,64616 98,932 12 67 124 15,55394 98,6276 12 38 101 23,09983 95,646
13 33 109 16,91185 98,3345 13 30 101 14,93011 98,1083 13 39 101 23,46663 98,191
14 29 101 16,31656 98,9485 14 33 101 16,14761 98,3057 14 44 101 27,68243 98,427
15 28 101 15,71848 97,434 15 33 114 15,67019 97,2383 15 55 101 31,46764 98,549
16 62 101 14,66315 90,638 16 44 101 16,80583 97,2641 16 45 101 30,04274 94,543
17 26 99 9,245677 67,0483 17 35 101 16,78847 90,4772 17 46 98 27,75951 73,585
18 39 80 9,219314 51,719 18 37 92 13,47393 58,6501 18 50 92 24,52515 55,136
19 29 96 10,88761 71,3187 19 26 99 14,1146 83,1181 19 43 86 22,16793 56,371
20 29 101 10,32275 87,5035 20 38 100 15,52197 80,0081 20 51 99 25,56832 81,884
21 36 100 10,60706 82,8571 21 34 98 16,78006 79,4194 21 53 100 31,03576 76,704
22 30 98 10,22837 77,8927 22 30 96 16,99297 79,6721 22 66 94 39,23104 66,943
23 24 97 9,851359 69,2753 23 37 98 20,14493 78,298 23 58 101 33,4689 84,11
AVG 38,25 89,958 16,16265 66,9327 AVG 34,45833 86,95833 12,90666 67,2996 AVG 46,45833 85,375 25,51313 65,483
228
lxv. Sampel Data Penggunaan Bandwidth Indonesia Bulan April
Waktu Penggunaan Bandwidth Indonesia Per Hari (9
April 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari
(17 April 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari (30
April 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb)
Jam
Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb)
Jam
Maksimal Bandwidth
(Mb)
Rata - Rata Bandwidth
(Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 11 153 1,35 31,49 0 29 202 2,27 37,94 0 29 68 1,83 24,21
1 19 159 1,17 26,09 1 7 154 1,5 26,02 1 13 69 1,32 14,94
2 5 109 0,82 12,02 2 9 108 1,03 15,24 2 13 92 0,88 14,75
3 6 96 0,61 8,75 3 10 43 0,46 3,33 3 16 47 0,61 6,21
4 17 85 0,4 8,31 4 5 92 0,86 10,41 4 19 41 0,97 7,91
5 6 63 0,55 5,35 5 15 131 1,07 12,38 5 33 42 1,08 7,37
6 13 110 0,88 16,04 6 20 60 1,42 10,33 6 33 41 1,27 8,27
7 25 85 0,95 16,59 7 13 101 2,97 34,24 7 34 138 2,84 37,33
8 12 97 0,85 11,74 8 31 238 5,93 102,5 8 34 233 6,54 112,01
9 14 51 1,04 13,38 9 26 246 7,52 114,88 9 28 223 7,05 124,79
10 14 161 1,74 33,57 10 30 238 7,1 104,94 10 21 245 8,12 149,33
11 23 191 1,83 34,28 11 36 202 4,98 114,61 11 24 238 8,11 139,2
12 16 71 1,4 31,72 12 27 211 4,22 131,74 12 28 228 6,86 121,22
13 18 137 1,58 29,36 13 27 196 3,86 115,5 13 31 233 7,32 125,75
14 14 52 1,56 22,1 14 24 197 3,96 115,24 14 32 239 9,26 159,3
15 18 99 1,88 29,52 15 32 203 3,48 115,55 15 36 234 7,48 134
16 19 67 1,96 19,71 16 14 231 3,46 87,32 16 26 236 5,63 90,35
17 11 146 1,68 24,64 17 12 204 3,2 91,5 17 25 175 3,64 53,82
18 12 74 2,22 15,18 18 17 166 1,74 38,96 18 20 137 2,6 26,73
19 19 155 2,25 22,35 19 19 81 1,66 32,64 19 27 144 3,29 47,31
20 17 147 2,4 24,48 20 11 125 2,32 53,32 20 26 184 4,47 71
21 31 73 2,35 31,47 21 16 127 2,81 58,52 21 20 210 4,61 72,74
22 11 131 2,26 36,33 22 24 154 2,75 57,66 22 20 187 3,76 65,93
23 22 82 1,44 17,8 23 23 125 1,54 57,61 23 17 112 2,66 52,71
AVG 15,54167 108,0833 1,465417 21,76125 AVG 19,875 159,7917 3,004583 64,26583 AVG 25,20833 158,1667 4,258333 69,46583
229
lxvi. Sampel Data Penggunaan Bandwidth Indonesia Bulan Mei
Waktu Penggunaan Bandwidth Indonesia Per Hari (8
Mei 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari
(15 Mei 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari
(26 Mei 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 8 168 1,69 31,90 0 15 114 1,60 20,74 0 9 49 2,03 9,5
1 15 61 1,16 13,41 1 15 110 1,28 20,38 1 7 68 1,8 15,04
2 27 40 0,49 5,75 2 6 124 1,03 13,68 2 21 56 1,43 9,25
3 13 11 0,25 0,37 3 7 64 0,73 7,19 3 11 46 1,55 5,2
4 10 32 0,53 2,41 4 13 58 0,77 9,49 4 10 41 1,66 3,5
5 15 20 0,86 7,02 5 13 82 0,88 9,53 5 18 43 2,41 6,52
6 15 40 0,81 4,75 6 15 95 1,36 14,77 6 12 87 1,49 11,51
7 18 113 1,75 20,44 7 16 85 1,47 16,27 7 16 150 2,77 26,23
8 22 211 4,05 68,45 8 21 120 2,28 36,63 8 21 208 7,12 86,2
9 27 233 6,44 112,46 9 17 111 2,39 29,85 9 37 231 9,32 139,94
10 61 244 7,96 132,77 10 12 173 3,15 49,85 10 36 226 10,28 148,03
11 27 229 8,20 136,86 11 35 176 3,82 65,09 11 28 240 10,02 149,72
12 28 230 8,24 140,08 12 20 156 3,59 53,95 12 20 206 7,75 131,43
13 43 236 8,62 146,22 13 20 205 4,90 72,81 13 31 223 8,6 138,26
14 30 247 8,28 132,62 14 23 203 4,58 79,18 14 14 188 2,52 53,26
15 27 239 8,48 144,22 15 17 152 3,63 65,81 15 23 200 2,09 102,48
16 22 214 5,49 95,13 16 18 171 3,20 56,00 16 15 177 2,02 78,77
17 19 108 3,28 45,89 17 23 111 2,68 41,63 17 11 131 1,92 52,94
18 9 73 2,31 16,92 18 16 98 2,70 31,84 18 18 139 1,32 35,75
19 None None None None 19 23 133 3,52 44,07 19 19 163 1,73 34,76
20 None None None None 20 20 119 2,96 38,39 20 16 226 1,99 79,4
21 None None None None 21 17 149 3,45 45,61 21 19 152 2,11 78,25
22 16 106 1,54 5,61 22 19 168 3,63 53,47 22 13 142 2,02 70,57
23 11 104 1,19 6,77 23 27 141 2,69 44,07 23 19 123 1,58 57,96
AVG 22,04762 140,9048 3,886687 60,47928 AVG 17,83333 129,9167 2,595417 38,34583 AVG 18,5 146,4583 3,647083 63,51958
230
lxvii. Sampel Data Penggunaan Bandwidth Indonesia Bulan Juni
Waktu Penggunaan Bandwidth Indonesia Per Hari (2
Juni 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari
(10 Juni 2014)
Waktu Penggunaan Bandwidth Indonesia Per Hari
(18 Juni 2014)
Jam Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal Bandwidth
(Mb)
Rata - Rata
Bandwidth (Mb) Jam
Maksimal
Bandwidth (Mb)
Rata - Rata
Bandwidth (Mb)
Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive Transmite Receive
0 13 88 2,452552 24,37262 0 16 66 1,899264 20,65144 0 25 73 4,730733 20,94167
1 10 71 2,322312 15,67873 1 12 85 2,038182 31,21452 1 27 70 3,208607 18,86777
2 10 63 3,065145 17,66353 2 12 77 1,932047 17,61951 2 7 112 1,233133 12,0568
3 12 48 2,114974 7,887203 3 19 48 1,064908 8,5294 3 6 118 1,398297 7,768326
4 18 32 1,628956 5,697599 4 11 25 1,169632 2,901324 4 10 77 1,033945 6,330383
5 14 86 1,525406 12,65606 5 31 61 0,708951 11,06917 5 16 44 1,706303 8,888984
6 26 72 2,067603 12,60791 6 15 57 1,089169 13,51208 6 12 118 1,704837 6,950669
7 15 175 3,600646 47,48268 7 23 200 2,619347 33,27597 7 30 166 2,789994 32,24566
8 35 229 8,989424 127,9336 8 24 227 6,144361 104,461 8 36 154 4,975797 76,15768
9 28 217 8,600818 129,8866 9 25 224 8,808449 120,5029 9 22 213 7,91958 113,6241
10 26 230 9,885429 139,8296 10 26 225 9,409959 133,465 10 23 191 8,442037 107,2207
11 38 235 10,00702 151,2058 11 32 230 8,675 144,7023 11 27 224 7,967836 133,3105
12 29 236 8,87822 147,5398 12 21 240 7,934606 143,6771 12 18 187 6,762181 98,50638
13 28 242 9,538821 149,3526 13 36 234 7,934149 144,2826 13 33 201 8,456038 113,1389
14 27 232 10,60597 166,6862 14 34 237 7,865889 147,8309 14 26 187 8,748101 103,2706
15 24 240 10,01528 171,4324 15 24 239 7,329225 133,9313 15 35 178 8,924694 103,5137
16 22 224 6,505105 101,6066 16 53 211 6,121283 108,221 16 26 199 7,637215 90,65594
17 19 161 2,758085 31,9105 17 26 217 5,16277 89,61339 17 19 112 5,194704 41,82425
18 19 143 3,05498 32,51147 18 24 90 3,067908 35,93105 18 20 131 3,101033 38,43897
19 18 126 3,884925 42,25982 19 23 102 3,775415 38,41197 19 36 149 4,994291 51,96614
20 25 128 5,495954 61,85607 20 12 121 3,878051 45,95604 20 20 177 6,721886 68,99001
21 23 189 5,116372 59,54647 21 20 197 4,646068 60,11855 21 22 177 3,965544 64,75
22 24 117 3,744484 56,01673 22 30 207 4,063972 46,27395 22 19 181 4,11 63,70855
23 17 171 2,972874 47,22908 23 17 147 3,425067 52,7545 23 14 92 2,923122 40,16872
AVG 21,66667 156,4583 5,367973 73,36874 AVG 23,58333 156,9583 4,615153 70,37112 AVG 22,04167 147,125 4,943746 59,30398
231
LAMPIRAN E
Pada Lampiran E terdapat data hari dimana terjadi mati lamu selama bulan April 2014
sampai bulan Juni 2014
232
233
234
235
236
237
238
239
LAMPIRAN F
Pada lampiran F, terdapat bagan dari struktur program yang telah dibuat oleh penulis.
Bagan tersebut dapay di lihat pada halaman selanjutnya.
240
lxviii. Struktur Program Bandwidth
Mengkoneksikan Raspberry
dengan BGP Server
Menggunakanan Komunikasi
Internet
Melakukan
Proses ping
ke ip tujuan
Masukan data
ping ke dalam
database
Program
berhenti 2
detik
Notifikasi sms jika jaringan
International terdapat
perubahan status
Mendapatkan Data
bandwdith dari BGP
server
Masukan data
Bandwidth ke
dalam
database
Program
berhenti 2
detik
241
lxix. Struktur Program Listrik
Mengaktifkan
GPIO 27
sebagai inputan
Membaca Tegangan Pada
GPIO
Notifikasi SMS
ketika Terjadi
peruahan status
listrik
Memasukan
Data ke dalam
Database
Menghentikan
Program
selama 2 detik
242
lxx. Struktur Program Temperatur
Mengaktifkan
Protokol 1 wire
Membaca
Sensor 1
Menambahkan
ke dalam
listtemp
Membaca
Sensor 2
Menambahkan
ke dalam
listtemp
Membaca
Sensor 3
Menambahkan
ke dalam
listtemp
Memasukan data
listtemp ke dalam
database
Program berhenti
selama 2 detik
Mengirim SMS
ketika perubahan
status
111
LAMPIRAN G
Pada lampiran F berisikan datasheet Sensor DS18B20 :
1-Wire ® (Protocol)
Company: Dallas Semiconductor/Maxim
Linus Wong
What is it?
Protocol: to digitally communicate over twisted-pair cable with 1-Wire components
over a 1-Wire network
network is defined with an open-drain (wired-AND) master/slave multidrop
architecture with resistor pull-up to a nominal 5V supply at the master
1-Wire net’s 3 components:
a bus master with controlling software (e.g. TMEX™ iButton® viewer)
wiring and associated connectors
1-Wire devices
Features/Benefits
each 1-Wire slave has stored in ROM a unique 64-bit serial number that acts as its
node address device to be individually selected from among many that can be
connected to the same bus wire
This globally unique address is composed of eight bytes divided into three main
sections. Starting with the LSB, the first byte stores the 8-bit family codes that
identify the device type. The next six bytes store a customizable 48-bit individual
112
address. The last byte, the most significant byte (MSB), contains a cyclic
redundancy check (CRC) with a value based on the data contained in the first seven
bytes. This allows the master to determine if an address was read without error.
With a 248 serial number pool, conflicting or duplicate node addresses on the net
are never a problem.
1-Wire devices can be formatted with a file directory like a floppy disk files can
be randomly accessed and changed without disturbing other records
Maximum data security can be provided by 1-Wire chip implementation of the US
government-certified Secure Hash Algorithm (SHA-1)
uses a single wire (plus ground) to accomplish both communication and power
transmission.
A single bus master can feed multiple slaves over a single twisted-pair cable
simplify design with an interface protocol that supplies control, signaling, and
power over a single-wire connection.
About the Protocol
1-Wire protocol uses conventional CMOS/TTL logic levels (maximum 0.8V for
logic “zero” and a
minimum 2.2V for logic “one”) with operation specified over a supply voltage
range of 2.8V to 6V.
113
Both master and slaves are configured as transceivers permitting bit sequential data
to flow in either direction, but only one direction at a time (halfduplex); Master
initiates and controls all devices
Data is byte-sequential and bit-sequential with data read and written least
significant bit (LSB) first
signal is transferred in time slots
System clock is not required; each 1-Wire part is self-clocked by an internal
oscillator synchronized to the falling edge of the master
4 basic protocol operations:
(http://www.maxim-ic.com/appnotes.cfm/appnote_number/522/ln/en App126)
All device commands are built off these!
Libraries implementing these and higher order functions available.
114
Typical 1-Wire Communication Flow
The first part of any communication involves the bus master issuing a “reset” which
synchronizes the entire bus. A slave device is then selected for subsequent
communications. This can be done by selecting all slaves, selecting a specific slave
(using the serial number of the device), or by discovering the next slave on the bus
using a binary search algorithm. These commands are referred to collectively as
“network” or ROM (Read-Only-Memory) commands. Once a specific device has
been selected, all other devices drop out and ignore subsequent communications
until the next reset is issued.
115
Once a device is isolated for bus communication the master can issue device-
specific commands to it, send data to it, or read data from it. Because each device
type performs different functions and serves a different purpose, each has a unique
protocol once it has been selected. Even though each device type may have different
protocols and features, they all have the same selection process and follow the
command flow as seen in Figure 1 (above).
How power is supplied in the most common cases (w/ diagrams)
3 primary ways:
Sourcing power whenever the line is above 3.5V.
Since 1-Wire devices can operate with a 3V supply, the energy available between
the bus supply levels of 3.5V and 5V can be tapped.
equivalent to operating the load in shunt mode (permanently across the bus, or
preferably under bus master control)
(Powering methods continued)
Sourcing power when line is high by transferring charge to a capacitor (or
rechargeable battery) through a blocking diode
116
During idle periods when the bus is at 5V, the circuit ‘steals’ power from the line
to charge the capacitor and power the load.
Disadv: adds both capacitive load and leakage that reduce the range and capability
of the 1-Wire network. Can fix by can be isolating it between two addressable
switches controlled by the line master.
Adv: simple and economical; used internally by 1-Wire devices
Parasitic power:
concept of "stealing" power from the net by a half-wave rectifier
When data line is pulled high, the diode in the half-wave rectifier turns on and
charges an on-chip capacitor.
When the voltage on the net drops below the voltage on the capacitor, the diode is
reverse biased, which isolates the charge. The resulting charge provides the energy
source to power the slave during the intervals when the net is pulled low. The
amount of charge lost during these periods is replenished when the data line returns
high.
Sourcing power with a strong pull-up during idle communication time.
117
can be accomplished by using a MOSFET to pull the bus directly to the rail
E.g. DS18S20-PAR (digital thermometer, during temperature conversions)
http://pdfserv.maxim-ic.com/arpdf/DS18S20-PAR.pdf
http://www.maxim-ic.com/appnotes.cfm/appnote_number/949/ln/en (App147:
Supplying power via 1-wire bus)
http://www.maxim-ic.com/appnotes.cfm/appnote_number/857/ln/en (App148:
Guidelines for Reliable 1-wire networks)
Some Topologies
(see http://www.maxim-ic.com/appnotes.cfm/appnote_number/523/ln/en)
118
General Ways to Communicate
Software methods via microprocessor: 1-Wire API for Windows (TMEX), 1-Wire
COM interface (OWCOM), 1-Wire Public Domain (PD), and 1-Wire API for
Java™ (OWAPI)
a predefined 1-Wire master chip in Verilog and VHDL
DS2480B Serial 1-Wire Line Driver to communicate with any UART
DS1481 provides a 1-Wire master with a parallel interface.
(http://www.maxim-ic.com/appnotes.cfm/appnote_number/522/ln/en last page)
119
Closing Remarks
DS9091K 1-Wire MicroLAN Evaluation Kit
http://www.maxim-ic.com/quick_view2.cfm/qv_pk/2973
$49.00
examples: Window/door monitor, Temperature logger, Simulated room temperature control,
Burglar alarm system
37 1-Wire devices, 48 iButtons and accessories (sensors, clocks, adapters, memory,
etc.)
* http://www.maxim-ic.com/1-Wire (main page)
http://www.maxim-ic.com/appnotes.cfm/appnote_number/1796/ln/en (overview)
http://www.maxim-ic.com/appnotes.cfm/appnote_number/1189/ln/en (App214:
Using a UART to Implement a 1-Wire Bus Master)
http://www.maxim-ic.com/appnotes.cfm/appnote_number/855/ln/en (App155:
overview and selection guide to available APIs/resources for communicating with
the variety of devices)
* http://www.maxim-ic.com/an_prodline2.cfm/prodline/21 (ALL Application
Notes and Tutorials for 1-Wire devices)
120
* http://www.maxim-ic.com/appnotes.cfm/appnote_number/523/ln/en (App132:
Quick Guide to 1-Wire net Using PCs and Microcontrollers)
http://www.brianlane.com/digitemp.php (“DigiTemp is a simple to use interface to
the Dallas Semiconductor DS18S20 (DS18S20-PAR), DS1822, (DS1822-PAR)
and DS18B20 (DS18B20-PAR) digital temperature sensors”)