uptime-monitor/main.py

75 lines
1.9 KiB
Python
Raw Normal View History

2024-01-22 07:58:22 +00:00
import cv2
import numpy as np
import urllib.request
from datetime import datetime
2024-01-22 08:25:58 +00:00
import time
2024-01-22 07:58:22 +00:00
recent=[]
history=[]
width=720
2024-01-22 08:01:09 +00:00
height=50
2024-01-22 07:58:22 +00:00
red=(0x00,0x00,0xff)
orange=(0x00,0x66,0xff)
yellow=(0x00,0xcc,0xff)
light_green=(0x33,0xff,0xcc)
green=(0x00,0xcc,0x00)
def update_history():
average=0
for i in recent:
average+=i
average/=len(recent)
if len(history)>=144:
del(history[0])
history.append(average)
def fill(img,pos,color):
for i in range(5):
2024-01-22 08:01:09 +00:00
for j in range(height):
2024-01-22 07:58:22 +00:00
img[j,i+5*pos,:]=[color[0]%256,color[1]%256,color[2]%256]
def update_graph():
img=np.ones([height,width,3],dtype=np.uint8)
for i,delay in enumerate(history):
if delay>=5000:
fill(img,i,red)
2024-01-22 13:35:10 +00:00
elif delay>=3000:
2024-01-22 07:58:22 +00:00
fill(img,i,orange)
2024-01-22 13:35:10 +00:00
elif delay>=2000:
2024-01-22 07:58:22 +00:00
fill(img,i,yellow)
2024-01-22 13:35:10 +00:00
elif delay>=1000:
2024-01-22 07:58:22 +00:00
fill(img,i,light_green)
else:
fill(img,i,green)
2024-01-22 09:21:01 +00:00
cv2.imwrite("/tmp/uptime-graph/image.png", img)
2024-01-22 07:58:22 +00:00
def testConnect(url):
try:
time1=datetime.now().timestamp()
code=urllib.request.urlopen(url,timeout=5).getcode()
time2=datetime.now().timestamp()
delay=int((time2-time1)*1000)
except:
code=404
if code/100>=4:
delay=10000
return (code,delay)
if __name__=="__main__":
lastminute=-1
while True:
if datetime.now().second==0 and datetime.now().minute!=lastminute:
# if True:
2024-01-22 08:25:58 +00:00
time.sleep(0.5)
2024-01-22 07:58:22 +00:00
(code,delay)=testConnect("https://blog.clf3.org")
print(code,end=" ")
if code/100<=3:
print("connected",delay,"ms")
else:
print("error")
if len(recent)<10:
recent.append(delay)
else:
update_history()
update_graph()
recent=[]
recent.append(delay)
lastminute=datetime.now().minute