获取数据调质设备数据api 推送钉钉 分两脚本(Fbox)

Fbox

1.写入数据库

import requests
import json
from requests.auth import HTTPBasicAuth
import pymysql
import time,datetime


class GetFBoxData(object):


    conn = pymysql.connect(host="修改.30", port=64825修改, user="root修改", passwd="修改",
                           db="data_warehouse修改")
    cursor = conn.cursor()

    def get_access_token(self):
        url = r'https://account.flexem.com/core/connect/token'

        body = {
            "scope": "fbox",
            "client_id": "修改",
            "client_secret": "ae36040b49e64bed974修改",
            "grant_type": "client_credentials"

        }

        res = requests.post(url, data=body)
        access_token = res.json()
        access_token = access_token['access_token']
        return access_token

    def get_channelID(self, areaID, access_key):
        """
        获取通道ID
        """
        url = r'http://fbcs101.fbox360.com/api/v2/box/{}/hdataitems'.format(str(areaID))

        headers = {
            "Authorization": "Bearer "
        }

        headers['Authorization'] = "Bearer {}".format(access_key)

        res = requests.get(url=url, headers=headers)
        data = res.json()
        data = data[0]['channels']
        channelList = []
        for i in data:
            channelDir = {}
            channelDir['uid'] = i['uid']
            channelDir['name'] = i['name']
            channelList.append(channelDir)
        return channelList

    def get_hisData(self, access_key, uid):
        """
        历史数据
        """
        area_url = r'http://fbhs1.fbox360.com/api/v2/hdata/get'
        headers = {
            "Authorization": "Bearer ",
        }
        channel_id = []
        body = {
            "type": 0,
            "ids": channel_id,
            "g": 0,
            # "begin": "1687910400000",
            # "end": "1687914424000",
            "tr": 3,
            "limit": -1,
            "tz": "Asia/Shanghai"
        }

        headers['Authorization'] = "Bearer {}".format(access_key)

        channel_id.append(str(uid))
        res = requests.post(url=area_url, json=body, headers=headers)
        # {'rows': []}
        res_info = res.json()
        if res_info['rows'] == []:
            resIndo = None
        else:
            resIndo = res_info['rows'][-1]
        return resIndo

    def insertData(self,value,key,insertList,hisT,nowTime):
        sql = 'insert into ods_fbox_hisdata (station_id,station_name,air_inlet_pressure,outlet_pressur,oxygen_content_analyzer,' \
                                            'clockwise_air_flow_rate,accumulated_air_flow_rate,instantaneous_gas_flow_rate,accumulated_gas_flow_rate,data_time,system_time) ' \
              'values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
        self.cursor.execute(sql,(str(value),key,insertList[0],insertList[1],insertList[2],insertList[3],insertList[4],insertList[5],insertList[6],hisT,nowTime))
        self.conn.commit()

if __name__ == '__main__':
    fBoxData = GetFBoxData()
    access_token = fBoxData.get_access_token()
    nowTime = datetime.datetime.now()
    # print(nowTime)
    areaList = {
        "修改面山": "修改4795109",
        "修改场": "修改4057872462",
        "修改三井": "修改805083",
        "修改七井": "修改061808079",
        "修改气站": "修改5941826523",
        "修改十四井": "修改0242173079",
        "修改加": "修改20618019"
    }

    for key, value in areaList.items():
        # print(key)
        channelInfo = fBoxData.get_channelID(value, access_token)
        insertList = []
        for i in channelInfo[:-1]:
            uid = i['uid']
            name = i['name']
            # print(uid, name)
            # if '进口压力' in name:
            hisData = fBoxData.get_hisData(access_token, uid)
            hisT = hisData['t']
            hisC = hisData['c'][0]
            hisT = datetime.datetime.fromtimestamp(hisT/1000)
            # print(hisT, hisC)
            insertList.append(hisC)
        print(value,key,insertList,hisT,nowTime)
        fBoxData.insertData(value,key,insertList,hisT,nowTime)
    fBoxData.conn.close()
    # fBoxData.conn.close()
    # fBoxData.get_hisData(access_token)

2.从数据库中判断,并推送钉钉

import datetime
import json
import requests
import hmac
import hashlib
import base64
import time
import urllib.parse

import pymysql

conn = pymysql.connect(host="修改30", port=648修改, user="root修改", passwd="修改",
                       db="data_warehouse修改")
cursor = conn.cursor()

# 钉钉推送
def send_dingding(content):
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=ad3fab502275cb46dbfb1221572cf1bd5d81修改'  # 钉钉机器人webhook

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC3863cc7fac06ceb0265d13c72361bb8c修改'  # 钉钉机器人秘钥
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    url = webhook + '&timestamp=' + timestamp + '&sign=' + sign

    headers = {'Content-Type': 'application/json'}
    data = {
        "msgtype": "text",
        "text": {
            "content": content
        },
        "isAtAll": True}  # 这是判断是否要全员艾特
    # 发送post请求
    res = requests.post(url, data=json.dumps(data), headers=headers)

# 查询数据库数据
def getDate():
    """
    获取最新整点数据  传给压力检查和时间检查函数
    """
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:00:00')
    sql = 'select station_name,air_inlet_pressure,data_time,system_time from ods_fbox_hisdata where system_time >= "{}"'.format(str(nowTime))
    cursor.execute(sql)
    res = cursor.fetchall()
    return res

# 判断压力
def checkPressure(station_name, air_inlet_pressure, data_time):
    """
    压力检查  如果压力小于0则报警
    """
    nowTime = datetime.datetime.now()
    if air_inlet_pressure <= 0:
        message = str(nowTime) +str("    ")+ station_name + '出现空气进口压力数据异常,请管理员查看!'+str("    ")+'空气进口压力数据为:'+str(air_inlet_pressure)+str("    ")+'最近回传时间为:'+str(data_time)
        return message
    else:
        pass

def checkTime(station_name, air_inlet_pressure, data_time, system_time):
    """
    时间检查  如果回传采集时间 减去 数据回传时间 大于 半个小时1800秒 则报警
    """
    now = datetime.datetime.now()
    time_difference = (system_time-data_time).seconds
    if time_difference >= 1800:
        message = str(now) +str("    ")+ station_name + '出现回传数据异常,请管理员查看!'+str("    ")+'最近回传时间为:'+str(data_time)
        return message
    else:
        pass

if __name__ == '__main__':
    data = getDate()
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if data == ():
        sys_message = str(nowTime) + str("    ") + "数据采集异常!请管理员自行查看系统数据并联系数据中心"
        send_dingding(sys_message)
    else:
        for i in data:
            station_name = i[0]
            air_inlet_pressure = i[1]
            data_time = i[2]
            system_time = i[3]
            pressure_message = checkPressure(station_name, air_inlet_pressure, data_time)
            if pressure_message is not None:
                send_dingding(pressure_message)
            time_message = checkTime(station_name, air_inlet_pressure, data_time, system_time)
            if time_message is not None:
                send_dingding(time_message)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑森林法则

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值