程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

ctwing電信AEP平台對接塗鴉智能雲平台python程序源碼

編輯: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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved