-
Notifications
You must be signed in to change notification settings - Fork 0
/
TPMSv2.5.py
290 lines (238 loc) · 8.92 KB
/
TPMSv2.5.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import time
import paho.mqtt.client as mqtt
import ssl
import logging
import subprocess
import sys
import serial
from datetime import datetime as dt
from paho.mqtt.client import connack_string as ack
class RS232Reader:
def __init__(self, port='/dev/rs232', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, xonxoff=False, rtscts=False, dsrdtr=False, timeout=10):
self.port = port
self.baudrate = baudrate
self.parity = parity
self.stopbits = stopbits
self.bytesize = bytesize
self.xonxoff = xonxoff
self.rtscts = rtscts
self.dsrdtr = dsrdtr
self.timeout = timeout
def read_serial_data(self):
global mystring
command_handshake = b'\xaa\x41\xa1\x06\x11\xa3'
command_alltyres = b'\xaa\x41\xa1\x07\x63\x00\xf6'
command_trailer = b'\xaa\x41\xa1\x07\x63\x20\x16'
ser = serial.Serial(
port=self.port,
baudrate=self.baudrate,
parity=self.parity,
stopbits=self.stopbits,
bytesize=self.bytesize,
xonxoff=self.xonxoff,
rtscts=self.rtscts,
dsrdtr=self.dsrdtr,
timeout=self.timeout
)
error_msg = None
try:
ser.setRTS(False)
ser.setDTR(False)
ser.write(command_handshake)
print('HANDSHAKE')
time.sleep(1)
a = ser.read(6)
handshake = ""
for c in a:
handshake = handshake + " " + hex(c)
print(handshake)
a = ""
handshake = ""
ser.close()
except Exception as e:
error_msg = f'Error with handshake request: {e}'
logger.info(error_msg)
try:
ser.open()
ser.write(command_alltyres)
print('ALL TYRES')
time.sleep(1.5)
x = ser.read_all()
mystring = x.decode('utf-8')
print(mystring)
except serial.SerialException as e:
error_msg = f'Error: Failed to read serial data. {str(e)}'
logger.info(error_msg)
finally:
ser.close()
return error_msg
def read_serial_data(self):
global mystring
command_handshake = b'\xaa\x41\xa1\x06\x11\xa3'
command_alltyres = b'\xaa\x41\xa1\x07\x63\x00\xf6'
command_trailer = b'\xaa\x41\xa1\x07\x63\x20\x16'
out = ''
ser = serial.Serial(
port=self.port,
baudrate=self.baudrate,
parity=self.parity,
stopbits=self.stopbits,
bytesize=self.bytesize,
xonxoff=self.xonxoff,
rtscts=self.rtscts,
dsrdtr=self.dsrdtr,
timeout=self.timeout
)
error_msg = None
try:
ser.setRTS(False)
ser.setDTR(False)
ser.write(command_handshake)
print('HANDSHAKE')
time.sleep(1)
a = ser.read(6)
handshake = ""
for c in a:
handshake = handshake + " " + hex(c)
print(handshake)
a = ""
handshake = ""
ser.close()
except Exception as e:
error_msg = f'Error with handshake request: {e}'
logger.info(error_msg)
try:
ser.open()
ser.write(command_alltyres)
print('ALL TYRES')
time.sleep(1.5)
x = ser.read(428)
mystring = ""
for c in x:
mystring = mystring + "," + hex(c)
print(mystring)
x = ""
except serial.SerialException as e:
error_msg = f'Error: Failed to read serial data. {str(e)}'
logger.info(error_msg)
finally:
ser.close()
return error_msg # This line should be inside the function
def run(self):
error_msg = self.read_serial_data()
return error_msg
class DeviceData:
def __init__(self):
self.imei = None
self.latitude = None
self.longitude = None
self.pub_message = None
def get_device_imei(self):
try:
returned_output = subprocess.check_output('gsmctl -i', shell=True)
decoded_imei = returned_output.decode("utf-8")
self.imei = decoded_imei.strip()
except Exception as e:
logger.info(f'Error: Failed to get device IMEI. {str(e)}')
def get_gps_latitude(self):
try:
returned_lat = subprocess.check_output('gpsctl -i', shell=True)
decoded_lat = returned_lat.decode("utf-8")
self.latitude = decoded_lat.strip()
except Exception as e:
logger.info(f'Error: Failed to get GPS latitude. {str(e)}')
def get_gps_longitude(self):
try:
returned_long = subprocess.check_output('gpsctl -x', shell=True)
decoded_long = returned_long.decode("utf-8")
self.longitude = decoded_long.strip()
except Exception as e:
logger.info(f'Error: Failed to get GPS longitude. {str(e)}')
def compile_pub_message(self, mystring):
if self.latitude is None or self.longitude is None or self.imei is None:
logger.info('Error: Missing device data.')
return None
index = 0
self.pub_message = f"{dt.now().strftime('%Y-%m-%d %H:%M:%S')};{self.latitude};{self.longitude};{self.imei};{mystring}"
def run(self, mystring):
self.get_device_imei()
self.get_gps_latitude()
self.get_gps_longitude()
self.compile_pub_message(mystring)
#------------- #V1 --------------------------------------------------------------------------------------
class MQTTClient:
def __init__(self, broker='broker.emqx.io', port=1883, topic='gometro/tpms/fleet1', keepalive=60, qos=1, max_retries=5, retry_delay=2):
self.broker = broker
self.port = port
self.topic = topic
self.keepalive = keepalive
self.qos = qos
self.max_retries = max_retries
self.retry_delay = retry_delay
self.client = mqtt.Client()
def establish_mqtt_connection(self):
connected = False
retry_count = 0
while not connected and retry_count < self.max_retries:
try:
self.client.connect(self.broker, self.port, self.keepalive)
connected = True
except Exception as e:
retry_count += 1
logger.info(f'Connection failed. Retrying in {self.retry_delay} seconds...')
time.sleep(self.retry_delay)
if not connected:
logger.info(f'Could not establish connection after {self.max_retries} attempts.')
else:
logger.info('Connection established successfully.')
def publish_message_with_retry(self, pub_message):
retries = self.max_retries
while retries > 0:
try:
(rc, mid) = self.client.publish(self.topic, pub_message, qos=self.qos)
if rc == mqtt.MQTT_ERR_SUCCESS:
logger.info(f'Message with ID {mid} published successfully with QoS {self.qos}')
pub_message = ""
mystring = ""
return True
else:
logger.info(f'Failed to publish message with QoS {self.qos}, Error code: {rc}')
except Exception as e:
logger.info(f'Error: Failed to publish message with QoS {self.qos}: {str(e)}')
retries -= 1
if retries > 0:
logger.info(f'Retrying in {self.retry_delay} seconds... ({retries} retries left)')
time.sleep(self.retry_delay)
else:
logger.info('Failed to publish message after all retries.')
return False
def run(self, pub_message, error_msg=None):
mqtt.Client.connected_flag = False
self.establish_mqtt_connection()
self.client.loop_start()
if error_msg:
self.publish_message_with_retry(error_msg)
self.publish_message_with_retry(pub_message)
self.client.loop_stop()
self.client.disconnect()
class SyslogHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
subprocess.run(['logger', '-t', 'TPMSv2.4', msg])
logger = logging.getLogger('TPMSv2.4')
logger.setLevel(logging.INFO) # You can change the log level as needed
logger.addHandler(SyslogHandler())
mystring = ""
if __name__ == '__main__':
rs232_reader = RS232Reader()
error_msg = rs232_reader.run()
if error_msg:
device_data = DeviceData()
device_data.run(mystring)
mqtt_client = MQTTClient()
mqtt_client.run(device_data.pub_message, error_msg)
else:
device_data = DeviceData()
device_data.run(mystring)
mqtt_client = MQTTClient()
mqtt_client.run(device_data.pub_message)