adxl345: Support querying accelerometer data from webhooks interface

Signed-off-by: Kevin O'Connor <kevin@koconnor.net>
This commit is contained in:
Kevin O'Connor 2021-08-12 01:05:09 -04:00
parent d87f7a77c3
commit dd95f80d9d
1 changed files with 109 additions and 63 deletions

View File

@ -1,10 +1,10 @@
# Support for reading acceleration data from an adxl345 chip
#
# Copyright (C) 2020 Kevin O'Connor <kevin@koconnor.net>
# Copyright (C) 2020-2021 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging, time, collections, multiprocessing, os
from . import bus
import logging, time, collections, threading, multiprocessing, os
from . import bus, motion_report
# ADXL345 registers
REG_DEVID = 0x00
@ -30,24 +30,33 @@ Accel_Measurement = collections.namedtuple(
# Helper class to obtain measurements
class ADXL345QueryHelper:
def __init__(self, printer, chip, axes_map):
def __init__(self, printer, chip, cconn):
self.printer = printer
self.chip = chip
self.axes_map = axes_map
self.cconn = cconn
print_time = printer.lookup_object('toolhead').get_last_move_time()
self.request_start_time = self.request_end_time = print_time
self.raw_samples = None
self.samples = []
self.drops = self.overflows = 0
self.start2_time = 0.
self.time_per_sample = self.start_range = self.end_range = 0.
def finish_measurements(self):
self.chip._finish_measurements()
toolhead = self.printer.lookup_object('toolhead')
self.request_end_time = toolhead.get_last_move_time()
toolhead.wait_moves()
self.cconn.finalize()
toolhead.dwell(0.200)
toolhead.wait_moves()
self._setup_data(*self.chip.final_results) # XXX
def get_stats(self):
return ("drops=%d,overflows=%d"
",time_per_sample=%.9f,start_range=%.6f,end_range=%.6f"
% (self.drops, self.overflows,
self.time_per_sample, self.start_range, self.end_range))
def _setup_data(self, raw_samples, end_sequence, overflows,
def _setup_data(self, end_sequence, overflows,
start1_time, start2_time, end1_time, end2_time):
raw_samples = self.cconn.get_messages()
if not raw_samples or not end_sequence:
return
self.raw_samples = raw_samples
@ -55,32 +64,26 @@ class ADXL345QueryHelper:
self.start2_time = start2_time
self.start_range = start2_time - start1_time
self.end_range = end2_time - end1_time
self.total_count = (end_sequence - 1) * 8 + len(raw_samples[-1][1]) // 6
self.total_count = raw_samples[-1]['params']['data'][-1][0] + 1
total_time = end2_time - start2_time
self.time_per_sample = time_per_sample = total_time / self.total_count
self.seq_to_time = time_per_sample * 8.
actual_count = sum([len(data)//6 for _, data in raw_samples])
self.time_per_sample = total_time / self.total_count
actual_count = sum([len(m['params']['data']) for m in raw_samples])
self.drops = self.total_count - actual_count
def decode_samples(self):
if not self.raw_samples:
return self.samples
(x_pos, x_scale), (y_pos, y_scale), (z_pos, z_scale) = self.axes_map
actual_count = 0
count = 0
self.samples = samples = [None] * self.total_count
for seq, data in self.raw_samples:
d = bytearray(data)
count = len(data)
sdata = [(d[i] | (d[i+1] << 8)) - ((d[i+1] & 0x80) << 9)
for i in range(0, count-1, 2)]
seq_time = self.start2_time + seq * self.seq_to_time
for i in range(count//6):
samp_time = seq_time + i * self.time_per_sample
x = sdata[i*3 + x_pos] * x_scale
y = sdata[i*3 + y_pos] * y_scale
z = sdata[i*3 + z_pos] * z_scale
samples[actual_count] = Accel_Measurement(samp_time, x, y, z)
actual_count += 1
del samples[actual_count:]
for msg in self.raw_samples:
for seq, x, y, z in msg['params']['data']:
samp_time = self.start2_time + seq * self.time_per_sample
if samp_time < self.request_start_time:
continue
if samp_time > self.request_end_time:
break
samples[count] = Accel_Measurement(samp_time, x, y, z)
count += 1
del samples[count:]
return self.samples
def write_to_file(self, filename):
def write_impl():
@ -180,13 +183,15 @@ class ADXLCommandHelper:
val = gcmd.get("VAL", minval=0, maxval=255, parser=lambda x: int(x, 0))
self.chip.set_reg(reg, val)
MIN_MSG_TIME = 0.100
# Printer class that controls ADXL345 chip
class ADXL345:
def __init__(self, config):
self.printer = config.get_printer()
ADXLCommandHelper(config, self)
self.query_rate = 0
self.last_tx_time = 0.
self.last_sequence = 0
am = {'x': (0, SCALE), 'y': (1, SCALE), 'z': (2, SCALE),
'-x': (0, -SCALE), '-y': (1, -SCALE), '-z': (2, -SCALE)}
axes_map = config.getlist('axes_map', ('x','y','z'), count=3)
@ -197,8 +202,8 @@ class ADXL345:
if self.data_rate not in QUERY_RATES:
raise config.error("Invalid rate parameter: %d" % (self.data_rate,))
# Measurement storage (accessed from background thread)
self.lock = threading.Lock()
self.raw_samples = []
self.last_sequence = 0
self.samples_start1 = self.samples_start2 = 0.
# Setup mcu sensor_adxl345 bulk query code
self.spi = bus.MCU_SPI_from_config(config, 3, default_speed=5000000)
@ -212,6 +217,15 @@ class ADXL345:
mcu.register_config_callback(self._build_config)
mcu.register_response(self._handle_adxl345_start, "adxl345_start", oid)
mcu.register_response(self._handle_adxl345_data, "adxl345_data", oid)
# API server endpoints
self.api_dump = motion_report.APIDumpHelper(
self.printer, self._api_update, self._api_startstop, 0.100)
self.name = "default"
if len(config.get_name().split()) > 1:
self.name = config.get_name().split()[1]
wh = self.printer.lookup_object('webhooks')
wh.register_mux_endpoint("adxl345/dump_adxl345", "sensor", self.name,
self._handle_dump_adxl345)
def _build_config(self):
self.query_adxl345_cmd = self.mcu.lookup_command(
"query_adxl345 oid=%c clock=%u rest_ticks=%u",
@ -223,20 +237,6 @@ class ADXL345:
oid=self.oid, cq=self.spi.get_command_queue())
def _clock_to_print_time(self, clock):
return self.mcu.clock_to_print_time(self.mcu.clock32_to_clock64(clock))
def _handle_adxl345_start(self, params):
self.samples_start1 = self._clock_to_print_time(params['start1_clock'])
self.samples_start2 = self._clock_to_print_time(params['start2_clock'])
def _handle_adxl345_data(self, params):
last_sequence = self.last_sequence
sequence = (last_sequence & ~0xffff) | params['sequence']
if sequence < last_sequence:
sequence += 0x10000
self.last_sequence = sequence
raw_samples = self.raw_samples
if len(raw_samples) >= 300000:
# Avoid filling up memory with too many samples
return
raw_samples.append((sequence, params['data']))
def _convert_sequence(self, sequence):
sequence = (self.last_sequence & ~0xffff) | sequence
if sequence < self.last_sequence:
@ -255,8 +255,40 @@ class ADXL345:
"This is generally indicative of connection problems "
"(e.g. faulty wiring) or a faulty adxl345 chip." % (
reg, val, stored_val))
# Measurement collection
def is_measuring(self):
return self.query_rate > 0
def _handle_adxl345_start(self, params):
self.samples_start1 = self._clock_to_print_time(params['start1_clock'])
self.samples_start2 = self._clock_to_print_time(params['start2_clock'])
def _handle_adxl345_data(self, params):
with self.lock:
self.raw_samples.append(params)
def _extract_samples(self, raw_samples):
# Load variables to optimize inner loop below
(x_pos, x_scale), (y_pos, y_scale), (z_pos, z_scale) = self.axes_map
last_sequence = self.last_sequence
# Process every message in raw_samples
count = 0
samples = [None] * (len(raw_samples) * 8)
for params in raw_samples:
seq = (last_sequence & ~0xffff) | params['sequence']
if seq < last_sequence:
seq += 0x10000
last_sequence = seq
d = bytearray(params['data'])
len_d = len(d)
sdata = [(d[i] | (d[i+1] << 8)) - ((d[i+1] & 0x80) << 9)
for i in range(0, len_d-1, 2)]
for i in range(len_d // 6):
x = round(sdata[i*3 + x_pos] * x_scale, 6)
y = round(sdata[i*3 + y_pos] * y_scale, 6)
z = round(sdata[i*3 + z_pos] * z_scale, 6)
samples[count] = (seq * 8 + i, x, y, z)
count += 1
self.last_sequence = last_sequence
del samples[count:]
return samples
def _start_measurements(self):
if self.is_measuring():
return
@ -267,54 +299,68 @@ class ADXL345:
raise self.printer.command_error("Invalid adxl345 id (got %x vs %x)"
% (dev_id, ADXL345_DEV_ID))
# Setup chip in requested query rate
clock = 0
if self.last_tx_time:
clock = self.mcu.print_time_to_clock(self.last_tx_time)
self.set_reg(REG_POWER_CTL, 0x00, minclock=clock)
self.set_reg(REG_POWER_CTL, 0x00)
self.set_reg(REG_DATA_FORMAT, 0x0B)
self.set_reg(REG_FIFO_CTL, 0x00)
self.set_reg(REG_BW_RATE, QUERY_RATES[self.data_rate])
self.set_reg(REG_FIFO_CTL, 0x80)
# Setup samples
print_time = self.printer.lookup_object('toolhead').get_last_move_time()
self.raw_samples = []
self.last_sequence = 0
systime = self.printer.get_reactor().monotonic()
print_time = self.mcu.estimated_print_time(systime) + MIN_MSG_TIME
self.samples_start1 = self.samples_start2 = print_time
self.last_sequence = 0
with self.lock:
self.raw_samples = []
# Start bulk reading
reqclock = self.mcu.print_time_to_clock(print_time)
rest_ticks = self.mcu.seconds_to_clock(4. / self.data_rate)
self.last_tx_time = print_time
self.query_rate = self.data_rate
self.query_adxl345_cmd.send([self.oid, reqclock, rest_ticks],
reqclock=reqclock)
logging.info("ADXL345 starting measurements")
logging.info("ADXL345 starting '%s' measurements", self.name)
def _finish_measurements(self):
if not self.is_measuring():
return
# Halt bulk reading
print_time = self.printer.lookup_object('toolhead').get_last_move_time()
clock = self.mcu.print_time_to_clock(print_time)
params = self.query_adxl345_end_cmd.send([self.oid, 0, 0],
minclock=clock)
self.last_tx_time = print_time
params = self.query_adxl345_end_cmd.send([self.oid, 0, 0])
self.query_rate = 0
raw_samples = self.raw_samples
self.raw_samples = []
with self.lock:
self.raw_samples = []
# Generate results
end1_time = self._clock_to_print_time(params['end1_clock'])
end2_time = self._clock_to_print_time(params['end2_clock'])
end_sequence = self._convert_sequence(params['sequence'])
overflows = params['limit_count']
logging.info("ADXL345 finished measurements")
self.final_results = (raw_samples, end_sequence, overflows,
logging.info("ADXL345 finished '%s' measurements", self.name)
self.final_results = (end_sequence, overflows,
self.samples_start1, self.samples_start2,
end1_time, end2_time) # XXX
# API interface
def _api_update(self, eventtime):
with self.lock:
raw_samples = self.raw_samples
self.raw_samples = []
if not raw_samples:
return {}
samples = self._extract_samples(raw_samples)
if not samples:
return {}
return {'data': samples}
def _api_startstop(self, is_start):
if is_start:
self._start_measurements()
else:
self._finish_measurements()
def _handle_dump_adxl345(self, web_request):
self.api_dump.add_client(web_request)
hdr = ('sequence', 'x_acceleration', 'y_acceleration', 'z_acceleration')
web_request.send({'header': hdr})
def start_internal_client(self):
if self.is_measuring():
raise self.printer.command_error(
"ADXL345 measurement already in progress")
self._start_measurements()
return ADXL345QueryHelper(self.printer, self, self.axes_map)
cconn = self.api_dump.add_internal_client()
return ADXL345QueryHelper(self.printer, self, cconn)
def load_config(config):
return ADXL345(config)