提交 cb9bfcda authored 作者: blu's avatar blu

dingbot

上级 3f16cd34
...@@ -16,7 +16,7 @@ import pdb, traceback, sys, socket ...@@ -16,7 +16,7 @@ import pdb, traceback, sys, socket
logger = logging.getLogger(__file__) logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
ch = logging.StreamHandler() ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter(('[%(asctime)s][ota][%(lineno)d][%(levelname)s] %(message)s'))) ch.setFormatter(logging.Formatter(('[%(asctime)s][dingbot][%(lineno)d][%(levelname)s] %(message)s')))
logger.addHandler(ch) logger.addHandler(ch)
SECRET = os.getenv('SECRET', 'SEC3219d0b06510f560349170c4d571b8fd10a5dfa616d4f9ef5494f63add766d65') # SECf8938911f24df40a0b86b711179fa7fc8ba88eb5d82e4e9f07bc03b5f29e8f6a SECRET = os.getenv('SECRET', 'SEC3219d0b06510f560349170c4d571b8fd10a5dfa616d4f9ef5494f63add766d65') # SECf8938911f24df40a0b86b711179fa7fc8ba88eb5d82e4e9f07bc03b5f29e8f6a
...@@ -27,6 +27,7 @@ MQTT_HOST='evcloudsvc.ilabservice.cloud' ...@@ -27,6 +27,7 @@ MQTT_HOST='evcloudsvc.ilabservice.cloud'
MQTT_PORT=11883 MQTT_PORT=11883
MQTT_USER='admin' MQTT_USER='admin'
MQTT_PASSWORD='vJ3zHqWrHbrqxVMT' MQTT_PASSWORD='vJ3zHqWrHbrqxVMT'
EVC_API_TPL='http://evcloudsvc.ilabservice.cloud:8089/ipcstatus?sn={}'
app = Flask(__name__, app = Flask(__name__,
static_url_path='', static_url_path='',
...@@ -48,12 +49,14 @@ class DingBot: ...@@ -48,12 +49,14 @@ class DingBot:
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
return timestamp, urllib.parse.quote_plus(base64.b64encode(hmac_code)) return timestamp, urllib.parse.quote_plus(base64.b64encode(hmac_code))
def send_msg(self, title, text): def send_msg(self, title, body, link):
ts, sign = self.sign() ts, sign = self.sign()
url = API_TPL.format(self.token, ts, sign) url = API_TPL.format(self.token, ts, sign)
body = {'msgtype': 'markdown', 'markdown':{ body = {'msgtype': 'link', 'link':{
'title': title, 'title': title,
'text': text 'text': body,
'picUrl':'',
'messageUrl': link
}} }}
r = requests.post(url, json = body) r = requests.post(url, json = body)
logger.info("{}, {}".format(r.status_code, r.text)) logger.info("{}, {}".format(r.status_code, r.text))
...@@ -89,7 +92,49 @@ class DingBot: ...@@ -89,7 +92,49 @@ class DingBot:
logger.info("disconnected") logger.info("disconnected")
def handle(self, jd): def handle(self, jd):
self.send_msg('alarm', json.dumps(jd)) '''
{
"category":"issues",
"code":0,
"data":{
"AV_MGROFFLINE":{
"catId":"AV_MGROFFLINE",
"ipc":"TESTDEV1",
"level":"error",
"modId":"ALL",
"msg":"[autogen]evcloudsvc detects cluster mgr TESTDEV1 offline for ipc TESTDEV1",
"status":"active",
"time":1591170511,
"type":"report"
}
},
"msg":"ok",
"rid":"",
"sn":"evcloudsvc",
"time":1591170511650,
"type":"report"
}
'''
issues = ""
idx = 1
ipcSn = ""
if jd.get('category') == 'issues' and jd.get('data'):
for k, v in jd["data"].items():
if not ipcSn:
ipcSn = v["ipc"]
msg = v["msg"]
if k == 'AV_MGROFFLINE':
issues += "[{}]盒子离线;".format(idx)
elif k == 'AV_OPENINPUT':
pos = msg.rfind(":")
issues += "[{}]连接失败: {}".format(idx, msg[pos+2:])
else:
issues += "[{}] {}".format(idx, msg)
if issues:
body = "摄像头 {}故障 ".format(ipcSn) + issues
self.send_msg('告警', body, EVC_API_TPL.format(ipcSn))
def __init__(self, token, secret, host=MQTT_HOST, port=MQTT_PORT): def __init__(self, token, secret, host=MQTT_HOST, port=MQTT_PORT):
''' '''
...@@ -109,9 +154,9 @@ class DingBot: ...@@ -109,9 +154,9 @@ class DingBot:
self.client.loop_start() self.client.loop_start()
except Exception as e: except Exception as e:
logger.error('exception in init:', e) logger.error('exception in init:', e)
extype, value, tb = sys.exc_info() # extype, value, tb = sys.exc_info()
traceback.print_exc() # traceback.print_exc()
pdb.post_mortem(tb) # pdb.post_mortem(tb)
@app.teardown_appcontext @app.teardown_appcontext
def shutdown_session(exception=None): def shutdown_session(exception=None):
......
...@@ -1379,7 +1379,7 @@ public: ...@@ -1379,7 +1379,7 @@ public:
thread th=thread([this]{ thread th=thread([this]{
while(1){ while(1){
// check every 5 minutes // check every 5 minutes
this_thread::sleep_for(chrono::seconds(5)); this_thread::sleep_for(chrono::seconds(60*5));
{ {
lock_guard<recursive_mutex> lg(mutIpcStatus); lock_guard<recursive_mutex> lg(mutIpcStatus);
for(auto &[k,v]: this->peerData["ipcStatus"].items()){ for(auto &[k,v]: this->peerData["ipcStatus"].items()){
...@@ -1389,6 +1389,9 @@ public: ...@@ -1389,6 +1389,9 @@ public:
} }
}); });
if(th.joinable()){
th.detach();
}
svr.Get("/config", [this](const Request& req, Response& res) { svr.Get("/config", [this](const Request& req, Response& res) {
json ret; json ret;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论