Advertisement
Guest User

Untitled

a guest
May 1st, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.73 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. import mysql.connector
  3. from datetime import datetime
  4.  
  5.  
  6. def fixDate(badDate): # CONVERTS THE DATE FORMAT
  7. day = badDate[0:2]
  8. month = badDate[2:4]
  9. year = badDate[4:6]
  10. return "20" + year + "-" + month + "-" + day
  11.  
  12.  
  13. def fixTime(badTime): # CONVERTS THE TIME FORMAT
  14. hour = badTime[0:2]
  15. min = badTime[2:4]
  16. sec = badTime[4:6]
  17. return hour + ":" + min + ":" + sec
  18.  
  19.  
  20. def DMSToD(input): # CONVERTS THE GPS FORMAT
  21. array = str(input).split(".")
  22. temp = str(int(array[1])/0.6).split(".")[0]
  23. return float(array[0] + "." + temp)
  24.  
  25. def overallMins(_):
  26. return _.hour * 60 + _.minute + _.second/60
  27.  
  28.  
  29. # def fixGPSInput(GPSInput): #EXTRACTS THE LONG AND LAT FROM THE MQTT MESSAGE
  30. # inp = GPSInput.split(",")
  31. # for i in range(3):
  32. # inp.pop()
  33. # time = fixTime(inp[0][6:12])
  34. # latitude = float(inp[2])/100
  35. # latitude = DMSToD(latitude)
  36. # if inp[3] == 'S':
  37. # latitude = latitude * -1
  38. # longitude = float(inp[4]) / 100
  39. # longitude = DMSToD(longitude)
  40. # if inp[5] == 'W':
  41. # longitude = longitude * -1
  42. # speed = inp[6]
  43. # angleTrue = inp[7]
  44. # date = fixDate(inp[8])
  45. # return date, time, str(latitude), str(longitude), speed, angleTrue
  46.  
  47.  
  48. def formatBatteryDiagnosticsBar(myResult, iteration):
  49. myResult = myResult[0]
  50. outputGraph = str(iteration*4+1) + ", "
  51. for i in range(len(myResult)):
  52. if i > 1:
  53. print(float(myResult[i]))
  54. outputGraph += str(float(myResult[i]))
  55. if i < len(myResult)-1:
  56. outputGraph += ', ' + str(i + iteration*4) + ', '
  57. return outputGraph
  58.  
  59.  
  60. def formatBatteryDiagnosticsLine(myResult):
  61. output = []
  62. baseTime = 0
  63. for i, data in enumerate(myResult):
  64. if i == 0:
  65. baseTime = overallMins(data[2])
  66. for j in range(4):
  67. output.append(str(overallMins(data[2]) - baseTime) + "," + str(float(data[j+3])) + ",")
  68. else:
  69. for j in range(4):
  70. output[j] += (str(overallMins(data[2]) - baseTime) + "," + str(float(data[j + 3])) + ",")
  71.  
  72. for j in range(4):
  73. output[j] = output[j][:-1]
  74.  
  75. return output
  76.  
  77.  
  78. def fixVoltageInput(voltageInput):
  79. inp = voltageInput.split(",")
  80. output = []
  81. for i in range(4):
  82. temp_upperbits = int(inp[2 * i + 1]) * 256
  83. temp_lowerbits = int(inp[2 * i])
  84. total = (temp_lowerbits + temp_upperbits)/10000
  85. total = '{:03.2f}'.format(total)
  86. output.append(total)
  87. return output
  88.  
  89.  
  90. def fixGPSInput(GPSInput):
  91. inp = GPSInput.split(",")
  92. output = []
  93. for i in range(2):
  94. temp_1 = int(inp[4 * i])
  95. temp_2 = int(inp[4 * i + 1]) * 256
  96. temp_3 = int(inp[4 * i + 2]) * 256 * 256
  97. temp_4 = int(inp[4 * i + 3]) * 256 * 256 * 256
  98. total = (temp_1 + temp_2 + temp_3 + temp_4)/100000
  99. total = total - 90 * (i+1)
  100. output.append(total)
  101. return output
  102.  
  103.  
  104. def on_connect(client, userdata, flags, rc): # CALLED AFTER CONNECTION TO MQTT SERVER
  105. # Callback from client receiving CONNACK
  106. print("Connected wth result code " + str(rc))
  107.  
  108. # subscribe here to ensure a lost connection will renew subscriptions
  109. client.subscribe("AEV/CARS/#")
  110.  
  111.  
  112. def storeBatteryData(voltages, code, carID):
  113. 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] + "');"
  114. print(insertMessage)
  115. myCursor.execute(insertMessage)
  116. conn.commit()
  117.  
  118. def pullBatteryData(carID, numPoints):
  119. newMsgGraphLine = []
  120. newMsgGraphBar = ''
  121. for i in range(4): # Bar Graph
  122. 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"
  123. myCursor.execute(pullMessage)
  124. myResult = myCursor.fetchall()
  125. newMsgGraphBar += formatBatteryDiagnosticsBar(myResult, i) + ", "
  126.  
  127. for i in range(4): # Line Graph
  128. 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
  129. myCursor.execute(pullMessage)
  130. myResult = myCursor.fetchall()
  131. newMsgGraphLine += formatBatteryDiagnosticsLine(myResult)
  132. return newMsgGraphBar, newMsgGraphLine
  133.  
  134.  
  135. def on_message(client, userdata, msg): # CALLED WHEN MESSAGE RECEIVED FROM MQTT SERVER
  136. # Callback for when a topic client is subscribed to receives a publish
  137. print("***\nMessage Received\n\nTopic:\t\t" + msg.topic + "\nPayload:\t" + str(msg.payload.decode('UTF-8')) + "\n***")
  138. topicList = msg.topic.split('/')
  139.  
  140. carID = topicList[2]
  141. innerTopic = topicList[3]
  142.  
  143. if innerTopic == "GPSDATA": # THIS HANDLES THE RECIEVING OF GPS DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
  144. fixedData = fixGPSInput(msg.payload.decode('UTF-8'))
  145. 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")
  146. insertMessage = "INSERT INTO diagnosticinfo (CarID, Latitude, Longitude, Time) VALUES ('" + carID + "'," + fixedData[2] + "," + fixedData[3] + ",'" + fixedData[0] + " " + fixedData[1] + "');"
  147. myCursor.execute(insertMessage)
  148. conn.commit()
  149.  
  150. 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
  151. duration = str(msg.payload.decode('UTF-8'))
  152. pullMessage = "SELECT CarID, InfoID, Latitude, Longitude FROM aev.diagnosticinfo WHERE Latitude is NOT NULL and CarID = '" + carID + "' ORDER BY InfoID DESC LIMIT " + duration
  153. print(pullMessage)
  154. myCursor.execute(pullMessage)
  155. myresult = myCursor.fetchall()
  156. print(myresult)
  157. postTopic = 'AEV/CARS/' + carID + '/LATLNG'
  158. for i in myresult[::-1]:
  159. newMsg = str(i[2]) + "," + str(i[3])
  160. client.publish(postTopic, newMsg)
  161. print('message sent')
  162.  
  163. 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
  164. dataType = topicList[4]
  165. if dataType == "BATTERY":
  166. newMsgGraphBar, newMsgGraphLine = pullBatteryData(carID, msg.payload)
  167. postTopic = 'AEV/CARS/' + carID + '/DIAGNOSTICSGRAPHSEND/BAR'
  168. client.publish(postTopic, newMsgGraphBar)
  169.  
  170. postTopic = 'AEV/CARS/' + carID + '/DIAGNOSTICSGRAPHSEND/LINE'
  171. sendMsg = ''
  172. for i, cellData in enumerate(newMsgGraphLine):
  173. if i == 0:
  174. sendMsg = "S,S" + str(i) + "," + str(len(cellData))
  175. else:
  176. sendMsg += ",S,S" + str(i) + "," + str(len(cellData))
  177.  
  178. client.publish(postTopic, sendMsg)
  179. print('message sent')
  180.  
  181. elif innerTopic == "CANDATA": #THIS HANDLES THE RECIEVING OF CAN DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
  182. componentCANID = topicList[4]
  183. if componentCANID == '100':
  184. voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
  185. storeBatteryData(voltages, 0, carID)
  186.  
  187. elif componentCANID == '104':
  188. voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
  189. storeBatteryData(voltages, 4, carID)
  190.  
  191. elif componentCANID == '108':
  192. voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
  193. storeBatteryData(voltages, 8, carID)
  194.  
  195. elif componentCANID == '112':
  196. voltages = fixVoltageInput(msg.payload.decode('UTF-8'))
  197. storeBatteryData(voltages, 12, carID)
  198.  
  199. elif componentCANID == '99':
  200. gps = fixGPSInput(msg.payload.decode('UTF-8'))
  201. print(gps)
  202. print("Fixed message contains:\nLatitude = " + str(gps[0]) + "\nLongitude = " + str(gps[1]) + "\n***\n")
  203. insertMessage = "INSERT INTO diagnosticinfo (CarID, Latitude, Longitude, Time) VALUES ('" + carID + "', '" + str(gps[0]) + "', '" + str(gps[1]) + "', '" + str(datetime.now())[:19] + "');"
  204. print(insertMessage)
  205. myCursor.execute(insertMessage)
  206. conn.commit()
  207.  
  208. elif innerTopic == "CONTROL": #THIS HANDLES THE RECIEVING OF CAN DATA FROM THE CARS AND PASSES IT INTO A MYSQL DB
  209. carProperty = topicList[4]
  210. if carProperty == 'SPEED':
  211. speed = msg.payload.decode('UTF-8')
  212. print("Fixed message contains:\nSPEED = " + speed + "\n***\n")
  213. insertMessage = "INSERT INTO controlinfo (CarID, User, Time, Header, Value) VALUES ('" + carID + "', 'TESTUSER', '" + str(datetime.now())[:19] + "', '" + carProperty + "', '" + speed + "');"
  214. print(insertMessage)
  215. myCursor.execute(insertMessage)
  216. conn.commit()
  217.  
  218.  
  219.  
  220.  
  221.  
  222.  
  223. conn = mysql.connector.connect(user="root", password="red23813", host="localhost", database="aev") #CREATES MYSQL CONNECTION
  224. myCursor = conn.cursor() #ENTER MYSQL CONNECTION
  225.  
  226. SERVER_IP = '192.168.15.31' #SPECIFY MQTT IP
  227. SERVER_PORT = 1883 #SPECIFY MQTT PORT
  228.  
  229. client = mqtt.Client() #CREATE MQTT CLIENT
  230. client.on_connect = on_connect #SET ON CONNECTION FUNCTION
  231. client.on_message = on_message #SET ON MESSAGE RECIEVED FUNCTION
  232.  
  233. client.username_pw_set('pythonClient', password='aev2020')
  234.  
  235. client.connect(SERVER_IP, SERVER_PORT, 60) #CONNECT TO THE MQTT SERVER
  236. forward=0
  237.  
  238. client.loop_forever() #MQTT LOOP
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement