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

Ctwing Telecom AEP platform docking graffiti intelligent cloud platform Python program source code

編輯:Python

Project description :
Connect the wireless inclination sensor 、 The wireless current sensor data pair is connected to the graffiti cloud platform .
Source code :

 """ www.daq-iot.com Data acquisition Internet of things all rights reserved , Unauthorized use for commercial purposes is prohibited """
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 = ".\\ Graffiti cloud docking directory .xlsx"
file_result = os.path.join(file_name)
wb = openpyxl.load_workbook(file_result) # First of all get excel File generation objects wb Use openpyxl.load_workbook Method 
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 = ".\\ Graffiti cloud docking directory .xlsx"
file_result = os.path.join(file_name)
wb = openpyxl.load_workbook(file_result) # First of all get excel File generation objects wb Use openpyxl.load_workbook Method 
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 = ".\\ Graffiti cloud docking directory .xlsx"
file_result = os.path.join(file_name)
wb = openpyxl.load_workbook(file_result) # First of all get excel File generation objects wb Use openpyxl.load_workbook Method 
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 encryption :param key: :param value: Encrypted string :return: Convert encrypted results to 16 Base string , And capitalize """
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)==' tilt ':
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) == ' electric current ':
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 # The client publishes the message subject 
# 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 Yes connect to proxy . If client_id The length of is zero or zero , The behavior is defined by the protocol version used . If you use MQTT v3.1.1, So a zero length client id Will be sent to the agent , The proxy will be sent to generate a random variable for the client . If you use MQTT v3.1, that id It will be Randomly generated . In both cases ,clean_session All must be True. If this doesn't happen in this case ValueError. Be careful : In general, if the client server enables two listeners, the client client_id Cannot be the same as the server , If we use time here "20190222142358" As it is id, If with the server id identical , The message cannot be received """
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) # The default port here is 1883, Communication port period keepalive Default 60
# client.username_pw_set("", "")
# client.connect("127.0.0.1", 1883, 5)
client.loop_start()
""" The client publishes the message :param message: Message body :return: """
# publish( The theme :Topic; The message content )
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