Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt
- import mysql.connector
- from datetime import datetime
- def fixDate(badDate): # CONVERTS THE DATE FORMAT
- day = badDate[0:2]
- month = badDate[2:4]
- year = badDate[4:6]
- return "20" + year + "-" + month + "-" + day
- def fixTime(badTime): # CONVERTS THE TIME FORMAT
- hour = badTime[0:2]
- min = badTime[2:4]
- sec = badTime[4:6]
- return hour + ":" + min + ":" + sec
- def DMSToD(input): # CONVERTS THE GPS FORMAT
- array = str(input).split(".")
- temp = str(int(array[1])/0.6).split(".")[0]
- return float(array[0] + "." + temp)
- def overallMins(_):
- return _.hour * 60 + _.minute + _.second/60
- # def fixGPSInput(GPSInput): #EXTRACTS THE LONG AND LAT FROM THE MQTT MESSAGE
- # inp = GPSInput.split(",")
- # for i in range(3):
- # inp.pop()
- # time = fixTime(inp[0][6:12])
- # latitude = float(inp[2])/100
- # latitude = DMSToD(latitude)
- # if inp[3] == 'S':
- # latitude = latitude * -1
- # longitude = float(inp[4]) / 100
- # longitude = DMSToD(longitude)
- # if inp[5] == 'W':
- # longitude = longitude * -1
- # speed = inp[6]
- # angleTrue = inp[7]
- # date = fixDate(inp[8])
- # return date, time, str(latitude), str(longitude), speed, angleTrue
- def formatBatteryDiagnosticsBar(myResult, iteration):
- myResult = myResult[0]
- outputGraph = str(iteration*4+1) + ", "
- for i in range(len(myResult)):
- if i > 1:
- print(float(myResult[i]))
- outputGraph += str(float(myResult[i]))
- if i < len(myResult)-1:
- outputGraph += ', ' + str(i + iteration*4) + ', '
- return outputGraph
- def formatBatteryDiagnosticsLine(myResult):
- output = []
- baseTime = 0
- for i, data in enumerate(myResult):
- if i == 0:
- baseTime = overallMins(data[2])
- for j in range(4):
- output.append(str(overallMins(data[2]) - baseTime) + "," + str(float(data[j+3])) + ",")
- else:
- for j in range(4):
- output[j] += (str(overallMins(data[2]) - baseTime) + "," + str(float(data[j + 3])) + ",")
- for j in range(4):
- output[j] = output[j][:-1]
- return output
- def fixVoltageInput(voltageInput):
- inp = voltageInput.split(",")
- output = []
- for i in range(4):
- temp_upperbits = int(inp[2 * i + 1]) * 256
- temp_lowerbits = int(inp[2 * i])
- total = (temp_lowerbits + temp_upperbits)/10000
- total = '{:03.2f}'.format(total)
- output.append(total)
- return output
- def fixGPSInput(GPSInput):
- inp = GPSInput.split(",")
- output = []
- for i in range(2):
- temp_1 = int(inp[4 * i])
- temp_2 = int(inp[4 * i + 1]) * 256
- temp_3 = int(inp[4 * i + 2]) * 256 * 256
- temp_4 = int(inp[4 * i + 3]) * 256 * 256 * 256
- total = (temp_1 + temp_2 + temp_3 + temp_4)/100000
- total = total - 90 * (i+1)
- output.append(total)
- return output
- def on_connect(client, userdata, flags, rc): # CALLED AFTER CONNECTION TO MQTT SERVER
- # Callback from client receiving CONNACK
- print("Connected wth result code " + str(rc))
- # subscribe here to ensure a lost connection will renew subscriptions
- client.subscribe("AEV/CARS/#")
- def storeBatteryData(voltages, code, carID):
- insertMessage = "INSERT INTO diagnosticinfo (CarID, BATTCELL" + str(code) + ", BATTCELL" + str(code + 1) + ", BATTCELL" + str(code + 2) + ", BATTCELL" + str(code + 3) + ", Time) VALUES ('" + carID + "', " + voltages[0] + ", " + voltages[1] + ", " + voltages[2] + ", " + voltages[3] + ", '" + str(datetime.now())[:19] + "');"
- print(insertMessage)
- myCursor.execute(insertMessage)
- conn.commit()
- def pullBatteryData(carID, numPoints):
- newMsgGraphLine = []
- newMsgGraphBar = ''
- for i in range(4): # Bar Graph
- pullMessage = "SELECT CarID, InfoID, BATTCELL" + str(i*4) + ", BATTCELL" + str(i*4+1) + ", BATTCELL" + str(i*4+2) + ", BATTCELL" + str(i*4+3) + " FROM aev.diagnosticinfo WHERE BATTCELL" + str(i*4) + " is NOT NULL and CarID = '" + carID + "' ORDER BY InfoID DESC LIMIT 1"
- myCursor.execute(pullMessage)
- myResult = myCursor.fetchall()
- newMsgGraphBar += formatBatteryDiagnosticsBar(myResult, i) + ", "
- for i in range(4): # Line Graph
- pullMessage = "SELECT CarID, InfoID, BATTCELL" + str(i*4) + ", BATTCELL" + str(i*4+1) + ", BATTCELL" + str(i*4+2) + ", BATTCELL" + str(i*4+3) + " FROM aev.diagnosticinfo WHERE BATTCELL" + str(i*4) + " is NOT NULL and CarID = '" + carID + "' ORDER BY InfoID ASC LIMIT " + numPoints
- myCursor.execute(pullMessage)
- myResult = myCursor.fetchall()
- newMsgGraphLine += formatBatteryDiagnosticsLine(myResult)
- return newMsgGraphBar, newMsgGraphLine
- def on_message(client, userdata, msg): # CALLED WHEN MESSAGE RECEIVED FROM MQTT SERVER
- # Callback for when a topic client is subscribed to receives a publish
- print("***\nMessage Received\n\nTopic:\t\t" + msg.topic + "\nPayload:\t" + str(msg.payload.decode('UTF-8')) + "\n***")
- topicList = msg.topic.split('/')
- carID = topicList[2]
- innerTopic = topicList[3]
- if innerTopic == "GPSDATA": # THIS HANDLES THE RECIEVING OF GPS DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
- fixedData = fixGPSInput(msg.payload.decode('UTF-8'))
- print("Fixed message contains:\nDate = " + fixedData[0] + "\t\tTime = " + fixedData[1] + "\nLatitude = " + fixedData[2] + "\tLongitude = " + fixedData[3] + "\nSpeed = " + fixedData[4] + "\t\t\tHeading (True) = " + fixedData[5] + "\n***\n")
- insertMessage = "INSERT INTO diagnosticinfo (CarID, Latitude, Longitude, Time) VALUES ('" + carID + "'," + fixedData[2] + "," + fixedData[3] + ",'" + fixedData[0] + " " + fixedData[1] + "');"
- myCursor.execute(insertMessage)
- conn.commit()
- elif innerTopic == "TRACE": # THIS HEARS REQUESTS FROM A WEBSITE OR APP ASKING FOR GPS DATA, PULLS IT FROM THE MYSQL DB AND SENDS IT TO THE REQUESTED CHANNEL
- duration = str(msg.payload.decode('UTF-8'))
- pullMessage = "SELECT CarID, InfoID, Latitude, Longitude FROM aev.diagnosticinfo WHERE Latitude is NOT NULL and CarID = '" + carID + "' ORDER BY InfoID DESC LIMIT " + duration
- print(pullMessage)
- myCursor.execute(pullMessage)
- myresult = myCursor.fetchall()
- print(myresult)
- postTopic = 'AEV/CARS/' + carID + '/LATLNG'
- for i in myresult[::-1]:
- newMsg = str(i[2]) + "," + str(i[3])
- client.publish(postTopic, newMsg)
- print('message sent')
- elif innerTopic == "DIAGNOSTICSREQUEST": #THIS HEARS REQUESTS FROM A WEBSITE OR APP ASKING FOR GPS DATA, PULLS IT FROM THE MYSQL DB AND SENDS IT TO THE REQUESTED CHANNEL
- dataType = topicList[4]
- if dataType == "BATTERY":
- newMsgGraphBar, newMsgGraphLine = pullBatteryData(carID, msg.payload)
- postTopic = 'AEV/CARS/' + carID + '/DIAGNOSTICSGRAPHSEND/BAR'
- client.publish(postTopic, newMsgGraphBar)
- postTopic = 'AEV/CARS/' + carID + '/DIAGNOSTICSGRAPHSEND/LINE'
- sendMsg = ''
- for i, cellData in enumerate(newMsgGraphLine):
- if i == 0:
- sendMsg = "S,S" + str(i) + "," + str(len(cellData))
- else:
- sendMsg += ",S,S" + str(i) + "," + str(len(cellData))
- client.publish(postTopic, sendMsg)
- print('message sent')
- elif innerTopic == "CANDATA": #THIS HANDLES THE RECIEVING OF CAN DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
- componentCANID = topicList[4]
- if componentCANID == '100':
- voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
- storeBatteryData(voltages, 0, carID)
- elif componentCANID == '104':
- voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
- storeBatteryData(voltages, 4, carID)
- elif componentCANID == '108':
- voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
- storeBatteryData(voltages, 8, carID)
- elif componentCANID == '112':
- voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
- storeBatteryData(voltages, 12, carID)
- elif componentCANID == '99':
- gps = fixGPSInput(msg.payload.decode('UTF-8'))
- print(gps)
- print("Fixed message contains:\nLatitude = " + str(gps[0]) + "\nLongitude = " + str(gps[1]) + "\n***\n")
- insertMessage = "INSERT INTO diagnosticinfo (CarID, Latitude, Longitude, Time) VALUES ('" + carID + "', '" + str(gps[0]) + "', '" + str(gps[1]) + "', '" + str(datetime.now())[:19] + "');"
- print(insertMessage)
- myCursor.execute(insertMessage)
- conn.commit()
- elif innerTopic == "CONTROL": #THIS HANDLES THE RECIEVING OF CAN DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
- carProperty = topicList[4]
- if carProperty == 'SPEED':
- speed = msg.payload.decode('UTF-8')
- print("Fixed message contains:\nSPEED = " + speed + "\n***\n")
- insertMessage = "INSERT INTO controlinfo (CarID, User, Time, Header, Value) VALUES ('" + carID + "', 'TESTUSER', '" + str(datetime.now())[:19] + "', '" + carProperty + "', '" + speed + "');"
- print(insertMessage)
- myCursor.execute(insertMessage)
- conn.commit()
- conn = mysql.connector.connect(user="root", password="red23813", host="localhost", database="aev") #CREATES MYSQL CONNECTION
- myCursor = conn.cursor() #ENTER MYSQL CONNECTION
- SERVER_IP = '192.168.15.31' #SPECIFY MQTT IP
- SERVER_PORT = 1883 #SPECIFY MQTT PORT
- client = mqtt.Client() #CREATE MQTT CLIENT
- client.on_connect = on_connect #SET ON CONNECTION FUNCTION
- client.on_message = on_message #SET ON MESSAGE RECIEVED FUNCTION
- client.username_pw_set('pythonClient', password='aev2020')
- client.connect(SERVER_IP, SERVER_PORT, 60) #CONNECT TO THE MQTT SERVER
- forward=0
- client.loop_forever() #MQTT LOOP
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement