-
Notifications
You must be signed in to change notification settings - Fork 1
/
bbblue_acq
executable file
·154 lines (134 loc) · 7.17 KB
/
bbblue_acq
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
#!/usr/bin/env python
import argparse
import configparser
import csv
import datetime
import os
import time
import mysql
from mysql.connector import connection
from app.sensors import AK8963 as msu
from app.sensors import BMP280 as barometer
from app.sensors import MPU9250 as imu
from app.utilities import current_timestamp
def main(write_csv=False, mysql_config=(None, None, None, None), verbosity=0):
if verbosity > 0:
print(f"Writing CSV is {write_csv}")
print(f"MySQL Config is {mysql_config}")
mpu9250 = imu.MPU9250()
ak8963 = msu.AK8963()
bmp280 = barometer.BMP280()
mpu9250.configMPU9250(imu.GFS_250, imu.AFS_8G)
ak8963.configAK8963(msu.AK8963_MODE_C100HZ, msu.AK8963_BIT_16)
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H%M%S')
output_dir = "data_collection"
os.makedirs(output_dir, exist_ok=True)
output_file = os.path.join(output_dir, f"data_12axis_{st}.csv")
if mysql_config is not None:
(db_ip, user, password, database) = mysql_config
database = "bb_" + database
print(f"** {current_timestamp()[0]} Attemping to open a MySQL with IP {db_ip} and username: {user}")
cnx = connection.MySQLConnection(user=user, password=password, host=db_ip)
print(f"** {current_timestamp()[0]} Writing to MySQL with connection {cnx}")
print(f"** {current_timestamp()[0]} Attemping to open a database called {database}")
try:
cnx.database = database
except mysql.connector.errors.ProgrammingError:
print(f"** {current_timestamp()[0]} DB {database} does not exist, creating a new one")
cnx.cmd_query(f"CREATE DATABASE {database};")
table_name = f"data_{datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H_%M_%S')}"
print(f"** {current_timestamp()[0]} Create a new table {table_name}")
cnx.cmd_query(f"CREATE TABLE `{database}`.`{table_name}` ( `key` INT NOT NULL AUTO_INCREMENT," +
"`timestamp` FLOAT NOT NULL," +
"`wall_time` VARCHAR(30) NULL," +
"`imu_temp` FLOAT NULL," +
"`imu_ax` FLOAT NOT NULL," +
"`imu_ay` FLOAT NULL," +
"`imu_az` FLOAT NULL," +
"`imu_gx` FLOAT NULL," +
"`imu_gy` FLOAT NULL," +
"`imu_gz` FLOAT NULL," +
"`msu_ax` FLOAT NULL," +
"`msu_ay` FLOAT NULL," +
"`msu_az` FLOAT NULL," +
"`baro_temp` FLOAT NULL," +
"`baro` FLOAT NULL," +
"PRIMARY KEY (`key`)," +
"UNIQUE INDEX `key_UNIQUE` (`key` ASC));")
if write_csv:
print(f"** {current_timestamp()[0]} Writing CSV to {output_file}")
csv_file_handle = open(output_file, 'w', newline='')
csv_writer = csv.writer(csv_file_handle, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(
["Data", "Timestamp", "Wall_Time", "MPU_Temp", "IMU_Ax", "IMU_Ay", "IMU_Az", "IMU_Gx", "IMU_Gy",
"IMU_Gz", "MSU_Ax", "MSU_Ay", "MSU_Az", "Baro_Temp", "Baro"])
i = 0
while True:
try:
st, ts = current_timestamp()
temp_imu = mpu9250.readTemperature()
acc = mpu9250.readAccel()
gyro = mpu9250.readGyro()
magnet = ak8963.readMagnet()
temperature_barometer = bmp280.readTemperature()[0]
barometric_pressure = bmp280.readPressure()
if verbosity > 1:
print(f"{ts:.2f} {st} MPU9250 Data: = {temp_imu:.1f} C ")
print(f"{ts:.2f} {st} \t{acc['x']:= 7.2f} G {acc['y']:= 7.2f} G {acc['z']:= 7.2f} G")
print(f"{ts:.2f} {st} \t{gyro['x']:= 7.2f} dps {gyro['y']:= 7.2f} dps {gyro['z']:= 7.2f} dps")
print(f"{ts:.2f} {st} AK8963 Data: = {magnet['x']:= 7.2f} {magnet['y']:= 7.2f} {magnet['z']:= 7.2f}")
print(f"{ts:.2f} {st} BMP280 Data: = {temperature_barometer:.1f} C ", end="")
print(f"{barometric_pressure:.1f} hPa")
if write_db:
sql = f"INSERT INTO `{database}`.`{table_name}`"
sql += " (`timestamp`, `wall_time`, `imu_temp`, `imu_ax`, `imu_ay`, `imu_az`, `imu_gx`, `imu_gy`,"
sql += " `imu_gz`, `msu_ax`, `msu_ay`, `msu_az`, `baro_temp`, `baro`)"
sql += f" VALUES ('{ts}', '{st}', '{temp_imu}', {acc['x']}, '{acc['y']}', '{acc['z']}',"
sql += f" '{gyro['x']}', '{gyro['y']}', '{gyro['z']}', '{magnet['x']}',"
sql += f" '{magnet['y']}', '{magnet['z']}', '{temperature_barometer}', '{barometric_pressure}');"
print(sql) if verbosity > 1 else None
cnx.cmd_query(sql)
csv_writer.writerow([i, ts, st, temp_imu, acc['x'], acc['y'], acc['z'], gyro['x'], gyro['y'], gyro['z'],
magnet['x'], magnet['y'], magnet['z'], temperature_barometer,
barometric_pressure]) if write_csv else None
i += 1
except KeyboardInterrupt:
print(f"** {st} KeyboardInterrupt received, closing file.")
csv_file_handle.close() if write_csv else None
cnx.close() if write_db else None
break
if __name__ == "__main__":
config_file = "config.ini"
if not os.path.isfile(config_file):
raise FileNotFoundError(f"** {current_timestamp()[0]} \"{config.ini}\" must exist under {os.getcwd()}")
cnf = configparser.ConfigParser()
cnf.read(config_file)
mysql_user = cnf["DEFAULT"].get("mysql_user")
mysql_password = cnf["DEFAULT"].get("mysql_password")
mysql_server = cnf["DEFAULT"].get("mysql_server")
instance_name = cnf["DEFAULT"].get("instance_name")
parser = argparse.ArgumentParser(description='Beagle Bone Blue Data Acquisition Wrapper')
parser.add_argument('-3', help='3 Axis Mode', action='store_true')
parser.add_argument('-6', help='6 Axis Mode', action='store_true')
parser.add_argument('-9', help='9 Axis Mode', action='store_true')
parser.add_argument('-12', help='12 Axis Mode', action='store_true')
parser.add_argument('-c', help='Write CSV', action='store_true')
parser.add_argument('-d', help='Write Database', action='store_true')
parser.add_argument('--csv', help='Specific CSV File Name Write')
parser.add_argument('--db-server-ip', help='Mysql Database Server IP')
parser.add_argument('--verbose', '-v', action='count')
parser.add_argument('-q', action='store_true', help='Quiet Mode')
args = vars(parser.parse_args())
write_csv = args['c']
write_db = args['d']
quiet = args['q']
verbosity = args['verbose'] if not quiet else 0
if not write_csv and not write_db:
verbosity = 1 if verbosity is None else verbosity
db_ip = None
mysql_config = (None, None, None, None)
if write_db:
db_ip = args["db_server_ip"] if args["db_server_ip"] is not None else mysql_server
mysql_config = (db_ip, mysql_user, mysql_password, instance_name)
main(write_csv=args['c'], mysql_config=mysql_config, verbosity=verbosity)