栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

ctwing电信AEP平台对接涂鸦智能云平台python程序源码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ctwing电信AEP平台对接涂鸦智能云平台python程序源码

项目描述:
将无线倾角传感器、无线电流传感器数据对接到涂鸦云平台。
源代码:

 """
    www.daq-iot.com
    数采物联网版权所有,非授权禁止商业目的使用
 """
import base64
import hashlib
import hmac
import traceback
import ssl
import paho.mqtt.client as mqtt
import json
import os
import ssl
import time
import openpyxl
import pandas as pd
from flask import Flask
from flask import request


app = Flask(__name__)
def logintime():
    return int(time.time())
def datatime():
    return int(round(time.time() * 1000))
def getdeviceid(m):
    file_name = ".\涂鸦云对接目录.xlsx"
    file_result = os.path.join(file_name)
    wb = openpyxl.load_workbook(file_result)  # 首先获取excel文件生成对象wb 使用openpyxl.load_workbook 方法
    lie = pd.DataFrame(pd.read_excel(file_result))
    sheet = wb.active
    for i in range(1, len(lie) + 2):
        cell = sheet.cell(row=i, column=1)
        cv = cell.value
        if cv ==  m:
            dev = sheet.cell(row=i, column=2)
            dv = dev.value
            return dv
def getdeviceselect(m):
    file_name = ".\涂鸦云对接目录.xlsx"
    file_result = os.path.join(file_name)
    wb = openpyxl.load_workbook(file_result)  # 首先获取excel文件生成对象wb 使用openpyxl.load_workbook 方法
    lie = pd.DataFrame(pd.read_excel(file_result))
    sheet = wb.active
    for i in range(1, len(lie) + 2):
        cell = sheet.cell(row=i, column=1)
        cv = cell.value
        if cv == m:
            dev = sheet.cell(row=i, column=3)
            dv = dev.value
            return dv
def getdevtype(m):
    file_name = ".\涂鸦云对接目录.xlsx"
    file_result = os.path.join(file_name)
    wb = openpyxl.load_workbook(file_result)  # 首先获取excel文件生成对象wb 使用openpyxl.load_workbook 方法
    lie = pd.DataFrame(pd.read_excel(file_result))
    sheet = wb.active
    for i in range(1, len(lie) + 2):
        cell = sheet.cell(row=i, column=1)
        cv = cell.value
        if cv == m:
            dev = sheet.cell(row=i, column=4)
            dv = dev.value
            return dv

def hmac_sha256(key, value):
    """
    hmacsha256加密
    :param key:
    :param value: 加密字符串
    :return: 加密结果转换为16进制字符串,并大写
    """
    message = value.encode("utf-8")
    return hmac.new(key.encode("utf-8"), message, digestmod=hashlib.sha256).hexdigest()

@app.route("/he/data/push/global", methods=['POST'])
def he_data_push_global():
    try:
        print('**** Receive Post Data *****')

        data = request.get_data()

        data= data.decode("utf-8")
        data=data.replace("'",'"')
        json_data = json.loads(data)
        print(json_data)
        IMEI=json_data["IMEI"]
        deviceid = getdeviceid(IMEI)
        deviceselect = getdeviceselect(IMEI)
        if getdevtype(IMEI)=='倾斜':
            time1=logintime()
            time2=datatime()
            # print(json_data)
            # data=data[2:-1]
            data=json_data["payload"]
            # print(data)
            data = str(data).replace("'", '"')
            data=json.loads(data)
            # print(data)
            data=data["APPdata"]
            # print(str(data))

            debs64=base64.b64decode(data)
            debs64=str(debs64)[11:-1]
            debs64=debs64.replace("{",'{"')
            debs64 = debs64.replace(",", '","')
            debs64 = debs64.replace(":", '":"')
            debs64 = debs64.replace("}", '"}')
            debs64=json.loads(debs64)


            jiaodu=int(debs64["angle"])/10
            dianliang=debs64["BT"]



            realdata={
            "msgId":"45lkj3551234001",
            "time":time2,
            "data":{
                "jiaodu":{
                    "value":int(jiaodu*10),
                    "time": time2
                },
                "dianliang":{
                      "value":int(float(dianliang)*10),
                      'time': time2
                }
            }
            }
        elif getdevtype(IMEI) == '电流':
             time1 = logintime()
             time2 = datatime()
             payload = json_data['payload']['serviceData']
             dianliu=payload["IntData2"]
             dianlaing=payload["VoltageCur"]
             realdata = {
                "msgId": "45lkj3551234001",
                "time": time2,
                "data": {
                    "dianliu": {
                        "value": dianliu,
                        "time": time2
                    },
                    "dianliang": {
                        "value": dianlaing,
                        'time': time2
                    }
                }
            }

        print(realdata)
        TASK_TOPIC = 'tylink/%s/thing/property/report'%deviceid  # 客户端发布消息主题
        # print(TASK_TOPIC)

        client_id = "tuyalink_%s"%deviceid
        username="%s|signMethod=hmacSha256,timestamp=%s,secureMode=1,accessType=1"%(deviceid,time1)
        value="deviceId={},timestamp={},secureMode=1,accessType=1".format(deviceid,time1)
        password=hmac_sha256(deviceselect,value)
        # print(value)
        # print(client_id,username,password)
        """
        client_id是连接到代理。如果client_id的长度为零或为零,则行为为由使用的协议版本定义。如果使用MQTT v3.1.1,
        那么一个零长度的客户机id将被发送到代理,代理将被发送为客户端生成一个随机变量。如果使用MQTT v3.1,那么id将是
        随机生成的。在这两种情况下,clean_session都必须为True。如果这在这种情况下不会产生ValueError。
        注意:一般情况下如果客户端服务端启用两个监听那么客户端client_id 不能与服务器相同,如这里用时间"20190222142358"作为它的id,
        如果与服务器id相同,则无法接收到消息
        """
        client = mqtt.Client(client_id, transport='tcp')
        client.username_pw_set(username, password)
        client.tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,
               tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
        client.connect("m1.tuyacn.com", 8883, 60)  # 此处端口默认为1883,通信端口期keepalive默认60


        # client.username_pw_set("", "")
        # client.connect("127.0.0.1", 1883, 5)
        client.loop_start()

        """
        客户端发布消息
        :param message: 消息主体
        :return:
        """
        # publish(主题:Topic; 消息内容)
        client.publish(TASK_TOPIC, json.dumps(realdata, ensure_ascii=False))
        print(realdata)
        print("Successful send message!")

        return 'POST SUCCESS'
    except:
        print(traceback.format_exc())
        return repr(Exception)
        pass

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=8002)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990833.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号