#!/usr/bin/python3
import logging
import time
import flask
from flask import jsonify, request
import os
from ICM20948 import ICM20948DataStream, ICM20948, CompassOffsets
logging.basicConfig()
logging.root.setLevel(logging.NOTSET)
logging.basicConfig(level=logging.NOTSET)
logger = logging.getLogger("COMPASS SERVICE")
logger.setLevel("DEBUG")
def load_from_file():
if os.path.isfile('previous_mag_cal'):
with open('previous_mag_cal', 'r') as offsets:
raw = offsets.readline()
clean = raw.split('\n')[0].split(';')
offsets = CompassOffsets(float(clean[0]), float(clean[1]), float(clean[2]), float(clean[3]), float(clean[4]), float(clean[5]))
return offsets
return False
START_ON_LAUNCH = False
saved_offsets = load_from_file()
if saved_offsets:
OFFSETS = saved_offsets
START_ON_LAUNCH = True
# OFFSETS = None
COMPASS_COM = ICM20948DataStream("/dev/compass", baudrate=115200).start()
# COMPASS_COM = ICM20948DataStream("/dev/cu.SLAB_USBtoUART", baudrate=115200).start()
if START_ON_LAUNCH:
COMPASS = ICM20948(COMPASS_COM, pre_calibreted=OFFSETS).start()
else:
COMPASS = ICM20948(COMPASS_COM)
app = flask.Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return "
Compass server is running...
"
@app.route('/alive', methods=['POST'])
def alive():
logger.info(f"Returning alive")
return jsonify({'Success': True, 'is_running': COMPASS.running})
@app.route('/get_heading', methods=['POST', 'GET'])
def get_heading():
heading = COMPASS.read()
return jsonify({'Success': True, 'heading': heading})
@app.route('/start_compass', methods=['POST'])
def start_compass():
COMPASS.start()
return jsonify({'Success': True})
@app.route('/stop_compass', methods=['POST'])
def stop_compass():
COMPASS.stop()
return jsonify({'Success': True})
@app.route('/calibrate', methods=['POST'])
def calibrate():
if request.is_json:
content = request.get_json()
time_s = int(content.get('time', 60))
logger.info(f"Calibrating for {time_s} seconds")
logger.warning(f"This request will hang for {time_s} seconds, expect a timeout")
if COMPASS.running:
COMPASS.stop()
COMPASS.calibrate(calib_time=time_s)
COMPASS.start()
with open('previous_mag_cal', 'w+') as save_file:
nco = COMPASS.offsets
new_compass_offsets_str = f"{nco.min_x};{nco.max_x};{nco.min_y};{nco.max_y};{nco.hard_offset_x};{nco.hard_offset_y}"
save_file.writelines([new_compass_offsets_str])
return jsonify({'Success': True})
else:
return jsonify({'Error': 'Not JSON'})
@app.route('/set_offset', methods=['POST'])
def set_offset():
if request.is_json:
content = request.get_json()
offset = content.get('offset', 'nil')
assert offset != 'nil'
logger.info(f"Setting offset: {offset}")
COMPASS.set_offset(offset)
return jsonify({'Success': True})
else:
return jsonify({'Error': 'Not JSON'})
app.run(host='0.0.0.0', port=3333)