Browse Source

中海财富中心

李莎 2 years ago
commit
218effb4b9
9 changed files with 587 additions and 0 deletions
  1. 49 0
      MyUtils/ConfigUtils.py
  2. 137 0
      MyUtils/DateUtils.py
  3. 18 0
      MyUtils/Dingtalk.py
  4. 42 0
      MyUtils/HttpUtil.py
  5. 53 0
      MyUtils/MetadataWebUtil.py
  6. 72 0
      MyUtils/MysqlUtils.py
  7. 104 0
      MyUtils/ZillionUtil.py
  8. 18 0
      config.json
  9. 94 0
      main.py

+ 49 - 0
MyUtils/ConfigUtils.py

@@ -0,0 +1,49 @@
+import xml.etree.ElementTree as ET
+
+
+#读取xml文件
+class ConfigUtils():
+    def __init__(self,file):
+        self.url = ""
+        self.tree = ET.parse(file)
+        self.root = self.tree.getroot()
+
+    def readTop(self, key, child):
+        datas = []
+        data = self.root.find(key)
+        for key in child:
+            datas.append(data.get(key))
+        return datas
+
+    def readTopDict(self, key, child):
+        datas = {}
+        data = self.root.find(key)
+        for key in child:
+            datas[key] = data.get(key)
+        return datas
+
+    def readConfig(self,parent,child):
+        datas=[]
+        for childLine in self.root.find(parent):
+            data=[]
+            for key in child:
+                data.append(childLine.get(key))
+            datas.append(data)
+        return datas
+
+    def readConfigDict(self,parent,child):
+        datas=[]
+        for childLine in self.root.find(parent):
+            data={}
+            for key in child:
+                data[key]=childLine.get(key)
+            datas.append(data)
+        return datas
+
+    def readConfigSingle(self,key):
+        data = self.root.find(key).text
+        return data
+
+
+if __name__ == '__main__':
+    config = ConfigUtils("logger.conf")

+ 137 - 0
MyUtils/DateUtils.py

@@ -0,0 +1,137 @@
+import datetime
+from dateutil.relativedelta import relativedelta
+from dateutil import rrule
+
+YYmmddHHMMSS = "%Y%m%d%H%M%S"
+YYmmdd = "%Y%m%d"
+YYmm = "%Y%m"
+# 根据开始月份结束月份获取所有月份
+def get_each_month(start_month, end_month):
+    if str(start_month).count('-') != 1 or str(end_month).count('-') != 1:
+        print("Parameter Error: Pls input a string such as '2019-01'")
+        return []
+    if int(str(start_month).split('-')[1]) > 12 or int(str(end_month).split('-')[1]) > 12:
+        print('Parameter Error: Pls input correct month range such as between 1 to 12')
+        return []
+    if int(str(start_month).split('-')[1]) == 0 or int(str(end_month).split('-')[1]) == 13:
+        print('Parameter Error: Pls input correct month range such as between 1 to 12')
+        return []
+    start = datetime.datetime.strptime(start_month, "%Y-%m")
+    end = datetime.datetime.strptime(end_month, "%Y-%m")
+    month_count = rrule.rrule(rrule.MONTHLY, dtstart=start, until=end).count()  # 计算总月份数
+    if end < start:
+        print("Parameter Error: Pls input right date range,start_month can't latter than end_month")
+        return []
+    else:
+        list_month = []
+        year = int(str(start)[:7].split('-')[0])  # 截取起始年份
+        for m in range(month_count):  # 利用range函数填充结果列表
+            month = int(str(start)[:7].split('-')[1])  # 截取起始月份,写在for循环里,作为每次迭代的累加基数
+            month = month + m
+            if month > 12:
+                if month % 12 > 0:
+                    month = month % 12  # 计算结果大于12,取余数
+                    if month == 1:
+                        year += 1  # 只需在1月份的时候对年份加1,注意year的初始化在for循环外
+                else:
+                    month = 12
+            if len(str(month)) == 1:
+                list_month.append(str(year) + '-0' + str(month))
+            else:
+                list_month.append(str(year) + '-' + str(month))
+        return list_month
+
+
+# 转换格式,去掉"-",%Y%m
+def get_eachmonth(start_month, end_month):
+    startmonth = start_month[0:4] + "-" + start_month[4:6]
+    endmonth = end_month[0:4] + "-" + end_month[4:6]
+    months = get_each_month(startmonth, endmonth)
+    list_month = [i[0:4] + i[5:7] for i in months]
+    return list_month
+
+
+def get_month(starttime, endtime):
+    months = []
+    starttime = datetime.datetime.strptime(starttime, YYmmddHHMMSS)
+    endtime = datetime.datetime.strptime(endtime, YYmmddHHMMSS)
+    while starttime <= endtime:
+        start = starttime.strftime("%Y%m")
+        if start not in months:
+            months.append(start)
+        starttime = starttime + datetime.timedelta(days=1)
+    return months
+
+def get_month_range(starttime, endtime):
+    months = []
+    starttime = datetime.datetime.strptime(starttime[0:8], YYmmdd)
+    endtime = datetime.datetime.strptime(endtime[0:8], YYmmdd)
+    while starttime <= endtime:
+        start = starttime.strftime(YYmmddHHMMSS)
+        endMonth = datetime.datetime.strptime(start[0:6], YYmm) + relativedelta(months=+1)
+
+        end = endMonth.strftime(YYmmddHHMMSS)
+        if endtime <= endMonth:
+            end = endtime.strftime(YYmmddHHMMSS)
+        starttime = endMonth
+        months.append([start, end])
+    return months
+
+
+
+def get_month1(starttime, endtime):
+    months = []
+    startyear = int(starttime[0:4])
+    startmonth = int(starttime[4:6])
+    endyear = int(endtime[0:4])
+    endmonth = int(endtime[4:6])
+    while startyear != endyear or startmonth != endmonth:
+        startyearstr = str(startyear)
+        startmonthstr = str(startmonth)
+        if startmonth < 10:
+            startmonthstr = "0" + str(startmonth)
+        months.append(startyearstr + startmonthstr)
+        startmonth += 1
+        if startmonth == 13:
+            startyear += 1
+            startmonth = 1
+    months.append(endtime[0:6])
+    return months
+
+#根据开始结束时间获取最大区间为1天的时间区间
+# def get_day(starttime,endtime):
+#     times = []
+#     starttime = datetime.datetime.strptime(starttime, YYmmddHHMMSS)
+#     endtime = datetime.datetime.strptime(endtime, YYmmddHHMMSS)
+#     while starttime < endtime:
+#         start = starttime.strftime(YYmmddHHMMSS)
+#         starttime_delta = starttime + datetime.timedelta(days=1)
+#         end = starttime_delta.strftime(YYmmddHHMMSS)
+#         if str(starttime)[0:7]<str(starttime_delta)[0:7] :
+#             end = starttime_delta.strftime("%Y%m") +"01000000"
+#             starttime = datetime.datetime.strptime(end, YYmmddHHMMSS)
+#             times.append([start, end])
+#             continue
+#         if starttime >= starttime_delta:
+#             end = starttime_delta.strftime(YYmmddHHMMSS)
+#         starttime = starttime + datetime.timedelta(days=1)
+#         times.append([start,end])
+#     return times
+#根据开始结束时间获取最大区间为1天的时间区间
+def get_day(starttime,endtime):
+    times = []
+    starttime = datetime.datetime.strptime(starttime, YYmmddHHMMSS)
+    endtime = datetime.datetime.strptime(endtime, YYmmddHHMMSS)
+    while starttime < endtime:
+        start = starttime.strftime(YYmmddHHMMSS)
+        stratDay = datetime.datetime.strptime(start[0:8],YYmmdd)
+        starttime_delta = stratDay + datetime.timedelta(days=1)
+        end = starttime_delta.strftime(YYmmddHHMMSS)
+        if endtime <= starttime_delta:
+            end = endtime.strftime(YYmmddHHMMSS)
+        starttime = stratDay + datetime.timedelta(days=1)
+        times.append([start,end])
+    return times
+
+if __name__ == '__main__':
+    print(get_month_range("20200106000000", "20200115000000"))

+ 18 - 0
MyUtils/Dingtalk.py

@@ -0,0 +1,18 @@
+from  dingtalkchatbot.chatbot import DingtalkChatbot
+
+def send_message_mobiles(message,dingtalk,mobiles):
+    webhook = dingtalk
+    xiaoding = DingtalkChatbot(webhook)
+    xiaoding.send_text(msg=message,at_mobiles=[mobiles],is_auto_at=False)
+    return
+
+def send_message(message,dingtalk):
+    webhook = dingtalk
+    xiaoding = DingtalkChatbot(webhook)
+    xiaoding.send_text(msg=message)
+    return
+def send_message_markdown(title,text,dingtalk):
+    webhook = dingtalk
+    xiaoding = DingtalkChatbot(webhook)
+    xiaoding.send_markdown(title=title,text=text)
+    return

+ 42 - 0
MyUtils/HttpUtil.py

@@ -0,0 +1,42 @@
+# coding=utf-8
+import sys
+
+if (sys.version_info.major == 3):
+    from urllib import parse
+    import urllib.request as urllib2
+else:
+    import urllib2
+
+
+class HttpUtil(object):
+    #post方法获取数据  application/json
+    @staticmethod
+    def post(url, postData):  #
+        req = urllib2.Request(url, data=postData.encode('utf-8'),
+                              headers={'Content-Type': 'application/json;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60).read().decode("utf-8")
+        return res
+
+    #post方法获取数据  application/x-www-form-urlencoded
+    @staticmethod
+    def postText(url, postData):
+        req = urllib2.Request(url, data=postData.encode('utf-8'),
+                              headers={'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60).read().decode("utf-8")
+        return res
+
+    #get方法获取数据  text/xml
+    @staticmethod
+    def get(url, getData, isquote):
+        if isquote:
+            getData = parse.quote(getData)
+        req = urllib2.Request((url + getData), headers={'Content-Type': 'text/xml;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60)
+        req = res.read()
+        return req.decode()
+
+
+# if __name__ == '__main__':
+    # httputil = HttpUtil()
+    # httputil.postText()
+    # HttpUtil.postText()

+ 53 - 0
MyUtils/MetadataWebUtil.py

@@ -0,0 +1,53 @@
+import json
+from MyUtils.HttpUtil import *
+
+
+class MetadataWebUtil(object):
+    def __init__(self, url):
+        self.url = url
+
+    def get_hbase(self, params):
+        params = json.dumps(params)
+        word = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.persagy.com/" xmlns:ent="http://entity.persagy.com">' \
+               '<soapenv:Header/>' \
+               '<soapenv:Body><ser:Query>' \
+               '<arg0>%s</arg0>' \
+               '</ser:Query></soapenv:Body></soapenv:Envelope>' % (params)
+        res = HttpUtil.post(self.url, word)
+        res = res.split("<return>")[1].split("</return>")[0]
+        res = json.loads(res.replace("&#xd;", ""))
+        return res
+
+    def database_list(self):
+        params = {
+            "QueryType": "database_list"
+        }
+        res = self.get_hbase(params)
+        return res["Content"]
+
+    def table_list(self, database):
+        params = {
+            "QueryType": "table_list_strict",
+            "Database": database
+        }
+        table_list_strict = self.get_hbase(params)["Content"]
+        params = {
+            "QueryType": "table_list",
+            "Database": database
+        }
+        table_list = self.get_hbase(params)["Content"]
+        table_list = [i for i in table_list if i not in table_list_strict]
+        tables = {}
+        for table in table_list_strict:
+            childs = []
+            for i in table_list:
+                if i.startswith(table + "_"):
+                    try:
+                        word = i[len(table + "_"):]
+                        if len(word) == 4 or len(word) == 6:
+                            word = int(word)
+                            childs.append(i)
+                    except:
+                        pass
+            tables[table] = childs
+        return tables

+ 72 - 0
MyUtils/MysqlUtils.py

@@ -0,0 +1,72 @@
+import pymysql
+from dbutils.pooled_db import PooledDB
+
+
+class MysqlUtils():
+    # 连接池对象
+    __pool = None
+    def __init__(self,**config):
+        self.host = config["host"]
+        self.port = int(config["port"])
+        self.user = config["user"]
+        self.passwd = config["passwd"]
+        self.database = None
+        if "database" in config:
+            self.database = config["database"]
+        self.pool = self.get_conn()
+        # self.pool = None
+
+    def get_conn(self):
+        if MysqlUtils.__pool is None:
+            __pool = PooledDB(pymysql, mincached=1, maxcached=5, maxconnections=5,
+                              host=self.host, port=self.port, user=self.user, passwd=self.passwd,
+                              database=self.database,
+                               use_unicode=False, blocking=False, charset="utf8")
+            self.pool = __pool
+            return __pool
+
+
+    def query(self,sql):
+        con = None
+        cur = None
+        try:
+            con = self.pool.connection()
+            cur = con.cursor()
+            count = cur.execute(sql)
+            if count > 0:
+                result = cur.fetchall()
+                result = [[j.decode() if isinstance(j,bytes) else j for j in i] for i in result]
+                print(result)
+            else:
+                result = False
+            return result
+        except Exception as e:
+            print(e)
+        finally:
+            if cur:
+                cur.close()
+            if con:
+                con.close()
+
+
+    def update(self,sql):
+        con = None
+        cur = None
+        try:
+            con = self.pool.connection()
+            cur = con.cursor()
+            cur.execute(sql)
+            con.commit()
+        except Exception as e:
+            con.rollback()  # 事务回滚
+            print(e)
+        finally:
+            if cur:
+                cur.close()
+            if con:
+                con.close()
+
+    def close(self):
+        if MysqlUtils.__pool:
+            MysqlUtils.__pool.close()
+

+ 104 - 0
MyUtils/ZillionUtil.py

@@ -0,0 +1,104 @@
+from MyUtils.MetadataWebUtil import MetadataWebUtil
+
+
+class ZillionUtil():
+    def __init__(self, url):
+        self.metadata = MetadataWebUtil(url)
+
+    ##列出所有数据库
+    def database_list(self):
+        param = {
+            "QueryType": "database_list"
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+        # TODO  其他zillion语句
+
+    ##列出所有数据库下的表(不包含分表)
+    def table_list_strict(self,table):
+        param = {
+            	"QueryType":"table_list_strict",
+	            "Database":table
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+
+    ##列出所有数据库
+    # def query(self, database, table, Criteria):
+    #     param = {
+    #         "QueryType": "select",
+    #         "Database": database,
+    #         "Datatable": table,
+    #         "Criteria": Criteria
+    #     }
+    #     print(param)
+    #     databases = self.metadata.get_hbase(param)
+    #     return databases["Content"]
+
+    def select(self, database, table, Criteria):
+        param = {
+            "QueryType": "select",
+            "Database": database,
+            "Datatable": table,
+            "Criteria": Criteria
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+    def table_key(self, database, table):
+        param = {
+            "QueryType": "table_detail",
+            "Database": database,
+            "Datatable": table
+        }
+        databases = self.metadata.get_hbase(param)
+        key = databases["Content"]["Key"]
+        return key
+
+
+
+    def select_count(self, database, table, Criteria):
+        param = {
+            "QueryType": "select_count",
+            "Database": database,
+            "Datatable": table,
+            "Criteria": Criteria
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def query_data(self, sql):
+        databases = self.metadata.get_hbase(sql)
+        return databases["Content"]
+
+    def insert(self,database,table,InsertObject):
+        param = {
+            "QueryType": "batch_insert",
+            "Database": database,
+            "Datatable": table,
+            "InsertObjects": InsertObject
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def remove(self,database,table,key):
+        param = {
+            "QueryType": "remove",
+            "Database": database,
+            "Datatable": table,
+            "Key": key
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def put(self,database,table,InsertObject):
+        param = {
+            "QueryType": "batch_put",
+            "Database": database,
+            "Datatable": table,
+            "InsertObjects": InsertObject
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Result"]

+ 18 - 0
config.json

@@ -0,0 +1,18 @@
+{
+  "metadata": {
+    "database": "db_time_data",
+    "url": "http://47.93.33.207:8890/metadata-web/services/Service1_WS?wsdl"
+  },
+  "building": "1101020002",
+  "dingding": "https://oapi.dingtalk.com/robot/send?access_token=f654c98a50435c95ee10ab012ba1550d8ff27d741d1484656d8e42f88a814b7c",
+  "points": {
+    "1202": "B2南新风机房浸水报警传感器",
+    "1201": "2F空调机房浸水报警传感器",
+    "1203": "B2北新风机房浸水报警传感器",
+    "1101": "制冷机房浸水报警传感器",
+    "9002": "楼顶南新风机房浸水报警传感器",
+    "9001": "楼顶北新风机房浸水报警传感器"
+
+  },
+  "funcid":11701
+}

+ 94 - 0
main.py

@@ -0,0 +1,94 @@
+import datetime
+import json,pymysql
+import os
+import time
+from MyUtils.ZillionUtil import ZillionUtil
+from MyUtils.MysqlUtils import MysqlUtils
+from MyUtils.Dingtalk import send_message_markdown
+import pytz
+
+
+
+def datetime_now():
+    # datetime_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
+    #容器时间
+    # tz = pytz.timezone('Asia/Shanghai')  # 东八区
+    datetime_now = datetime.datetime.fromtimestamp(int(time.time()),
+                                    pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
+    return datetime_now
+
+
+
+# 获取能耗数据
+def get_data_time(zillionUtil,hbase_database, hbase_table, building,meters,funcid):
+    Criteria = {
+        "building": building,
+        "meter": {
+            "in":meters
+        },
+        "funcid": funcid
+    }
+    datas = zillionUtil.select(hbase_database, hbase_table, Criteria)
+    return datas
+
+
+# with open("config.json", "r",encoding="utf-8") as f:
+#     data = json.load(f)
+#     hbase_database = data["metadata"]["database"]
+#     url = data["metadata"]["url"]
+#     building = data["building"]
+#     funcid = data["funcid"]
+#     points = data["points"]
+#     dingding = data["dingding"]
+
+
+
+hbase_database = os.getenv("hbase_database")
+url = os.getenv("url")
+building = os.getenv("building")
+dingding = os.getenv("dingding")
+funcid = os.getenv("dingding")
+points = os.getenv("dingding")
+
+#存报警
+alarm = {}
+zillionUtil = ZillionUtil(url)
+meters = [i for i in points]
+
+#存发送钉钉报警内容
+while True:
+    messages = []
+    datas = get_data_time(zillionUtil,hbase_database,"original_present",building,meters,funcid)
+    for i in datas:
+        value = i["data"]
+        meter = i["meter"]
+        receivetime = i["receivetime"]
+        name = points[meter]
+        if value == 1:
+            #如果表之前未产生报警,直接发送报警,并将点位存在报警池中
+            #如果之前已经有报警,不重复发送
+            if meter not in alarm:
+                message = (" - **空间名称:** %s \n" + " - **设备类名称:** 水浸传感器 \n" + " - **报警值:** %s \n" + " - **状态:** <font color=#FF0000>请及时查看处理</font> \n")%(name, value)
+                messages.append(message)
+                messages.append("___")
+                alarm[meter] = value
+        else:
+            #如果报警恢复,删除报警池内容,发送恢复报警
+            if meter in alarm:
+                if alarm[meter] == 1:
+                    alarm.pop(meter)
+                    message = (" - **空间名称:** %s \n" + " - **设备类名称:** 水浸传感器 \n" + " - **报警值:** %s \n" + " - **状态:** 报警已恢复 \n") % (name, value)
+                    messages.append(message)
+                    messages.append("___")
+
+    if messages:
+        messages_info = "\n".join(messages)
+        #如果有报警,发送钉钉
+        title = "## <font color=#FF0000>【中海财富中心】位移传感器报警</font> "
+        messages_info = title +"\n" + messages_info
+        print(messages_info)
+        send_message_markdown(title,messages_info,dingding)
+        messages.clear()
+    time.sleep(60)
+
+