-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathheading_publisher.py
executable file
·164 lines (137 loc) · 6.23 KB
/
heading_publisher.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
#!/usr/bin/env python
import argparse
import logging
import time
from threading import Lock
from threading import Thread
import cli_args as cli
from constants import SERIAL_PORT, BAUD_RATE, MQTT_HOST, LOG_LEVEL, DEVICE_ID
from mqtt_connection import MqttConnection, PAHO_CLIENT
from serial_reader import SerialReader
from utils import current_time_millis
from utils import setup_logging
from utils import sleep
import frc_utils
from frc_utils import COMMAND
from frc_utils import ENABLED
logger = logging.getLogger(__name__)
CALIBRATION_BY_VALUES = "9-DOF Sensor calibrated by values"
CALIBRATION_BY_LOG = "9-DOF Sensor calibrated by log"
HEADING_TOPIC = "heading_topic"
CALIB_TOPIC = "calib_topic"
CALIB_PUBLISH = "calib_publish"
CALIB_ENABLED = "calib_enabled"
MIN_PUBLISH = "min_publish"
PUBLISH_LOCK = "publish_lock"
stopped = False
calibrated_by_values = False
calibrated_by_log = False
current_heading = -1
last_heading_publish_time = -1
last_calib_publish_time = -1
def on_connect(mqtt_client, userdata, flags, rc):
logger.info("Connected with result code: %s", rc)
Thread(target=background_publisher, args=(userdata, userdata[MIN_PUBLISH])).start()
mqtt_client.subscribe(userdata[COMMAND])
# SerialReader calls this for every line read from Arduino
def fetch_data(val, userdata):
global current_heading, calibrated_by_values, calibrated_by_log, last_calib_publish_time
if "X:" not in val:
logger.info("Non-data: %s", val)
else:
try:
mqtt_client = userdata[PAHO_CLIENT]
vals = val.split("\t")
x_val = vals[0]
heading = round(float(x_val.split(": ")[1]), 1)
if heading != current_heading:
logger.debug(val)
current_heading = heading
publish_heading(mqtt_client, userdata[HEADING_TOPIC], heading, userdata)
if userdata[CALIB_ENABLED] and not calibrated_by_values:
# The arduino sketch includes a "! " prefix to SYS if the data is not calibrated (and thus not reliable)
if "! " in val:
nocalib_str = val[val.index("! "):]
logger.info("9-DOF Sensor not calibrated by log: %s", nocalib_str)
mqtt_client.publish(userdata[CALIB_TOPIC], payload=(nocalib_str.encode("utf-8")), qos=0)
calibrated_by_log = False
else:
if not calibrated_by_log:
msg = CALIBRATION_BY_LOG
logger.info(msg)
mqtt_client.publish(userdata[CALIB_TOPIC], payload=(msg.encode("utf-8")), qos=0)
calibrated_by_log = True
calib_str = vals[3]
calibs = calib_str.split(" ")
sys_calib = int(calibs[0].split(":")[1])
gyro_calib = int(calibs[1].split(":")[1])
mag_calib = int(calibs[2].split(":")[1])
acc_calib = int(calibs[3].split(":")[1])
if sys_calib == 3 and gyro_calib == 3 and mag_calib == 3 and acc_calib == 3:
msg = CALIBRATION_BY_VALUES
logger.info(msg)
mqtt_client.publish(userdata[CALIB_TOPIC], payload=(msg.encode("utf-8")), qos=0)
calibrated_by_values = True
elif current_time_millis() - last_calib_publish_time > userdata[CALIB_PUBLISH] * 1000:
mqtt_client.publish(userdata[CALIB_TOPIC], payload=(calib_str.encode("utf-8")), qos=0)
last_calib_publish_time = current_time_millis()
except IndexError:
logger.info("Formatting error: %s", val)
def background_publisher(userdata, min_publish_secs):
client = userdata[PAHO_CLIENT]
heading_topic = userdata[HEADING_TOPIC]
while not stopped:
time.sleep(.5)
elapsed_time = current_time_millis() - last_heading_publish_time
if elapsed_time > min_publish_secs * 1000 and current_heading != -1:
publish_heading(client, heading_topic, current_heading, userdata)
def publish_heading(client, topic, heading, userdata):
global last_heading_publish_time
if not userdata[ENABLED]:
return
elapsed_time = current_time_millis() - last_heading_publish_time
if elapsed_time < 75:
return
publish_lock = userdata[PUBLISH_LOCK]
with publish_lock:
client.publish(topic, payload=(str(heading).encode("utf-8")), qos=0)
last_heading_publish_time = current_time_millis()
if __name__ == "__main__":
# Parse CLI args
parser = argparse.ArgumentParser()
cli.mqtt_host(parser)
cli.device_id(parser)
cli.serial_port(parser)
cli.baud_rate(parser)
parser.add_argument("--mpt", dest=MIN_PUBLISH, default=1, type=int, help="Minimum publishing time secs [1]")
parser.add_argument("--calib", dest=CALIB_ENABLED, default=False, action="store_true",
help="Enable calibration publishing[false]")
parser.add_argument("--cpt", dest=CALIB_PUBLISH, default=3, type=int, help="Calibration publishing time secs [3]")
cli.verbose(parser)
args = vars(parser.parse_args())
# Setup logging
setup_logging(level=args[LOG_LEVEL])
userdata = {HEADING_TOPIC: "heading/degrees",
CALIB_TOPIC: "heading/calibration",
COMMAND: "heading/command",
ENABLED: True,
PUBLISH_LOCK: Lock(),
CALIB_PUBLISH: args[CALIB_PUBLISH],
CALIB_ENABLED: args[CALIB_ENABLED],
MIN_PUBLISH: args[MIN_PUBLISH]},
with SerialReader(func=fetch_data,
userdata=userdata,
port=SerialReader.lookup_port(args[DEVICE_ID]) if args.get(DEVICE_ID) else args[SERIAL_PORT],
baudrate=args[BAUD_RATE],
debug=True):
with MqttConnection(hostname=(args[MQTT_HOST]),
userdata=userdata,
on_connect=on_connect,
on_message=frc_utils.on_message):
try:
sleep()
except KeyboardInterrupt:
pass
finally:
stopped = True
logger.info("Exiting...")