From 787a2fdf2ee042ce5781540e41eccf692748b472 Mon Sep 17 00:00:00 2001 From: siddacious Date: Mon, 31 Aug 2020 14:47:33 -0700 Subject: [PATCH 001/106] added shake; needs tuning --- adafruit_bno080/__init__.py | 65 +++++++++++++++++++++++++++++++---- examples/bno080_simpletest.py | 3 ++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index b1a644a..0e245b2 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -32,6 +32,9 @@ from time import sleep, monotonic, monotonic_ns from micropython import const +# TODO: Remove on release +from .debug import channels, reports + # TODO: shorten names # Channel 0: the SHTP command channel _BNO_CHANNEL_SHTP_COMMAND = const(0) @@ -74,6 +77,8 @@ _BNO_REPORT_ROTATION_VECTOR = const(0x05) _BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) _BNO_REPORT_STEP_COUNTER = const(0x11) +_BNO_REPORT_SHAKE_DETECTOR = const(0x19) + _DEFAULT_REPORT_INTERVAL = const(50000) # in microseconds = 50ms _QUAT_READ_TIMEOUT = 0.500 # timeout in seconds @@ -114,6 +119,7 @@ _BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14,), _BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), _BNO_REPORT_STEP_COUNTER: (1, 1, 12), + _BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), } DATA_BUFFER_SIZE = const(512) # data buffer size. obviously eats ram @@ -168,7 +174,12 @@ def _parse_sensor_report_data(report_bytes): # 10 Reserved # 11 Reserved def _parse_step_couter_report(report_bytes): - return unpack_from(" 0 def parse_sensor_id(buffer): @@ -222,7 +233,6 @@ def __init__(self, packet_bytes): self.data = packet_bytes[_BNO_HEADER_LEN:data_end_index] def __str__(self): - from .debug import channels, reports # pylint:disable=import-outside-toplevel length = self.header.packet_byte_count outstr = "\n\t\t********** Packet *************\n" @@ -252,11 +262,20 @@ def __str__(self): and len(self.data) >= 6 and self.data[5] in reports ): - outstr += "DBG::\t\t \tSensor Report Type: %s(%d)\n" % ( + outstr += "DBG::\t\t \tSensor Report Type: %s(%s)\n" % ( reports[self.data[5]], - self.data[5], + hex(self.data[5]), ) + if ( + self.report_id == 0xFC + and len(self.data) >= 6 + and self.data[1] in reports + ): + outstr += "DBG::\t\t \tEnabled Feature: %s(%s)\n" % ( + reports[self.data[1]], + hex(self.data[5]), + ) outstr += "DBG::\t\t Sequence number: %s\n" % self.header.sequence_number outstr += "\n" outstr += "DBG::\t\t Data:" @@ -383,6 +402,20 @@ def gyro(self): self._process_available_packets() return self._readings[_BNO_REPORT_GYROSCOPE] + @property + def shake(self): + """True if a shake was detected on any axis since the last time it was checked + + This property has a "latching" behavior where once a shake is detected, it will stay in a + "shaken" state until the value is read. This prevents missing shake events but means that + this property is not guaranteed to reflect the shake state at the moment it is read + """ + self._process_available_packets() + shake_detected = self._readings[_BNO_REPORT_SHAKE_DETECTOR] + # clear on read + if shake_detected: + self._readings[_BNO_REPORT_SHAKE_DETECTOR] = False + # # decorator? def _process_available_packets(self): processed_count = 0 @@ -459,9 +492,27 @@ def _handle_control_report(self, report_id, report_bytes): def _process_report(self, report_id, report_bytes): if report_id < 0xF0: + self._dbg("\tProcessing report:", reports[report_id]) + if self._debug: + outstr = "" + for idx, packet_byte in enumerate(report_bytes): + packet_index = idx + if (packet_index % 4) == 0: + outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) + outstr += "0x{:02X} ".format(packet_byte) + print(outstr) + self._dbg("") + if report_id == _BNO_REPORT_STEP_COUNTER: self._readings[report_id] = _parse_step_couter_report(report_bytes) return + if report_id == _BNO_REPORT_SHAKE_DETECTOR: + shake_detected = _parse_shake_report(report_bytes) + # shake not previously detected - auto cleared by 'shake' property + if not self._readings[_BNO_REPORT_SHAKE_DETECTOR]: + self._readings[_BNO_REPORT_SHAKE_DETECTOR] = shake_detected + return + sensor_data = _parse_sensor_report_data(report_bytes) # TODO: FIXME; Sensor reports are batched in a LIFO which means that multiple reports # for the same type will end with the oldest/last being kept and the other @@ -472,12 +523,14 @@ def _process_report(self, report_id, report_bytes): # TODO: Make this a Packet creation @staticmethod - def _get_feature_enable_report(feature_id): + def _get_feature_enable_report( + feature_id, report_interval=_DEFAULT_REPORT_INTERVAL + ): # TODO !!! ALLOCATION !!! set_feature_report = bytearray(17) set_feature_report[0] = _BNO_CMD_SET_FEATURE_COMMAND set_feature_report[1] = feature_id - pack_into(" Date: Fri, 4 Sep 2020 14:33:07 -0400 Subject: [PATCH 002/106] move reset() to soft_reset() and check packet types on reset --- adafruit_bno080/__init__.py | 37 +++++++++++++++++++++++++++---------- adafruit_bno080/i2c.py | 23 +++-------------------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 0e245b2..4e549e3 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -29,7 +29,7 @@ from struct import unpack_from, pack_into from collections import namedtuple -from time import sleep, monotonic, monotonic_ns +import time from micropython import const # TODO: Remove on release @@ -132,16 +132,16 @@ def _elapsed(start_time): - return monotonic() - start_time + return time.monotonic() - start_time def elapsed_time(func): """Print the runtime of the decorated function""" def wrapper_timer(*args, **kwargs): - start_time = monotonic_ns() # 1 + start_time = time.monotonic_ns() # 1 value = func(*args, **kwargs) - end_time = monotonic_ns() # 2 + end_time = time.monotonic_ns() # 2 run_time = end_time - start_time # 3 print("Finished", func.__name__, "in", (run_time / 1000000.0), "ms") return value @@ -248,7 +248,7 @@ def __str__(self): _BNO_CHANNEL_INPUT_SENSOR_REPORTS, ]: if self.report_id in reports: - outstr += "DBG::\t\t \tReport Type: %s(%d)\n" % ( + outstr += "DBG::\t\t \tReport Type: %s (0x%x)\n" % ( reports[self.report_id], self.report_id, ) @@ -351,11 +351,12 @@ def __init__(self, debug=False): def initialize(self): """Initialize the sensor""" - self.reset() + self.soft_reset() if not self._check_id(): raise RuntimeError("Could not read ID") for report_type in _ENABLED_SENSOR_REPORTS: self._enable_feature(report_type) + time.sleep(0.1) @property def magnetic(self): @@ -436,7 +437,7 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): else: report_id_str = "" self._dbg("** Waiting for packet on channel", channel_number, report_id_str) - start_time = monotonic() + start_time = time.monotonic() while _elapsed(start_time) < timeout: new_packet = self._wait_for_packet() @@ -452,7 +453,7 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): raise RuntimeError("Timed out waiting for a packet on channel", channel_number) def _wait_for_packet(self, timeout=_PACKET_READ_TIMEOUT): - start_time = monotonic() + start_time = time.monotonic() while _elapsed(start_time) < timeout: if not self._data_ready: continue @@ -618,9 +619,25 @@ def _read_header(self): def _data_ready(self): raise RuntimeError("Not implemented") - def reset(self): + def soft_reset(self): """Reset the sensor to an initial unconfigured state""" - raise RuntimeError("Not implemented") + print("Resetting...", end="") + data = bytearray(1) + data[0] = 1 + seq = self._send_packet(BNO_CHANNEL_EXE, data) + + for i in range(3): + time.sleep(0.5) + packet = self._read_packet() + #print(packet) + if i == 0 and packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND: + raise RuntimeError("Expected an SHTP announcement") + if i == 1 and packet.channel_number != BNO_CHANNEL_EXE: + raise RuntimeError("Expected a reset reply") + if i == 2 and packet.channel_number != _BNO_CHANNEL_CONTROL: + raise RuntimeError("Expected a control announcement") + print("OK!"); + # all is good! def _send_packet(self, channel, data): raise RuntimeError("Not implemented") diff --git a/adafruit_bno080/i2c.py b/adafruit_bno080/i2c.py index 9c383b5..a24549a 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno080/i2c.py @@ -6,7 +6,7 @@ Subclass of `adafruit_bno080.BNO080` to use I2C """ -from time import sleep +import time from struct import pack_into import adafruit_bus_device.i2c_device as i2c_device from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet @@ -27,24 +27,6 @@ def __init__(self, i2c_bus, address=_BNO080_DEFAULT_ADDRESS, debug=False): self.bus_device_obj = i2c_device.I2CDevice(i2c_bus, address) super().__init__(debug) - def reset(self): - """Reset the sensor to an initial unconfigured state""" - # TODO: Update to use _wait_for_packet_type? - data = bytearray(1) - data[0] = 1 - self._send_packet(BNO_CHANNEL_EXE, data) - sleep(0.050) - - sleep(1) - data_read = True - while data_read: - data_read = self._read_packet() # pylint:disable=assignment-from-no-return - - sleep(0.050) - data_read = True - while data_read: - data_read = self._read_packet() # pylint:disable=assignment-from-no-return - def _send_packet(self, channel, data): data_length = len(data) write_length = data_length + 4 @@ -62,6 +44,7 @@ def _send_packet(self, channel, data): i2c.write(self._data_buffer, end=write_length) self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256 + return self._sequence_number[channel] # returns true if available data was read # the sensor will always tell us how much there is, so no need to track it ourselves @@ -69,7 +52,7 @@ def _send_packet(self, channel, data): def _read_packet(self): # TODO: MAGIC NUMBER? - sleep(0.001) # + time.sleep(0.001) # # TODO: this can be `_read_header` or know it's done by `_data_ready` with self.bus_device_obj as i2c: i2c.readinto(self._data_buffer, end=4) # this is expecting a header? From c90551383cc7cddfecb7209d526bbc8aece6925b Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 14:55:21 -0400 Subject: [PATCH 003/106] add hardware reset, and retries for resetting --- adafruit_bno080/__init__.py | 26 +++++++++++++++++++++++--- adafruit_bno080/i2c.py | 8 ++++---- examples/bno080_simpletest.py | 7 ++++--- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 4e549e3..b017fee 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -31,6 +31,7 @@ from collections import namedtuple import time from micropython import const +import digitalio # TODO: Remove on release from .debug import channels, reports @@ -332,8 +333,9 @@ class BNO080: """ - def __init__(self, debug=False): + def __init__(self, reset=None, debug=False): self._debug = debug + self._reset = reset self._dbg("********** __init__ *************") self._data_buffer = bytearray(DATA_BUFFER_SIZE) self._packet_slices = [] @@ -351,6 +353,7 @@ def __init__(self, debug=False): def initialize(self): """Initialize the sensor""" + self.hard_reset() self.soft_reset() if not self._check_id(): raise RuntimeError("Could not read ID") @@ -619,16 +622,33 @@ def _read_header(self): def _data_ready(self): raise RuntimeError("Not implemented") + def hard_reset(self): + """Hardware reset the sensor to an initial unconfigured state""" + if not self._reset: + return + self._reset.direction = digitalio.Direction.OUTPUT + self._reset.value = True + time.sleep(0.01) + self._reset.value = False + time.sleep(0.01) + self._reset.value = True + time.sleep(0.1) + def soft_reset(self): """Reset the sensor to an initial unconfigured state""" print("Resetting...", end="") data = bytearray(1) data[0] = 1 seq = self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.1) for i in range(3): - time.sleep(0.5) - packet = self._read_packet() + while True: # retry reading packets until ready! + packet = self._read_packet() + if packet: + break + time.sleep(0.1) + #print(packet) if i == 0 and packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND: raise RuntimeError("Expected an SHTP announcement") diff --git a/adafruit_bno080/i2c.py b/adafruit_bno080/i2c.py index a24549a..9974720 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno080/i2c.py @@ -23,9 +23,9 @@ class BNO080_I2C(BNO080): """ - def __init__(self, i2c_bus, address=_BNO080_DEFAULT_ADDRESS, debug=False): + def __init__(self, i2c_bus, reset=None, address=_BNO080_DEFAULT_ADDRESS, debug=False): self.bus_device_obj = i2c_device.I2CDevice(i2c_bus, address) - super().__init__(debug) + super().__init__(reset, debug) def _send_packet(self, channel, data): data_length = len(data) @@ -57,7 +57,7 @@ def _read_packet(self): with self.bus_device_obj as i2c: i2c.readinto(self._data_buffer, end=4) # this is expecting a header? self._dbg("") - self._dbg("READing packet") + self._dbg("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) header = Packet.header_from_buffer(self._data_buffer) packet_byte_count = header.packet_byte_count @@ -67,7 +67,7 @@ def _read_packet(self): self._sequence_number[channel_number] = sequence_number if packet_byte_count == 0: self._dbg("SKIPPING NO PACKETS AVAILABLE IN i2c._read_packet") - return False # remove header size from read length + return None packet_byte_count -= 4 self._dbg( "channel", diff --git a/examples/bno080_simpletest.py b/examples/bno080_simpletest.py index 61a2108..b670339 100644 --- a/examples/bno080_simpletest.py +++ b/examples/bno080_simpletest.py @@ -1,14 +1,15 @@ # SPDX-FileCopyrightText: 2020 Bryan Siepert, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense -from time import sleep +import time import board import busio from adafruit_bno080.i2c import BNO080_I2C - +from digitalio import DigitalInOut i2c = busio.I2C(board.SCL, board.SDA) -bno = BNO080_I2C(i2c) +reset_pin = DigitalInOut(board.G0) +bno = BNO080_I2C(i2c, reset=reset_pin) while True: From 23bd06d6ca8e6cad296c0f7ce385f6aab2cc9ee0 Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 15:01:33 -0400 Subject: [PATCH 004/106] a packet exception --- adafruit_bno080/__init__.py | 13 +++++++++---- adafruit_bno080/i2c.py | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index b017fee..78bfd04 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -132,6 +132,11 @@ REPORT_STATUS = ["Unreliable", "Accuracy low", "Accuracy medium", "Accuracy high"] +class PacketError(Exception): + """Raised when the packet couldnt be parsed""" + pass + + def _elapsed(start_time): return time.monotonic() - start_time @@ -359,7 +364,6 @@ def initialize(self): raise RuntimeError("Could not read ID") for report_type in _ENABLED_SENSOR_REPORTS: self._enable_feature(report_type) - time.sleep(0.1) @property def magnetic(self): @@ -644,10 +648,11 @@ def soft_reset(self): for i in range(3): while True: # retry reading packets until ready! - packet = self._read_packet() - if packet: + try: + packet = self._read_packet() break - time.sleep(0.1) + except PacketError: + time.sleep(0.1) #print(packet) if i == 0 and packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND: diff --git a/adafruit_bno080/i2c.py b/adafruit_bno080/i2c.py index 9974720..9882d5f 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno080/i2c.py @@ -9,7 +9,7 @@ import time from struct import pack_into import adafruit_bus_device.i2c_device as i2c_device -from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet +from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet, PacketError # should be removeable; I _think_ something else should be able to prep the buffers? @@ -67,7 +67,7 @@ def _read_packet(self): self._sequence_number[channel_number] = sequence_number if packet_byte_count == 0: self._dbg("SKIPPING NO PACKETS AVAILABLE IN i2c._read_packet") - return None + raise PacketError("No packet available") packet_byte_count -= 4 self._dbg( "channel", From de77dabea86b2036a86da29cf285fe5924b8491d Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 16:25:52 -0400 Subject: [PATCH 005/106] manually enable reports --- adafruit_bno080/__init__.py | 106 ++++++++++++++++++---------------- adafruit_bno080/i2c.py | 19 +++++- examples/bno080_simpletest.py | 13 ++++- 3 files changed, 83 insertions(+), 55 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 78bfd04..320546b 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -67,18 +67,18 @@ # Calibrated Acceleration (m/s2) -_BNO_REPORT_ACCELEROMETER = const(0x01) +BNO_REPORT_ACCELEROMETER = const(0x01) # Calibrated gyroscope (rad/s). -_BNO_REPORT_GYROSCOPE = const(0x02) +BNO_REPORT_GYROSCOPE = const(0x02) # Magnetic field calibrated (in µTesla). The fully calibrated magnetic field measurement. -_BNO_REPORT_MAGNETIC_FIELD = const(0x03) +BNO_REPORT_MAGNETIC_FIELD = const(0x03) # Linear acceleration (m/s2). Acceleration of the device with gravity removed -_BNO_REPORT_LINEAR_ACCELERATION = const(0x04) +BNO_REPORT_LINEAR_ACCELERATION = const(0x04) # Rotation Vector -_BNO_REPORT_ROTATION_VECTOR = const(0x05) -_BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) -_BNO_REPORT_STEP_COUNTER = const(0x11) -_BNO_REPORT_SHAKE_DETECTOR = const(0x19) +BNO_REPORT_ROTATION_VECTOR = const(0x05) +BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) +BNO_REPORT_STEP_COUNTER = const(0x11) +BNO_REPORT_SHAKE_DETECTOR = const(0x19) _DEFAULT_REPORT_INTERVAL = const(50000) # in microseconds = 50ms @@ -112,15 +112,15 @@ _BNO_CMD_TIMESTAMP_REBASE: 5, } # length is probably deterministic, like axes * 2 +4 -_ENABLED_SENSOR_REPORTS = { - _BNO_REPORT_ACCELEROMETER: (_Q_POINT_8_SCALAR, 3, 10), - _BNO_REPORT_GYROSCOPE: (_Q_POINT_9_SCALAR, 3, 10), - _BNO_REPORT_MAGNETIC_FIELD: (_Q_POINT_4_SCALAR, 3, 10), - _BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), - _BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14,), - _BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), - _BNO_REPORT_STEP_COUNTER: (1, 1, 12), - _BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), +_AVAIL_SENSOR_REPORTS = { + BNO_REPORT_ACCELEROMETER: (_Q_POINT_8_SCALAR, 3, 10), + BNO_REPORT_GYROSCOPE: (_Q_POINT_9_SCALAR, 3, 10), + BNO_REPORT_MAGNETIC_FIELD: (_Q_POINT_4_SCALAR, 3, 10), + BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), + BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14,), + BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), + BNO_REPORT_STEP_COUNTER: (1, 1, 12), + BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), } DATA_BUFFER_SIZE = const(512) # data buffer size. obviously eats ram @@ -158,7 +158,7 @@ def wrapper_timer(*args, **kwargs): def _parse_sensor_report_data(report_bytes): data_offset = 4 # this may not always be true report_id = report_bytes[0] - scalar, count, _report_length = _ENABLED_SENSOR_REPORTS[report_id] + scalar, count, _report_length = _AVAIL_SENSOR_REPORTS[report_id] results = [] @@ -204,7 +204,7 @@ def parse_sensor_id(buffer): def _report_length(report_id): if report_id < 0xF0: # it's a sensor report - return _ENABLED_SENSOR_REPORTS[report_id][2] + return _AVAIL_SENSOR_REPORTS[report_id][2] return _REPORT_LENGTHS[report_id] @@ -362,53 +362,62 @@ def initialize(self): self.soft_reset() if not self._check_id(): raise RuntimeError("Could not read ID") - for report_type in _ENABLED_SENSOR_REPORTS: - self._enable_feature(report_type) @property def magnetic(self): """A tuple of the current magnetic field measurements on the X, Y, and Z axes""" self._process_available_packets() # decorator? - return self._readings[_BNO_REPORT_MAGNETIC_FIELD] - + try: + return self._readings[BNO_REPORT_MAGNETIC_FIELD] + except KeyError: + raise RuntimeError("No magfield report found, is it enabled?") from None @property def quaternion(self): """A quaternion representing the current rotation vector""" self._process_available_packets() - return self._readings[_BNO_REPORT_ROTATION_VECTOR] + return self._readings[BNO_REPORT_ROTATION_VECTOR] @property def geomagnetic_quaternion(self): """A quaternion representing the current geomagnetic rotation vector""" self._process_available_packets() - return self._readings[_BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] + return self._readings[BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] @property def steps(self): """The number of steps detected since the sensor was initialized""" self._process_available_packets() - return self._readings[_BNO_REPORT_STEP_COUNTER] + return self._readings[BNO_REPORT_STEP_COUNTER] @property def linear_acceleration(self): """A tuple representing the current linear acceleration values on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() - return self._readings[_BNO_REPORT_LINEAR_ACCELERATION] + try: + return self._readings[BNO_REPORT_LINEAR_ACCELERATION] + except KeyError: + raise RuntimeError("No lin. accel report found, is it enabled?") from None @property def acceleration(self): """A tuple representing the acceleration measurements on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() - return self._readings[_BNO_REPORT_ACCELEROMETER] + try: + return self._readings[BNO_REPORT_ACCELEROMETER] + except KeyError: + raise RuntimeError("No accel report found, is it enabled?") from None @property def gyro(self): """A tuple representing Gyro's rotation measurements on the X, Y, and Z axes in radians per second""" self._process_available_packets() - return self._readings[_BNO_REPORT_GYROSCOPE] + try: + return self._readings[BNO_REPORT_GYROSCOPE] + except KeyError: + raise RuntimeError("No gyro report found, is it enabled?") from None @property def shake(self): @@ -419,20 +428,24 @@ def shake(self): this property is not guaranteed to reflect the shake state at the moment it is read """ self._process_available_packets() - shake_detected = self._readings[_BNO_REPORT_SHAKE_DETECTOR] + shake_detected = self._readings[BNO_REPORT_SHAKE_DETECTOR] # clear on read if shake_detected: - self._readings[_BNO_REPORT_SHAKE_DETECTOR] = False + self._readings[BNO_REPORT_SHAKE_DETECTOR] = False # # decorator? def _process_available_packets(self): processed_count = 0 while self._data_ready: - new_packet = self._read_packet() + print("reading a packet") + try: + new_packet = self._read_packet() + except PacketError: + continue self._handle_packet(new_packet) processed_count += 1 self._dbg("") - self._dbg("Processesd", processed_count, "packets") + #print("Processed", processed_count, "packets") self._dbg("") # we'll probably need an exit here for fast sensor rates self._dbg("") @@ -511,14 +524,14 @@ def _process_report(self, report_id, report_bytes): print(outstr) self._dbg("") - if report_id == _BNO_REPORT_STEP_COUNTER: + if report_id == BNO_REPORT_STEP_COUNTER: self._readings[report_id] = _parse_step_couter_report(report_bytes) return - if report_id == _BNO_REPORT_SHAKE_DETECTOR: + if report_id == BNO_REPORT_SHAKE_DETECTOR: shake_detected = _parse_shake_report(report_bytes) # shake not previously detected - auto cleared by 'shake' property - if not self._readings[_BNO_REPORT_SHAKE_DETECTOR]: - self._readings[_BNO_REPORT_SHAKE_DETECTOR] = shake_detected + if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: + self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected return sensor_data = _parse_sensor_report_data(report_bytes) @@ -541,10 +554,11 @@ def _get_feature_enable_report( pack_into(" 5: self._dbg("channel number out of range:", header.channel_number) # data_length, packet_byte_count) diff --git a/examples/bno080_simpletest.py b/examples/bno080_simpletest.py index b670339..aa16634 100644 --- a/examples/bno080_simpletest.py +++ b/examples/bno080_simpletest.py @@ -4,21 +4,27 @@ import time import board import busio +import adafruit_bno080 from adafruit_bno080.i2c import BNO080_I2C from digitalio import DigitalInOut -i2c = busio.I2C(board.SCL, board.SDA) +i2c = busio.I2C(board.SCL, board.SDA, frequency=400000) reset_pin = DigitalInOut(board.G0) bno = BNO080_I2C(i2c, reset=reset_pin) +bno.enable_feature(adafruit_bno080.BNO_REPORT_ACCELEROMETER) +#bno.enable_feature(adafruit_bno080.BNO_REPORT_GYROSCOPE) +#bno.enable_feature(adafruit_bno080.BNO_REPORT_MAGNETIC_FIELD) + while True: - # print("Acceleration:") + print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) print("") - # print("Gyro:") + """ + print("Gyro:") gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) print("") @@ -65,3 +71,4 @@ print("") sleep(0.5) + """ From 12bf82e3e322b30f93c7bfc7e90accda59db69f6 Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 16:40:16 -0400 Subject: [PATCH 006/106] needs more time to boot --- adafruit_bno080/__init__.py | 7 ++++--- adafruit_bno080/i2c.py | 10 ++-------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 320546b..045b705 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -638,21 +638,22 @@ def hard_reset(self): """Hardware reset the sensor to an initial unconfigured state""" if not self._reset: return + #print("Hard resetting...") self._reset.direction = digitalio.Direction.OUTPUT self._reset.value = True time.sleep(0.01) self._reset.value = False time.sleep(0.01) self._reset.value = True - time.sleep(0.1) + time.sleep(0.5) def soft_reset(self): """Reset the sensor to an initial unconfigured state""" - print("Resetting...", end="") + print("Soft resetting...", end="") data = bytearray(1) data[0] = 1 seq = self._send_packet(BNO_CHANNEL_EXE, data) - time.sleep(0.1) + time.sleep(0.5) for i in range(3): while True: # retry reading packets until ready! diff --git a/adafruit_bno080/i2c.py b/adafruit_bno080/i2c.py index 8d543e9..ed5ed72 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno080/i2c.py @@ -51,14 +51,8 @@ def _send_packet(self, channel, data): def _read_header(self): """Reads the first 4 bytes available as a header""" - while True: - with self.bus_device_obj as i2c: - try: - i2c.readinto(self._data_buffer, end=4) # this is expecting a header - break - except RuntimeError: - time.sleep(0.1) - pass + with self.bus_device_obj as i2c: + i2c.readinto(self._data_buffer, end=4) # this is expecting a header packet_header = Packet.header_from_buffer(self._data_buffer) self._dbg(packet_header) return packet_header From 1e254f2a0dd59c4b295b0b83907e88cb48394f07 Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 17:16:45 -0400 Subject: [PATCH 007/106] require manually enabling. works a treat on feather m4 --- adafruit_bno080/__init__.py | 27 ++++++++++++++++++++------- examples/bno080_simpletest.py | 28 ++++++++++++++++------------ 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 045b705..baffa9e 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -371,23 +371,33 @@ def magnetic(self): return self._readings[BNO_REPORT_MAGNETIC_FIELD] except KeyError: raise RuntimeError("No magfield report found, is it enabled?") from None + @property def quaternion(self): """A quaternion representing the current rotation vector""" self._process_available_packets() - return self._readings[BNO_REPORT_ROTATION_VECTOR] + try: + return self._readings[BNO_REPORT_ROTATION_VECTOR] + except KeyError: + raise RuntimeError("No quaternion report found, is it enabled?") from None @property def geomagnetic_quaternion(self): """A quaternion representing the current geomagnetic rotation vector""" self._process_available_packets() - return self._readings[BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] + try: + return self._readings[BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] + except KeyError: + raise RuntimeError("No geomag quaternion report found, is it enabled?") from None @property def steps(self): """The number of steps detected since the sensor was initialized""" self._process_available_packets() - return self._readings[BNO_REPORT_STEP_COUNTER] + try: + return self._readings[BNO_REPORT_STEP_COUNTER] + except KeyError: + raise RuntimeError("No steps report found, is it enabled?") from None @property def linear_acceleration(self): @@ -428,10 +438,13 @@ def shake(self): this property is not guaranteed to reflect the shake state at the moment it is read """ self._process_available_packets() - shake_detected = self._readings[BNO_REPORT_SHAKE_DETECTOR] - # clear on read - if shake_detected: - self._readings[BNO_REPORT_SHAKE_DETECTOR] = False + try: + shake_detected = self._readings[BNO_REPORT_SHAKE_DETECTOR] + # clear on read + if shake_detected: + self._readings[BNO_REPORT_SHAKE_DETECTOR] = False + except KeyError: + raise RuntimeError("No shake report found, is it enabled?") from None # # decorator? def _process_available_packets(self): diff --git a/examples/bno080_simpletest.py b/examples/bno080_simpletest.py index aa16634..ed15062 100644 --- a/examples/bno080_simpletest.py +++ b/examples/bno080_simpletest.py @@ -8,22 +8,27 @@ from adafruit_bno080.i2c import BNO080_I2C from digitalio import DigitalInOut -i2c = busio.I2C(board.SCL, board.SDA, frequency=400000) -reset_pin = DigitalInOut(board.G0) -bno = BNO080_I2C(i2c, reset=reset_pin) +i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) +reset_pin = DigitalInOut(board.D5) +bno = BNO080_I2C(i2c, reset=reset_pin, debug=False) bno.enable_feature(adafruit_bno080.BNO_REPORT_ACCELEROMETER) -#bno.enable_feature(adafruit_bno080.BNO_REPORT_GYROSCOPE) -#bno.enable_feature(adafruit_bno080.BNO_REPORT_MAGNETIC_FIELD) +bno.enable_feature(adafruit_bno080.BNO_REPORT_GYROSCOPE) +bno.enable_feature(adafruit_bno080.BNO_REPORT_MAGNETIC_FIELD) +bno.enable_feature(adafruit_bno080.BNO_REPORT_LINEAR_ACCELERATION) +bno.enable_feature(adafruit_bno080.BNO_REPORT_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno080.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno080.BNO_REPORT_STEP_COUNTER) +bno.enable_feature(adafruit_bno080.BNO_REPORT_SHAKE_DETECTOR) while True: - + time.sleep(0.1) + print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) print("") - """ print("Gyro:") gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) @@ -45,13 +50,14 @@ % (linear_accel_x, linear_accel_y, linear_accel_z) ) print("") + print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member - print( "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) ) print("") + print("Geomagnetic Rotation Vector Quaternion:") ( geo_quat_i, @@ -59,16 +65,14 @@ geo_quat_k, geo_quat_real, ) = bno.geomagnetic_quaternion # pylint:disable=no-member - print( "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) ) print("") + print("Steps detected:", bno.steps) print("") + if bno.shake: print("SHAKE DETECTED!") print("") - - sleep(0.5) - """ From 052adc239fbe2e9fca5bf29b595ee5225901b5ab Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 18:37:38 -0400 Subject: [PATCH 008/106] some uart --- adafruit_bno080/uart.py | 105 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 adafruit_bno080/uart.py diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py new file mode 100644 index 0000000..96ad7b1 --- /dev/null +++ b/adafruit_bno080/uart.py @@ -0,0 +1,105 @@ +# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries +# +# SPDX-License-Identifier: MIT +""" + + Subclass of `adafruit_bno080.BNO080` to use UART + +""" +import time +from struct import pack_into +from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet, PacketError + + +class BNO080_UART(BNO080): + """Library for the BNO080 IMU from Hillcrest Laboratories + + :param uart: The UART devce the BNO080 is connected to. + + """ + + def __init__(self, uart, reset=None, debug=False): + self._uart = uart + super().__init__(reset, debug) + + def _send_packet(self, channel, data): + return 0 + + def _read_into(self, buf, num): + print("Avail:", self._uart.in_waiting, "need", num) + for idx in range(num): + data = self._uart.read(1) + b = data[0] + if b == 0x7d: # control escape + data = self._uart.read(1) + b = data[0] + b ^=0x20 + buf[idx] = b + #print("UART Read buffer: ", [hex(i) for i in buf[0:num]]) + + def _read_packet(self): + # try to read initial packet start byte + while True: + data = self._uart.read(1) + if not data: + continue + b = data[0] + if b == 0x7e: + break + + # read protocol id + data = self._uart.read(1) + if data and data[0] == 0x7e: # second 0x7e + data = self._uart.read(1) + if not data or data[0] != 0x01: + raise RuntimeError("Unhandled UART control SHTP protocol") + + # read header + self._read_into(self._data_buffer, 4) + + print("SHTP Header:", [hex(x) for x in self._data_buffer[0:4]]) + + header = Packet.header_from_buffer(self._data_buffer) + packet_byte_count = header.packet_byte_count + channel_number = header.channel_number + sequence_number = header.sequence_number + + self._sequence_number[channel_number] = sequence_number + if packet_byte_count == 0: + self._dbg("SKIPPING NO PACKETS AVAILABLE IN i2c._read_packet") + raise PacketError("No packet available") + packet_byte_count -= 4 + self._dbg( + "channel", + channel_number, + "has", + packet_byte_count, + "bytes available to read", + ) + + self._read(packet_byte_count) + + # TODO: Allocation + new_packet = Packet(self._data_buffer) + if self._debug: + print(new_packet) + + self._update_sequence_number(new_packet) + + return new_packet + + #if data is not None: + print([hex(x) for x in data]) + + # returns true if all requested data was read + def _read(self, requested_read_length): + self._dbg("trying to read", requested_read_length, "bytes") + # +4 for the header + total_read_length = requested_read_length + 4 + if total_read_length > DATA_BUFFER_SIZE: + self._data_buffer = bytearray(total_read_length) + self._dbg( + "!!!!!!!!!!!! ALLOCATION: increased _data_buffer to bytearray(%d) !!!!!!!!!!!!! " + % total_read_length + ) + self._read_into(self._data_buffer, total_read_length) From 4902c8ded1d6eb0b0d1179cebb0e70d8ed45fb06 Mon Sep 17 00:00:00 2001 From: lady ada Date: Fri, 4 Sep 2020 21:06:09 -0400 Subject: [PATCH 009/106] simple test with serial cable --- adafruit_bno080/__init__.py | 4 +- adafruit_bno080/uart.py | 17 +++++++ examples/bno080_simpletest_uart.py | 77 ++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 examples/bno080_simpletest_uart.py diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index baffa9e..f74719d 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -31,7 +31,6 @@ from collections import namedtuple import time from micropython import const -import digitalio # TODO: Remove on release from .debug import channels, reports @@ -652,6 +651,7 @@ def hard_reset(self): if not self._reset: return #print("Hard resetting...") + import digitalio self._reset.direction = digitalio.Direction.OUTPUT self._reset.value = True time.sleep(0.01) @@ -677,7 +677,7 @@ def soft_reset(self): time.sleep(0.1) #print(packet) - if i == 0 and packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND: + if i == 0 and (packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND) and (packet.channel_number != _BNO_CHANNEL_WAKE_INPUT_SENSOR_REPORTS): raise RuntimeError("Expected an SHTP announcement") if i == 1 and packet.channel_number != BNO_CHANNEL_EXE: raise RuntimeError("Expected a reset reply") diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py index 96ad7b1..60104af 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno080/uart.py @@ -23,6 +23,23 @@ def __init__(self, uart, reset=None, debug=False): super().__init__(reset, debug) def _send_packet(self, channel, data): + data_length = len(data) + write_length = data_length + 4 + + pack_into(" Date: Sat, 5 Sep 2020 01:51:53 -0400 Subject: [PATCH 010/106] working --- adafruit_bno080/__init__.py | 30 ++++----- adafruit_bno080/uart.py | 125 ++++++++++++++++++++++++------------ 2 files changed, 96 insertions(+), 59 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index f74719d..6b65085 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -479,8 +479,9 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): return new_packet else: return new_packet - self._dbg("passing packet to handler for de-slicing") - self._handle_packet(new_packet) + if new_packet.channel_number not in (BNO_CHANNEL_EXE, _BNO_CHANNEL_SHTP_COMMAND): + self._dbg("passing packet to handler for de-slicing") + self._handle_packet(new_packet) raise RuntimeError("Timed out waiting for a packet on channel", channel_number) @@ -502,7 +503,6 @@ def _update_sequence_number(self, new_packet): self._sequence_number[channel] = seq def _handle_packet(self, packet): - # split out reports first _separate_batch(packet, self._packet_slices) while len(self._packet_slices) > 0: @@ -667,22 +667,16 @@ def soft_reset(self): data[0] = 1 seq = self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) - + seq = self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.5) + for i in range(3): - while True: # retry reading packets until ready! - try: - packet = self._read_packet() - break - except PacketError: - time.sleep(0.1) - - #print(packet) - if i == 0 and (packet.channel_number != _BNO_CHANNEL_SHTP_COMMAND) and (packet.channel_number != _BNO_CHANNEL_WAKE_INPUT_SENSOR_REPORTS): - raise RuntimeError("Expected an SHTP announcement") - if i == 1 and packet.channel_number != BNO_CHANNEL_EXE: - raise RuntimeError("Expected a reset reply") - if i == 2 and packet.channel_number != _BNO_CHANNEL_CONTROL: - raise RuntimeError("Expected a control announcement") + try: + packet = self._read_packet() + except PacketError: + time.sleep(0.5) + + print("OK!"); # all is good! diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py index 60104af..7ebf6ee 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno080/uart.py @@ -8,7 +8,7 @@ """ import time from struct import pack_into -from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet, PacketError +from . import BNO080, BNO_CHANNEL_EXE, _BNO_CHANNEL_CONTROL, _BNO_CHANNEL_SHTP_COMMAND, DATA_BUFFER_SIZE, const, Packet, PacketError class BNO080_UART(BNO080): @@ -25,7 +25,20 @@ def __init__(self, uart, reset=None, debug=False): def _send_packet(self, channel, data): data_length = len(data) write_length = data_length + 4 - + ba = bytearray(1) + + # request available size + """ + self._uart.write(b'\x7e') # start byte + time.sleep(0.001) + self._uart.write(b'\x00') # SHTP byte + time.sleep(0.001) + self._uart.write(b'\x7e') + avail = self._uart.read(5) + if avail[0] != 0x7e and avail[1] != 0x01 and avail[4] != 0x7e: + raise RuntimeError("Couldn't get available buffer size") + """ + pack_into(" DATA_BUFFER_SIZE: + self._data_buffer = bytearray(packet_byte_count) + + # skip 4 header bytes since they've already been read + self._read_into(self._data_buffer, start=4, end=packet_byte_count) + + #print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) + + data = self._uart.read(1) + b = data[0] + if b != 0x7e: + raise RuntimeError("Didn't find packet end") + new_packet = Packet(self._data_buffer) if self._debug: print(new_packet) @@ -104,19 +135,31 @@ def _read_packet(self): self._update_sequence_number(new_packet) return new_packet + + @property + def _data_ready(self): + return self._uart.in_waiting >= 4 + + def soft_reset(self): + """Reset the sensor to an initial unconfigured state""" + print("Soft resetting...", end="") + + data = bytearray([0, 1]) + self._send_packet(_BNO_CHANNEL_SHTP_COMMAND, data) + time.sleep(0.5) - #if data is not None: - print([hex(x) for x in data]) - - # returns true if all requested data was read - def _read(self, requested_read_length): - self._dbg("trying to read", requested_read_length, "bytes") - # +4 for the header - total_read_length = requested_read_length + 4 - if total_read_length > DATA_BUFFER_SIZE: - self._data_buffer = bytearray(total_read_length) - self._dbg( - "!!!!!!!!!!!! ALLOCATION: increased _data_buffer to bytearray(%d) !!!!!!!!!!!!! " - % total_read_length - ) - self._read_into(self._data_buffer, total_read_length) + # read the SHTP announce command packet response + while True: + packet = self._read_packet() + if (packet.channel_number == _BNO_CHANNEL_SHTP_COMMAND): + break + + data = bytearray([0xF9, 0]) + seq = self._send_packet(_BNO_CHANNEL_CONTROL, data) + time.sleep(0.5) + seq = self._send_packet(_BNO_CHANNEL_CONTROL, data) + time.sleep(0.5) + # read the SHTP announce command packet response + self._wait_for_packet_type(_BNO_CHANNEL_CONTROL, 0xF8) + + print("OK!") # all is good! From 1df0a1b9f1a94ae262cdfb51d90bbb5cf8acffe7 Mon Sep 17 00:00:00 2001 From: lady ada Date: Sat, 5 Sep 2020 02:00:59 -0400 Subject: [PATCH 011/106] neaten, more reliable reset --- adafruit_bno080/__init__.py | 13 ++++++++----- adafruit_bno080/uart.py | 14 ++++++-------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 6b65085..48aff8a 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -449,7 +449,7 @@ def shake(self): def _process_available_packets(self): processed_count = 0 while self._data_ready: - print("reading a packet") + #print("reading a packet") try: new_packet = self._read_packet() except PacketError: @@ -542,8 +542,11 @@ def _process_report(self, report_id, report_bytes): if report_id == BNO_REPORT_SHAKE_DETECTOR: shake_detected = _parse_shake_report(report_bytes) # shake not previously detected - auto cleared by 'shake' property - if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: - self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected + try: + if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: + self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected + except KeyError: + pass return sensor_data = _parse_sensor_report_data(report_bytes) @@ -570,7 +573,7 @@ def enable_feature(self, feature_id): self._dbg("\n********** Enabling feature id:", feature_id, "**********") set_feature_report = self._get_feature_enable_report(feature_id) - print("Enabling", feature_id) + #print("Enabling", feature_id) self._send_packet(_BNO_CHANNEL_CONTROL, set_feature_report) while True: packet = self._wait_for_packet_type( @@ -584,7 +587,7 @@ def enable_feature(self, feature_id): self._readings[feature_id] = (0.0, 0.0, 0.0, 0.0) else: self._readings[feature_id] = (0.0, 0.0, 0.0) - print("Enabled", feature_id) + #print("Enabled", feature_id) break else: raise RuntimeError("Was not able to enable feature", feature_id) diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py index 7ebf6ee..fd606e5 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno080/uart.py @@ -56,7 +56,7 @@ def _send_packet(self, channel, data): time.sleep(0.001) self._uart.write(b'\x7e') # end byte - print("Sending", [hex(x) for x in self._data_buffer[0:write_length]]) + #print("Sending", [hex(x) for x in self._data_buffer[0:write_length]]) self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256 return self._sequence_number[channel] @@ -98,7 +98,7 @@ def _read_header(self): # read header self._read_into(self._data_buffer, end=4) - print("SHTP Header:", [hex(x) for x in self._data_buffer[0:4]]) + #print("SHTP Header:", [hex(x) for x in self._data_buffer[0:4]]) def _read_packet(self): self._read_header() @@ -153,13 +153,11 @@ def soft_reset(self): packet = self._read_packet() if (packet.channel_number == _BNO_CHANNEL_SHTP_COMMAND): break - - data = bytearray([0xF9, 0]) - seq = self._send_packet(_BNO_CHANNEL_CONTROL, data) + + data = bytearray([1]) + self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) - seq = self._send_packet(_BNO_CHANNEL_CONTROL, data) + self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) - # read the SHTP announce command packet response - self._wait_for_packet_type(_BNO_CHANNEL_CONTROL, 0xF8) print("OK!") # all is good! From 7b3be04b9fd59f31818ddcd7492c0e04f4e70e68 Mon Sep 17 00:00:00 2001 From: lady ada Date: Sat, 5 Sep 2020 12:10:21 -0400 Subject: [PATCH 012/106] start adding SPI --- adafruit_bno080/__init__.py | 4 +- adafruit_bno080/spi.py | 178 ++++++++++++++++++++---------------- adafruit_bno080/uart.py | 6 +- 3 files changed, 102 insertions(+), 86 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 48aff8a..c85462d 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -37,7 +37,7 @@ # TODO: shorten names # Channel 0: the SHTP command channel -_BNO_CHANNEL_SHTP_COMMAND = const(0) +BNO_CHANNEL_SHTP_COMMAND = const(0) BNO_CHANNEL_EXE = const(1) _BNO_CHANNEL_CONTROL = const(2) _BNO_CHANNEL_INPUT_SENSOR_REPORTS = const(3) @@ -479,7 +479,7 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): return new_packet else: return new_packet - if new_packet.channel_number not in (BNO_CHANNEL_EXE, _BNO_CHANNEL_SHTP_COMMAND): + if new_packet.channel_number not in (BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND): self._dbg("passing packet to handler for de-slicing") self._handle_packet(new_packet) diff --git a/adafruit_bno080/spi.py b/adafruit_bno080/spi.py index 5348100..80e60a7 100644 --- a/adafruit_bno080/spi.py +++ b/adafruit_bno080/spi.py @@ -6,14 +6,14 @@ Subclass of `adafruit_bno080.BNO080` to use SPI """ -from time import sleep +import time from struct import pack_into import board -from digitalio import DigitalInOut, Direction +from digitalio import Direction, Pull import adafruit_bus_device.spi_device as spi_device -from . import BNO080, DATA_BUFFER_SIZE, const, Packet +from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, const, Packet # should be removeable; I _think_ something else should be able to prep the buffers? @@ -32,70 +32,110 @@ class BNO080_SPI(BNO080): # """Library for the BNO080 IMU from Hillcrest Laboratories - # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. # """ def __init__( - self, spi_bus, cs_pin_obj, int_pin_obj, baudrate=100000, debug=False + self, spi_bus, cspin, intpin, wakepin, resetpin, baudrate=100000, debug=False ): # pylint:disable=too-many-arguments - self.bus_device_obj = spi_device.SPIDevice( - spi_bus, cs_pin_obj, baudrate=baudrate, polarity=1, phase=1 + self._spi = spi_device.SPIDevice( + spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1 ) - self._int_pin = int_pin_obj - - self._int_check_pin = DigitalInOut(board.D9) - self._int_check_pin.direction = Direction.OUTPUT - self._int_check_pin.value = False - - self._read_pin = DigitalInOut(board.D10) - self._read_pin.direction = Direction.OUTPUT - self._read_pin.value = False - - self._write_pin = DigitalInOut(board.D11) - self._write_pin.direction = Direction.OUTPUT - self._write_pin.value = False - - super().__init__(debug) + self._int = intpin + self._wake = wakepin + super().__init__(resetpin, debug) + + + def hard_reset(self): + """Hardware reset the sensor to an initial unconfigured state""" + self._reset.direction = Direction.OUTPUT + self._wake.direction = Direction.OUTPUT + self._int.direction = Direction.INPUT + self._int.pull = Pull.UP + + print("Hard resetting...") + self._wake.value = True # set PS0 high (PS1 also must be tied high) + self._reset.value = True # perform hardware reset + time.sleep(0.01) + self._reset.value = False + time.sleep(0.01) + self._reset.value = True + self._wait_for_int() + print("Done!") + self._read_packet() + + def _wait_for_int(self): + print("Waiting for INT...", end="") + start_time = time.monotonic() + while _elapsed(start_time) < 1.0: + if not self._int.value: + break + else: + raise RuntimeError("Could not wake up") + print("OK") + + def soft_reset(self): + """Reset the sensor to an initial unconfigured state""" + print("Soft resetting...", end="") + data = bytearray(1) + data[0] = 1 + seq = self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.5) + seq = self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.5) + + for i in range(3): + try: + packet = self._read_packet() + except PacketError: + time.sleep(0.5) + print("OK!"); + # all is good! + + def _read_into(self, buf, start=0, end=None): + self._wait_for_int() + + with self._spi as spi: + spi.readinto(buf, start=start, end=end) + print("SPI Read buffer: ", [hex(i) for i in buf[start:end]]) + + def _read_header(self): + """Reads the first 4 bytes available as a header""" + self._wait_for_int() + + # read header + with self._spi as spi: + spi.readinto(self._data_buffer, end=4) + self._dbg("") + print("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) - def reset(self): - self._dbg("Sleeping") - sleep(2.050) - - self._dbg("**** waiting for advertising packet **") - # read and disregard first initial advertising packet - # The BNO08X uses advertisements to publish the channel maps and the names - # of the built-in applications. - # _advertising_packet = self._wait_for_packet() - self._wait_for_packet_type(0) - - # read and disregard init completed packet - self._dbg("**** received packet; waiting for init complete packet **") - self._wait_for_packet_type(2, 0xF1) - print("INIT COMPLETE?!") - - # I think this and `_send_packet` should take a `Packet` def _read_packet(self): - self._read_pin.value = True - + self._read_header() + + #print([hex(x) for x in self._data_buffer[0:4]]) header = Packet.header_from_buffer(self._data_buffer) + packet_byte_count = header.packet_byte_count + channel_number = header.channel_number + sequence_number = header.sequence_number - if header.data_length == 0: - self._read_pin.value = False + self._sequence_number[channel_number] = sequence_number + if packet_byte_count == 0: + raise PacketError("No packet available") - raise RuntimeError("Zero bytes ready") + self._dbg("channel %d has %d bytes available" % (channel_number, packet_byte_count-4)) - read_length = header.data_length - self._read(read_length) - self._read_pin.value = False + if packet_byte_count > DATA_BUFFER_SIZE: + self._data_buffer = bytearray(packet_byte_count) - # TODO: Allocaiton + # re-read header bytes since this is going to be a new transaction + self._read_into(self._data_buffer, start=0, end=packet_byte_count) + #print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) + new_packet = Packet(self._data_buffer) if self._debug: print(new_packet) self._update_sequence_number(new_packet) - return new_packet ###### Actually send bytes ########## @@ -117,51 +157,27 @@ def _read(self, requested_read_length): return unread_bytes > 0 def _send_packet(self, channel, data): - self._write_pin.value = True - self._dbg("Sending packet to channel", channel) data_length = len(data) write_length = data_length + 4 # struct.pack_into(fmt, buffer, offset, *values) pack_into(" Date: Sat, 5 Sep 2020 12:34:38 -0400 Subject: [PATCH 013/106] as good as its going to get with a BNO080 - will try BNO085 later --- adafruit_bno080/__init__.py | 12 ++++++++---- adafruit_bno080/spi.py | 15 +++++++-------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index c85462d..221ca87 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -504,9 +504,13 @@ def _update_sequence_number(self, new_packet): def _handle_packet(self, packet): # split out reports first - _separate_batch(packet, self._packet_slices) - while len(self._packet_slices) > 0: - self._process_report(*self._packet_slices.pop()) + try: + _separate_batch(packet, self._packet_slices) + while len(self._packet_slices) > 0: + self._process_report(*self._packet_slices.pop()) + except Exception as e: + print(packet) + raise e def _handle_control_report(self, report_id, report_bytes): if report_id == _SHTP_REPORT_PRODUCT_ID_RESPONSE: @@ -578,7 +582,7 @@ def enable_feature(self, feature_id): while True: packet = self._wait_for_packet_type( _BNO_CHANNEL_CONTROL, _BNO_CMD_GET_FEATURE_RESPONSE - ) + ) if packet.data[1] == feature_id: if ( diff --git a/adafruit_bno080/spi.py b/adafruit_bno080/spi.py index 80e60a7..d454bb3 100644 --- a/adafruit_bno080/spi.py +++ b/adafruit_bno080/spi.py @@ -37,7 +37,7 @@ class BNO080_SPI(BNO080): # """ def __init__( - self, spi_bus, cspin, intpin, wakepin, resetpin, baudrate=100000, debug=False + self, spi_bus, cspin, intpin, wakepin, resetpin, baudrate=4000000, debug=False ): # pylint:disable=too-many-arguments self._spi = spi_device.SPIDevice( spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1 @@ -66,14 +66,14 @@ def hard_reset(self): self._read_packet() def _wait_for_int(self): - print("Waiting for INT...", end="") + #print("Waiting for INT...", end="") start_time = time.monotonic() - while _elapsed(start_time) < 1.0: + while _elapsed(start_time) < 3.0: if not self._int.value: break else: raise RuntimeError("Could not wake up") - print("OK") + #print("OK") def soft_reset(self): """Reset the sensor to an initial unconfigured state""" @@ -82,8 +82,6 @@ def soft_reset(self): data[0] = 1 seq = self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) - seq = self._send_packet(BNO_CHANNEL_EXE, data) - time.sleep(0.5) for i in range(3): try: @@ -98,7 +96,7 @@ def _read_into(self, buf, start=0, end=None): with self._spi as spi: spi.readinto(buf, start=start, end=end) - print("SPI Read buffer: ", [hex(i) for i in buf[start:end]]) + #print("SPI Read buffer: ", [hex(i) for i in buf[start:end]]) def _read_header(self): """Reads the first 4 bytes available as a header""" @@ -108,7 +106,7 @@ def _read_header(self): with self._spi as spi: spi.readinto(self._data_buffer, end=4) self._dbg("") - print("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) + #print("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) def _read_packet(self): self._read_header() @@ -170,6 +168,7 @@ def _send_packet(self, channel, data): self._wait_for_int() with self._spi as spi: spi.write(self._data_buffer, end=write_length) + #print("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]]) self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256 return self._sequence_number[channel] From d9f0f5f00b0ec31ae462d4cedf4f5cb735f9d8e5 Mon Sep 17 00:00:00 2001 From: lady ada Date: Sat, 5 Sep 2020 12:38:37 -0400 Subject: [PATCH 014/106] more cleans, good enough to use --- adafruit_bno080/i2c.py | 10 ---------- adafruit_bno080/spi.py | 13 ------------- 2 files changed, 23 deletions(-) diff --git a/adafruit_bno080/i2c.py b/adafruit_bno080/i2c.py index ed5ed72..be595e4 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno080/i2c.py @@ -11,11 +11,8 @@ import adafruit_bus_device.i2c_device as i2c_device from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, const, Packet, PacketError -# should be removeable; I _think_ something else should be able to prep the buffers? - _BNO080_DEFAULT_ADDRESS = const(0x4A) - class BNO080_I2C(BNO080): """Library for the BNO080 IMU from Hillcrest Laboratories @@ -33,10 +30,7 @@ def _send_packet(self, channel, data): pack_into(" 5: self._dbg("channel number out of range:", header.channel_number) - # data_length, packet_byte_count) if header.packet_byte_count == 0x7FFF: print("Byte count is 0x7FFF/0xFFFF; Error?") if header.sequence_number == 0xFF: diff --git a/adafruit_bno080/spi.py b/adafruit_bno080/spi.py index d454bb3..7ec4cc1 100644 --- a/adafruit_bno080/spi.py +++ b/adafruit_bno080/spi.py @@ -12,14 +12,8 @@ import board from digitalio import Direction, Pull import adafruit_bus_device.spi_device as spi_device - from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, const, Packet -# should be removeable; I _think_ something else should be able to prep the buffers? - -_BNO080_DEFAULT_ADDRESS = const(0x4A) - - class BNO080_SPI(BNO080): """Instantiate a `adafruit_bno080.BNO080_SPI` instance to communicate with the sensor using SPI @@ -136,11 +130,6 @@ def _read_packet(self): self._update_sequence_number(new_packet) return new_packet - ###### Actually send bytes ########## - # Note: I _think_ these can be used for either SPI or I2C in the base class by having the - # subclass set the 'bus_device_object' to a `bus_device`.SPI` or `bus_device.I2C` - - # returns true if all requested data was read def _read(self, requested_read_length): self._dbg("trying to read", requested_read_length, "bytes") unread_bytes = 0 @@ -158,7 +147,6 @@ def _send_packet(self, channel, data): data_length = len(data) write_length = data_length + 4 - # struct.pack_into(fmt, buffer, offset, *values) pack_into(" Date: Tue, 8 Sep 2020 18:42:53 -0700 Subject: [PATCH 015/106] moved to bytearray copy by assignment --- adafruit_bno080/uart.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py index 70a6284..a5920cf 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno080/uart.py @@ -42,9 +42,7 @@ def _send_packet(self, channel, data): pack_into(" Date: Tue, 8 Sep 2020 19:55:33 -0700 Subject: [PATCH 016/106] linting --- adafruit_bno080/__init__.py | 51 ++++---- adafruit_bno080/i2c.py | 10 +- adafruit_bno080/spi.py | 44 +++---- adafruit_bno080/uart.py | 75 +++++++----- adafruit_bno080/uart.py.debug | 163 ++++++++++++++++++++++++++ examples/bno080_quaternion_service.py | 2 +- examples/bno080_simpletest.py | 4 +- examples/bno080_simpletest_spi.py | 11 +- examples/bno080_simpletest_uart.py | 12 +- 9 files changed, 281 insertions(+), 91 deletions(-) create mode 100644 adafruit_bno080/uart.py.debug diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 221ca87..5e164bb 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -133,7 +133,8 @@ class PacketError(Exception): """Raised when the packet couldnt be parsed""" - pass + + pass # pylint:disable=unnecessary-pass def _elapsed(start_time): @@ -387,7 +388,9 @@ def geomagnetic_quaternion(self): try: return self._readings[BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] except KeyError: - raise RuntimeError("No geomag quaternion report found, is it enabled?") from None + raise RuntimeError( + "No geomag quaternion report found, is it enabled?" + ) from None @property def steps(self): @@ -449,7 +452,7 @@ def shake(self): def _process_available_packets(self): processed_count = 0 while self._data_ready: - #print("reading a packet") + # print("reading a packet") try: new_packet = self._read_packet() except PacketError: @@ -457,7 +460,7 @@ def _process_available_packets(self): self._handle_packet(new_packet) processed_count += 1 self._dbg("") - #print("Processed", processed_count, "packets") + # print("Processed", processed_count, "packets") self._dbg("") # we'll probably need an exit here for fast sensor rates self._dbg("") @@ -479,7 +482,10 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): return new_packet else: return new_packet - if new_packet.channel_number not in (BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND): + if new_packet.channel_number not in ( + BNO_CHANNEL_EXE, + BNO_CHANNEL_SHTP_COMMAND, + ): self._dbg("passing packet to handler for de-slicing") self._handle_packet(new_packet) @@ -508,9 +514,9 @@ def _handle_packet(self, packet): _separate_batch(packet, self._packet_slices) while len(self._packet_slices) > 0: self._process_report(*self._packet_slices.pop()) - except Exception as e: + except Exception as error: print(packet) - raise e + raise error def _handle_control_report(self, report_id, report_bytes): if report_id == _SHTP_REPORT_PRODUCT_ID_RESPONSE: @@ -573,16 +579,18 @@ def _get_feature_enable_report( pack_into(" DATA_BUFFER_SIZE: self._data_buffer = bytearray(packet_byte_count) # re-read header bytes since this is going to be a new transaction self._read_into(self._data_buffer, start=0, end=packet_byte_count) - #print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) - + # print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) + new_packet = Packet(self._data_buffer) if self._debug: print(new_packet) @@ -139,7 +141,7 @@ def _read(self, requested_read_length): unread_bytes = total_read_length - DATA_BUFFER_SIZE total_read_length = DATA_BUFFER_SIZE - with self.bus_device_obj as spi: + with self._spi as spi: spi.readinto(self._data_buffer, end=total_read_length) return unread_bytes > 0 @@ -156,7 +158,7 @@ def _send_packet(self, channel, data): self._wait_for_int() with self._spi as spi: spi.write(self._data_buffer, end=write_length) - #print("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]]) + # print("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]]) self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256 return self._sequence_number[channel] diff --git a/adafruit_bno080/uart.py b/adafruit_bno080/uart.py index a5920cf..1ea84cf 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno080/uart.py @@ -8,7 +8,14 @@ """ import time from struct import pack_into -from . import BNO080, BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND, DATA_BUFFER_SIZE, const, Packet, PacketError +from . import ( + BNO080, + BNO_CHANNEL_EXE, + BNO_CHANNEL_SHTP_COMMAND, + DATA_BUFFER_SIZE, + Packet, + PacketError, +) class BNO080_UART(BNO080): @@ -25,9 +32,10 @@ def __init__(self, uart, reset=None, debug=False): def _send_packet(self, channel, data): data_length = len(data) write_length = data_length + 4 - ba = bytearray(1) - + byte_buffer = bytearray(1) + # request available size + # pylint:disable=pointless-string-statement """ self._uart.write(b'\x7e') # start byte time.sleep(0.001) @@ -38,42 +46,42 @@ def _send_packet(self, channel, data): if avail[0] != 0x7e and avail[1] != 0x01 and avail[4] != 0x7e: raise RuntimeError("Couldn't get available buffer size") """ - + # pylint:enable=pointless-string-statement + pack_into(" DATA_BUFFER_SIZE: self._data_buffer = bytearray(packet_byte_count) @@ -119,13 +130,13 @@ def _read_packet(self): # skip 4 header bytes since they've already been read self._read_into(self._data_buffer, start=4, end=packet_byte_count) - #print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) - + # print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) + data = self._uart.read(1) b = data[0] - if b != 0x7e: + if b != 0x7E: raise RuntimeError("Didn't find packet end") - + new_packet = Packet(self._data_buffer) if self._debug: print(new_packet) @@ -141,21 +152,21 @@ def _data_ready(self): def soft_reset(self): """Reset the sensor to an initial unconfigured state""" print("Soft resetting...", end="") - + data = bytearray([0, 1]) self._send_packet(BNO_CHANNEL_SHTP_COMMAND, data) time.sleep(0.5) - + # read the SHTP announce command packet response while True: packet = self._read_packet() - if (packet.channel_number == BNO_CHANNEL_SHTP_COMMAND): + if packet.channel_number == BNO_CHANNEL_SHTP_COMMAND: break - + data = bytearray([1]) self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) self._send_packet(BNO_CHANNEL_EXE, data) time.sleep(0.5) - print("OK!") # all is good! + print("OK!") # all is good! diff --git a/adafruit_bno080/uart.py.debug b/adafruit_bno080/uart.py.debug new file mode 100644 index 0000000..e78655f --- /dev/null +++ b/adafruit_bno080/uart.py.debug @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries +# +# SPDX-License-Identifier: MIT +""" + + Subclass of `adafruit_bno080.BNO080` to use UART + +""" +import time +from struct import pack_into +from . import BNO080, BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND, DATA_BUFFER_SIZE, const, Packet, PacketError + + +class BNO080_UART(BNO080): + """Library for the BNO080 IMU from Hillcrest Laboratories + + :param uart: The UART devce the BNO080 is connected to. + + """ + + def __init__(self, uart, reset=None, debug=False): + self._uart = uart + super().__init__(reset, debug) + + def _send_packet(self, channel, data): + data_length = len(data) + write_length = data_length + 4 + ba = bytearray(1) + + # request available size + """ + self._uart.write(b'\x7e') # start byte + time.sleep(0.001) + self._uart.write(b'\x00') # SHTP byte + time.sleep(0.001) + self._uart.write(b'\x7e') + avail = self._uart.read(5) + if avail[0] != 0x7e and avail[1] != 0x01 and avail[4] != 0x7e: + raise RuntimeError("Couldn't get available buffer size") + """ + + pack_into(" DATA_BUFFER_SIZE: + self._data_buffer = bytearray(packet_byte_count) + + # skip 4 header bytes since they've already been read + self._read_into(self._data_buffer, start=4, end=packet_byte_count) + + print("Packet: ", ",".join(["0x{:02X}".format(i) for i in self._data_buffer[:packet_byte_count]])) + + data = self._uart.read(1) + b = data[0] + if b != 0x7e: + print("Got", b, "instead of 0x7e") + raise RuntimeError("Didn't find packet end") + + new_packet = Packet(self._data_buffer) + if self._debug: + print(new_packet) + + self._update_sequence_number(new_packet) + + return new_packet + + @property + def _data_ready(self): + return self._uart.in_waiting >= 4 + + def soft_reset(self): + """Reset the sensor to an initial unconfigured state""" + print("Soft resetting...", end="") + + data = bytearray([0, 1]) + self._send_packet(BNO_CHANNEL_SHTP_COMMAND, data) + time.sleep(0.5) + + # read the SHTP announce command packet response + while True: + packet = self._read_packet() + if (packet.channel_number == BNO_CHANNEL_SHTP_COMMAND): + break + + data = bytearray([1]) + self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.5) + self._send_packet(BNO_CHANNEL_EXE, data) + time.sleep(0.5) + + print("OK!") # all is good! diff --git a/examples/bno080_quaternion_service.py b/examples/bno080_quaternion_service.py index 274d588..616ee1e 100644 --- a/examples/bno080_quaternion_service.py +++ b/examples/bno080_quaternion_service.py @@ -4,9 +4,9 @@ import time import board from adafruit_ble import BLERadio -from adafruit_bno080 import BNO080 from adafruit_ble_adafruit.adafruit_service import AdafruitServerAdvertisement from adafruit_ble_adafruit.quaternion_service import QuaternionService +from adafruit_bno080 import BNO080 i2c = board.I2C() bno = BNO080(i2c) diff --git a/examples/bno080_simpletest.py b/examples/bno080_simpletest.py index ed15062..56b6cb7 100644 --- a/examples/bno080_simpletest.py +++ b/examples/bno080_simpletest.py @@ -4,9 +4,9 @@ import time import board import busio +from digitalio import DigitalInOut import adafruit_bno080 from adafruit_bno080.i2c import BNO080_I2C -from digitalio import DigitalInOut i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) reset_pin = DigitalInOut(board.D5) @@ -23,7 +23,7 @@ while True: time.sleep(0.1) - + print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) diff --git a/examples/bno080_simpletest_spi.py b/examples/bno080_simpletest_spi.py index f2a9eeb..355f75c 100644 --- a/examples/bno080_simpletest_spi.py +++ b/examples/bno080_simpletest_spi.py @@ -13,12 +13,17 @@ cs = DigitalInOut(board.D5) cs.direction = Direction.OUTPUT - int_pin = DigitalInOut(board.D6) int_pin.direction = Direction.INPUT -bno = BNO080_SPI(spi, cs, int_pin, debug=True) -print("\n****** INIT COMPLETE *******") +wake_pin = DigitalInOut(board.D9) +wake_pin.direction = Direction.INPUT + +reset_pin = DigitalInOut(board.D9) +reset_pin.direction = Direction.INPUT + +bno = BNO080_SPI(spi, cs, int_pin, wake_pin, reset_pin, debug=True) + while True: print("getting quat") quat = bno.quaternion # pylint:disable=no-member diff --git a/examples/bno080_simpletest_uart.py b/examples/bno080_simpletest_uart.py index c3f93e0..6bb1263 100644 --- a/examples/bno080_simpletest_uart.py +++ b/examples/bno080_simpletest_uart.py @@ -2,13 +2,15 @@ # # SPDX-License-Identifier: Unlicense import time -import serial +import board +import busio import adafruit_bno080 from adafruit_bno080.uart import BNO080_UART -uart = serial.Serial("COM49", baudrate=3000000, timeout=1) -print(uart.name) -#uart = busio.UART(board.TX, board.RX, baudrate=3000000, receiver_buffer_size=2048) +# import serial +# uart = serial.Serial("COM49", baudrate=3000000, timeout=1) +# print(uart.name) +uart = busio.UART(board.TX, board.RX, baudrate=3000000, receiver_buffer_size=2048) bno = BNO080_UART(uart, reset=None, debug=True) bno.enable_feature(adafruit_bno080.BNO_REPORT_ACCELEROMETER) @@ -22,7 +24,7 @@ while True: time.sleep(0.1) - + print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) From 34250943af356b185e7e99becefa87f7a6201c08 Mon Sep 17 00:00:00 2001 From: siddacious Date: Tue, 8 Sep 2020 20:01:36 -0700 Subject: [PATCH 017/106] more linting --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f62466c..9c621df 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,4 @@ bundles dist **/*.egg-info .vscode -*notes* \ No newline at end of file +*notes* From fbfff2156a302a011e374caf59749c1c26f880ca Mon Sep 17 00:00:00 2001 From: siddacious Date: Tue, 8 Sep 2020 20:06:08 -0700 Subject: [PATCH 018/106] the more the lintier --- adafruit_bno080/__init__.py | 6 +- adafruit_bno080/uart.py.debug | 163 ---------------------------------- 2 files changed, 3 insertions(+), 166 deletions(-) delete mode 100644 adafruit_bno080/uart.py.debug diff --git a/adafruit_bno080/__init__.py b/adafruit_bno080/__init__.py index 5e164bb..faf0f14 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno080/__init__.py @@ -145,11 +145,11 @@ def elapsed_time(func): """Print the runtime of the decorated function""" def wrapper_timer(*args, **kwargs): - start_time = time.monotonic_ns() # 1 + start_time = time.monotonic() # 1 value = func(*args, **kwargs) - end_time = time.monotonic_ns() # 2 + end_time = time.monotonic() # 2 run_time = end_time - start_time # 3 - print("Finished", func.__name__, "in", (run_time / 1000000.0), "ms") + print("Finished", func.__name__, "in", (run_time * 1000.0), "ms") return value return wrapper_timer diff --git a/adafruit_bno080/uart.py.debug b/adafruit_bno080/uart.py.debug deleted file mode 100644 index e78655f..0000000 --- a/adafruit_bno080/uart.py.debug +++ /dev/null @@ -1,163 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries -# -# SPDX-License-Identifier: MIT -""" - - Subclass of `adafruit_bno080.BNO080` to use UART - -""" -import time -from struct import pack_into -from . import BNO080, BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND, DATA_BUFFER_SIZE, const, Packet, PacketError - - -class BNO080_UART(BNO080): - """Library for the BNO080 IMU from Hillcrest Laboratories - - :param uart: The UART devce the BNO080 is connected to. - - """ - - def __init__(self, uart, reset=None, debug=False): - self._uart = uart - super().__init__(reset, debug) - - def _send_packet(self, channel, data): - data_length = len(data) - write_length = data_length + 4 - ba = bytearray(1) - - # request available size - """ - self._uart.write(b'\x7e') # start byte - time.sleep(0.001) - self._uart.write(b'\x00') # SHTP byte - time.sleep(0.001) - self._uart.write(b'\x7e') - avail = self._uart.read(5) - if avail[0] != 0x7e and avail[1] != 0x01 and avail[4] != 0x7e: - raise RuntimeError("Couldn't get available buffer size") - """ - - pack_into(" DATA_BUFFER_SIZE: - self._data_buffer = bytearray(packet_byte_count) - - # skip 4 header bytes since they've already been read - self._read_into(self._data_buffer, start=4, end=packet_byte_count) - - print("Packet: ", ",".join(["0x{:02X}".format(i) for i in self._data_buffer[:packet_byte_count]])) - - data = self._uart.read(1) - b = data[0] - if b != 0x7e: - print("Got", b, "instead of 0x7e") - raise RuntimeError("Didn't find packet end") - - new_packet = Packet(self._data_buffer) - if self._debug: - print(new_packet) - - self._update_sequence_number(new_packet) - - return new_packet - - @property - def _data_ready(self): - return self._uart.in_waiting >= 4 - - def soft_reset(self): - """Reset the sensor to an initial unconfigured state""" - print("Soft resetting...", end="") - - data = bytearray([0, 1]) - self._send_packet(BNO_CHANNEL_SHTP_COMMAND, data) - time.sleep(0.5) - - # read the SHTP announce command packet response - while True: - packet = self._read_packet() - if (packet.channel_number == BNO_CHANNEL_SHTP_COMMAND): - break - - data = bytearray([1]) - self._send_packet(BNO_CHANNEL_EXE, data) - time.sleep(0.5) - self._send_packet(BNO_CHANNEL_EXE, data) - time.sleep(0.5) - - print("OK!") # all is good! From c42a50f6fb1ef18b96b0c9ec31c945694b55cd03 Mon Sep 17 00:00:00 2001 From: siddacious Date: Wed, 9 Sep 2020 13:37:05 -0700 Subject: [PATCH 019/106] renaming to bno08x for BNO080 and BNO085 --- README.rst | 16 +++++++------- .../__init__.py | 18 +++++++-------- {adafruit_bno080 => adafruit_bno08x}/debug.py | 0 {adafruit_bno080 => adafruit_bno08x}/i2c.py | 14 ++++++------ {adafruit_bno080 => adafruit_bno08x}/spi.py | 14 ++++++------ {adafruit_bno080 => adafruit_bno08x}/uart.py | 10 ++++----- docs/api.rst | 2 +- docs/conf.py | 16 +++++++------- docs/index.rst | 4 ++-- ...ervice.py => bno08x_quaternion_service.py} | 6 ++--- ...080_simpletest.py => bno08x_simpletest.py} | 22 +++++++++---------- ...letest_spi.py => bno08x_simpletest_spi.py} | 4 ++-- ...test_uart.py => bno08x_simpletest_uart.py} | 22 +++++++++---------- setup.py | 6 ++--- 14 files changed, 77 insertions(+), 77 deletions(-) rename {adafruit_bno080 => adafruit_bno08x}/__init__.py (98%) rename {adafruit_bno080 => adafruit_bno08x}/debug.py (100%) rename {adafruit_bno080 => adafruit_bno08x}/i2c.py (91%) rename {adafruit_bno080 => adafruit_bno08x}/spi.py (93%) rename {adafruit_bno080 => adafruit_bno08x}/uart.py (95%) rename examples/{bno080_quaternion_service.py => bno08x_quaternion_service.py} (90%) rename examples/{bno080_simpletest.py => bno08x_simpletest.py} (75%) rename examples/{bno080_simpletest_spi.py => bno08x_simpletest_spi.py} (88%) rename examples/{bno080_simpletest_uart.py => bno08x_simpletest_uart.py} (76%) diff --git a/README.rst b/README.rst index af89cfd..2221df7 100644 --- a/README.rst +++ b/README.rst @@ -1,23 +1,23 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-bno080/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/bno080/en/latest/ +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-bno08x/badge/?version=latest + :target: https://circuitpython.readthedocs.io/projects/bno08x/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg :target: https://adafru.it/discord :alt: Discord -.. image:: https://github.com/adafruit/Adafruit_CircuitPython_BNO080/workflows/Build%20CI/badge.svg - :target: https://github.com/adafruit/Adafruit_CircuitPython_BNO080/actions +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_BNO08x/workflows/Build%20CI/badge.svg + :target: https://github.com/adafruit/Adafruit_CircuitPython_BNO08x/actions :alt: Build Status .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black :alt: Code Style: Black -Helper library for the Hillcrest Laboratories BNO080 IMU +Helper library for the Hillcrest Laboratories BNO08x IMUs Dependencies @@ -63,10 +63,10 @@ Usage Example import board import busio - import adafruit_bno080 + import adafruit_bno08x i2c = busio.I2C(board.SCL, board.SDA) - bno = adafruit_bno080.BNO080(i2c) + bno = adafruit_bno08x.BNO08X(i2c) while True: quat = bno.rotation_vector @@ -77,7 +77,7 @@ Contributing ============ Contributions are welcome! Please read our `Code of Conduct -`_ +`_ before contributing to help this project stay welcoming. Documentation diff --git a/adafruit_bno080/__init__.py b/adafruit_bno08x/__init__.py similarity index 98% rename from adafruit_bno080/__init__.py rename to adafruit_bno08x/__init__.py index faf0f14..70afb4e 100644 --- a/adafruit_bno080/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -2,10 +2,10 @@ # # SPDX-License-Identifier: MIT """ -`adafruit_bno080` +`adafruit_bno08x` ================================================================================ -Helper library for the Hillcrest Laboratories BNO080 IMU +Helper library for the Hillcrest Laboratories BNO08x IMUs * Author(s): Bryan Siepert @@ -15,7 +15,7 @@ **Hardware:** -* `Adafruit BNO080 Breakout `_ +* `Adafruit BNO08x Breakout `_ **Software and Dependencies:** @@ -25,7 +25,7 @@ * `Adafruit's Bus Device library `_ """ __version__ = "0.0.0-auto.0" -__repo__ = "https:# github.com/adafruit/Adafruit_CircuitPython_BNO080.git" +__repo__ = "https:# github.com/adafruit/Adafruit_CircuitPython_BNO08x.git" from struct import unpack_from, pack_into from collections import namedtuple @@ -83,7 +83,7 @@ _DEFAULT_REPORT_INTERVAL = const(50000) # in microseconds = 50ms _QUAT_READ_TIMEOUT = 0.500 # timeout in seconds _PACKET_READ_TIMEOUT = 15.000 # timeout in seconds -_BNO080_CMD_RESET = const(0x01) +_BNO08X_CMD_RESET = const(0x01) _QUAT_Q_POINT = const(14) _BNO_HEADER_LEN = const(4) @@ -331,10 +331,10 @@ def is_error(cls, header): return False -class BNO080: - """Library for the BNO080 IMU from Hillcrest Laboratories +class BNO08X: + """Library for the BNO08x IMUs from Hillcrest Laboratories - :param ~busio.I2C i2c_bus: The I2C bus the BNO080 is connected to. + :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. """ @@ -581,7 +581,7 @@ def _get_feature_enable_report( # TODO: add docs for available features def enable_feature(self, feature_id): - """Used to enable a given feature of the BNO080""" + """Used to enable a given feature of the BNO08x""" self._dbg("\n********** Enabling feature id:", feature_id, "**********") set_feature_report = self._get_feature_enable_report(feature_id) diff --git a/adafruit_bno080/debug.py b/adafruit_bno08x/debug.py similarity index 100% rename from adafruit_bno080/debug.py rename to adafruit_bno08x/debug.py diff --git a/adafruit_bno080/i2c.py b/adafruit_bno08x/i2c.py similarity index 91% rename from adafruit_bno080/i2c.py rename to adafruit_bno08x/i2c.py index f128912..96b87e5 100644 --- a/adafruit_bno080/i2c.py +++ b/adafruit_bno08x/i2c.py @@ -3,25 +3,25 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno080.BNO080` to use I2C + Subclass of `adafruit_bno08x.BNO08X` to use I2C """ from struct import pack_into import adafruit_bus_device.i2c_device as i2c_device -from . import BNO080, DATA_BUFFER_SIZE, const, Packet, PacketError +from . import BNO08X, DATA_BUFFER_SIZE, const, Packet, PacketError -_BNO080_DEFAULT_ADDRESS = const(0x4A) +_BNO08X_DEFAULT_ADDRESS = const(0x4A) -class BNO080_I2C(BNO080): - """Library for the BNO080 IMU from Hillcrest Laboratories +class BNO08X_I2C(BNO08X): + """Library for the BNO08x IMUs from Hillcrest Laboratories - :param ~busio.I2C i2c_bus: The I2C bus the BNO080 is connected to. + :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. """ def __init__( - self, i2c_bus, reset=None, address=_BNO080_DEFAULT_ADDRESS, debug=False + self, i2c_bus, reset=None, address=_BNO08X_DEFAULT_ADDRESS, debug=False ): self.bus_device_obj = i2c_device.I2CDevice(i2c_bus, address) super().__init__(reset, debug) diff --git a/adafruit_bno080/spi.py b/adafruit_bno08x/spi.py similarity index 93% rename from adafruit_bno080/spi.py rename to adafruit_bno08x/spi.py index 1c3f103..81efee3 100644 --- a/adafruit_bno080/spi.py +++ b/adafruit_bno08x/spi.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno080.BNO080` to use SPI + Subclass of `adafruit_bno08x.BNO08X` to use SPI """ import time @@ -11,22 +11,22 @@ from digitalio import Direction, Pull import adafruit_bus_device.spi_device as spi_device -from . import BNO080, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError +from . import BNO08X, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError -class BNO080_SPI(BNO080): - """Instantiate a `adafruit_bno080.BNO080_SPI` instance to communicate with +class BNO08X_SPI(BNO08X): + """Instantiate a `adafruit_bno08x.BNO08X_SPI` instance to communicate with the sensor using SPI Args: - spi_bus ([busio.SPI]): The SPI bus to use to communicate with the BNO080 + spi_bus ([busio.SPI]): The SPI bus to use to communicate with the BNO08x cs_pin ([digitalio.DigitalInOut]): The pin object to use for the SPI Chip Select debug (bool, optional): Enables print statements used for debugging. Defaults to False. """ - # """Library for the BNO080 IMU from Hillcrest Laboratories + # """Library for the BNO08x IMUs from Hillcrest Laboratories - # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. + # :param ~busio.SPI spi_bus: The SPI bus the BNO08x is connected to. # """ diff --git a/adafruit_bno080/uart.py b/adafruit_bno08x/uart.py similarity index 95% rename from adafruit_bno080/uart.py rename to adafruit_bno08x/uart.py index 1ea84cf..12a02d2 100644 --- a/adafruit_bno080/uart.py +++ b/adafruit_bno08x/uart.py @@ -3,13 +3,13 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno080.BNO080` to use UART + Subclass of `adafruit_bno08x.BNO08X` to use UART """ import time from struct import pack_into from . import ( - BNO080, + BNO08X, BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND, DATA_BUFFER_SIZE, @@ -18,10 +18,10 @@ ) -class BNO080_UART(BNO080): - """Library for the BNO080 IMU from Hillcrest Laboratories +class BNO08X_UART(BNO08X): + """Library for the BNO08x IMUs from Hillcrest Laboratories - :param uart: The UART devce the BNO080 is connected to. + :param uart: The UART devce the BNO08x is connected to. """ diff --git a/docs/api.rst b/docs/api.rst index d98d960..ecae971 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,5 +4,5 @@ .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" -.. automodule:: adafruit_bno080 +.. automodule:: adafruit_bno08x :members: diff --git a/docs/conf.py b/docs/conf.py index f82fa67..d718a77 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -42,7 +42,7 @@ master_doc = "index" # General information about the project. -project = "Adafruit BNO080 Library" +project = "Adafruit BNO08x Library" copyright = "2020 Bryan Siepert" author = "Bryan Siepert" @@ -145,8 +145,8 @@ latex_documents = [ ( master_doc, - "AdafruitBNO080Library.tex", - "AdafruitBNO080 Library Documentation", + "AdafruitBNO08XLibrary.tex", + "AdafruitBNO08X Library Documentation", author, "manual", ), @@ -159,8 +159,8 @@ man_pages = [ ( master_doc, - "AdafruitBNO080library", - "Adafruit BNO080 Library Documentation", + "AdafruitBNO08Xlibrary", + "Adafruit BNO08x Library Documentation", [author], 1, ), @@ -174,10 +174,10 @@ texinfo_documents = [ ( master_doc, - "AdafruitBNO080Library", - "Adafruit BNO080 Library Documentation", + "AdafruitBNO08XLibrary", + "Adafruit BNO08x Library Documentation", author, - "AdafruitBNO080Library", + "AdafruitBNO08XLibrary", "One line description of project.", "Miscellaneous", ), diff --git a/docs/index.rst b/docs/index.rst index af9f68a..193e210 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -26,13 +26,13 @@ Table of Contents .. toctree:: :caption: Related Products -* `Adafruit BNO080 Breakout `_ +* `Adafruit BNO08x Breakout `_ .. toctree:: :caption: Other Links - Download + Download CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat diff --git a/examples/bno080_quaternion_service.py b/examples/bno08x_quaternion_service.py similarity index 90% rename from examples/bno080_quaternion_service.py rename to examples/bno08x_quaternion_service.py index 616ee1e..fd77924 100644 --- a/examples/bno080_quaternion_service.py +++ b/examples/bno08x_quaternion_service.py @@ -6,10 +6,10 @@ from adafruit_ble import BLERadio from adafruit_ble_adafruit.adafruit_service import AdafruitServerAdvertisement from adafruit_ble_adafruit.quaternion_service import QuaternionService -from adafruit_bno080 import BNO080 +from adafruit_bno08x import BNO08X i2c = board.I2C() -bno = BNO080(i2c) +bno = BNO08X(i2c) quat_svc = QuaternionService() quat_svc.measurement_period = 50 @@ -19,7 +19,7 @@ # The Web Bluetooth dashboard identifies known boards by their # advertised name, not by advertising manufacturer data. -ble.name = "Adafruit Hillcrest Laboratories BNO080 Breakout" +ble.name = "Adafruit Hillcrest Laboratories BNO08x Breakout" adv = AdafruitServerAdvertisement() adv.pid = 0x8088 diff --git a/examples/bno080_simpletest.py b/examples/bno08x_simpletest.py similarity index 75% rename from examples/bno080_simpletest.py rename to examples/bno08x_simpletest.py index 56b6cb7..d340464 100644 --- a/examples/bno080_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -5,21 +5,21 @@ import board import busio from digitalio import DigitalInOut -import adafruit_bno080 -from adafruit_bno080.i2c import BNO080_I2C +import adafruit_bno08x +from adafruit_bno08x.i2c import BNO08X_I2C i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) reset_pin = DigitalInOut(board.D5) -bno = BNO080_I2C(i2c, reset=reset_pin, debug=False) +bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) -bno.enable_feature(adafruit_bno080.BNO_REPORT_ACCELEROMETER) -bno.enable_feature(adafruit_bno080.BNO_REPORT_GYROSCOPE) -bno.enable_feature(adafruit_bno080.BNO_REPORT_MAGNETIC_FIELD) -bno.enable_feature(adafruit_bno080.BNO_REPORT_LINEAR_ACCELERATION) -bno.enable_feature(adafruit_bno080.BNO_REPORT_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno080.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno080.BNO_REPORT_STEP_COUNTER) -bno.enable_feature(adafruit_bno080.BNO_REPORT_SHAKE_DETECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETIC_FIELD) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) while True: time.sleep(0.1) diff --git a/examples/bno080_simpletest_spi.py b/examples/bno08x_simpletest_spi.py similarity index 88% rename from examples/bno080_simpletest_spi.py rename to examples/bno08x_simpletest_spi.py index 355f75c..747a7dc 100644 --- a/examples/bno080_simpletest_spi.py +++ b/examples/bno08x_simpletest_spi.py @@ -5,7 +5,7 @@ import board import busio from digitalio import DigitalInOut, Direction -from adafruit_bno080.spi import BNO080_SPI +from adafruit_bno08x.spi import BNO08X_SPI # need to limit clock to 3Mhz spi = busio.SPI(board.SCK, MISO=board.MISO, MOSI=board.MOSI) @@ -22,7 +22,7 @@ reset_pin = DigitalInOut(board.D9) reset_pin.direction = Direction.INPUT -bno = BNO080_SPI(spi, cs, int_pin, wake_pin, reset_pin, debug=True) +bno = BNO08X_SPI(spi, cs, int_pin, wake_pin, reset_pin, debug=True) while True: print("getting quat") diff --git a/examples/bno080_simpletest_uart.py b/examples/bno08x_simpletest_uart.py similarity index 76% rename from examples/bno080_simpletest_uart.py rename to examples/bno08x_simpletest_uart.py index 6bb1263..8f652e2 100644 --- a/examples/bno080_simpletest_uart.py +++ b/examples/bno08x_simpletest_uart.py @@ -4,23 +4,23 @@ import time import board import busio -import adafruit_bno080 -from adafruit_bno080.uart import BNO080_UART +import adafruit_bno08x +from adafruit_bno08x.uart import BNO08X_UART # import serial # uart = serial.Serial("COM49", baudrate=3000000, timeout=1) # print(uart.name) uart = busio.UART(board.TX, board.RX, baudrate=3000000, receiver_buffer_size=2048) -bno = BNO080_UART(uart, reset=None, debug=True) +bno = BNO08X_UART(uart, reset=None, debug=False) -bno.enable_feature(adafruit_bno080.BNO_REPORT_ACCELEROMETER) -bno.enable_feature(adafruit_bno080.BNO_REPORT_GYROSCOPE) -bno.enable_feature(adafruit_bno080.BNO_REPORT_MAGNETIC_FIELD) -bno.enable_feature(adafruit_bno080.BNO_REPORT_LINEAR_ACCELERATION) -bno.enable_feature(adafruit_bno080.BNO_REPORT_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno080.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno080.BNO_REPORT_STEP_COUNTER) -bno.enable_feature(adafruit_bno080.BNO_REPORT_SHAKE_DETECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETIC_FIELD) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) while True: time.sleep(0.1) diff --git a/setup.py b/setup.py index e1e3f89..6ea0ea0 100644 --- a/setup.py +++ b/setup.py @@ -26,11 +26,11 @@ name="adafruit-circuitpython-bno080", use_scm_version=True, setup_requires=["setuptools_scm"], - description="Helper library for the Hillcrest Laboratories BNO080 IMU", + description="Helper library for the Hillcrest Laboratories BNO08x IMUs", long_description=long_description, long_description_content_type="text/x-rst", # The project's main homepage. - url="https://github.com/adafruit/Adafruit_CircuitPython_BNO080", + url="https://github.com/adafruit/Adafruit_CircuitPython_BNO08x", # Author details author="Adafruit Industries", author_email="circuitpython@adafruit.com", @@ -55,5 +55,5 @@ # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=["adafruit_bno080"], + py_modules=["adafruit_bno08x"], ) From 0f2f4fcbf077aca5eae6bbe34bcfdb2dc4bbe26e Mon Sep 17 00:00:00 2001 From: siddacious Date: Wed, 9 Sep 2020 15:06:40 -0700 Subject: [PATCH 020/106] fixing dox build --- README.rst | 8 ++++---- docs/conf.py | 2 +- docs/examples.rst | 4 ++-- setup.py | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.rst b/README.rst index 2221df7..8dfad15 100644 --- a/README.rst +++ b/README.rst @@ -35,17 +35,17 @@ Installing from PyPI ===================== On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from -PyPI `_. To install for current user: +PyPI `_. To install for current user: .. code-block:: shell - pip3 install adafruit-circuitpython-bno080 + pip3 install adafruit-circuitpython-bno08x To install system-wide (this may be required in some cases): .. code-block:: shell - sudo pip3 install adafruit-circuitpython-bno080 + sudo pip3 install adafruit-circuitpython-bno08x To install in a virtual environment in your current project: @@ -54,7 +54,7 @@ To install in a virtual environment in your current project: mkdir project-name && cd project-name python3 -m venv .env source .env/bin/activate - pip3 install adafruit-circuitpython-bno080 + pip3 install adafruit-circuitpython-bno08x Usage Example ============= diff --git a/docs/conf.py b/docs/conf.py index d718a77..e76ae80 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -124,7 +124,7 @@ html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = "AdafruitBno080Librarydoc" +htmlhelp_basename = "AdafruitBno08xLibrarydoc" # -- Options for LaTeX output --------------------------------------------- diff --git a/docs/examples.rst b/docs/examples.rst index ad20161..f7dd4b3 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -3,6 +3,6 @@ Simple test Ensure your device works with this simple test. -.. literalinclude:: ../examples/bno080_simpletest.py - :caption: examples/bno080_simpletest.py +.. literalinclude:: ../examples/bno08x_simpletest.py + :caption: examples/bno08x_simpletest.py :linenos: diff --git a/setup.py b/setup.py index 6ea0ea0..2b96a55 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ long_description = f.read() setup( - name="adafruit-circuitpython-bno080", + name="adafruit-circuitpython-bno08x", use_scm_version=True, setup_requires=["setuptools_scm"], description="Helper library for the Hillcrest Laboratories BNO08x IMUs", @@ -50,7 +50,7 @@ ], # What does your project relate to? keywords="adafruit blinka circuitpython micropython bno080 IMU BNO055 SENSOR FUSION VR " - "MOTION TRACK", + "MOTION TRACK BNO085", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, From e2d680e72920402af02317fd92eb05206a914efc Mon Sep 17 00:00:00 2001 From: siddacious Date: Fri, 4 Sep 2020 18:59:05 -0700 Subject: [PATCH 021/106] added stability classifier, linted (mostly) --- adafruit_bno080/spi.py | 168 ++++++++++++++++++++++++++++++++++ adafruit_bno08x/__init__.py | 58 ++++++++++-- adafruit_bno08x/debug.py | 2 - examples/bno08x_simpletest.py | 3 + 4 files changed, 221 insertions(+), 10 deletions(-) create mode 100644 adafruit_bno080/spi.py diff --git a/adafruit_bno080/spi.py b/adafruit_bno080/spi.py new file mode 100644 index 0000000..cca5e71 --- /dev/null +++ b/adafruit_bno080/spi.py @@ -0,0 +1,168 @@ +# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries +# +# SPDX-License-Identifier: MIT +""" + + Subclass of `adafruit_bno080.BNO080` to use SPI + +""" +from time import sleep +from struct import pack_into + +import board +from digitalio import DigitalInOut, Direction +import adafruit_bus_device.spi_device as spi_device + +from . import BNO080, DATA_BUFFER_SIZE, const, Packet + +# should be removeable; I _think_ something else should be able to prep the buffers? + +_BNO080_DEFAULT_ADDRESS = const(0x4A) + + +class BNO080_SPI(BNO080): + """Instantiate a `adafruit_bno080.BNO080_SPI` instance to communicate with + the sensor using SPI + + Args: + spi_bus ([busio.SPI]): The SPI bus to use to communicate with the BNO080 + cs_pin ([digitalio.DigitalInOut]): The pin object to use for the SPI Chip Select + debug (bool, optional): Enables print statements used for debugging. Defaults to False. + """ + + # """Library for the BNO080 IMU from Hillcrest Laboratories + + # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. + # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. + + # """ + + def __init__( + self, spi_bus, cs_pin_obj, int_pin_obj, baudrate=100000, debug=False + ): # pylint:disable=too-many-arguments + self.bus_device_obj = spi_device.SPIDevice( + spi_bus, cs_pin_obj, baudrate=baudrate, polarity=1, phase=1 + ) + self._int_pin = int_pin_obj + + self._int_check_pin = DigitalInOut(board.D9) + self._int_check_pin.direction = Direction.OUTPUT + self._int_check_pin.value = False + + self._read_pin = DigitalInOut(board.D10) + self._read_pin.direction = Direction.OUTPUT + self._read_pin.value = False + + self._write_pin = DigitalInOut(board.D11) + self._write_pin.direction = Direction.OUTPUT + self._write_pin.value = False + + super().__init__(debug) + + def reset(self): + """Reset the sensor to an initial unconfigured state""" + self._dbg("Sleeping") + sleep(2.050) + + self._dbg("**** waiting for advertising packet **") + # read and disregard first initial advertising packet + # The BNO08X uses advertisements to publish the channel maps and the names + # of the built-in applications. + # _advertising_packet = self._wait_for_packet() + self._wait_for_packet_type(0) + + # read and disregard init completed packet + self._dbg("**** received packet; waiting for init complete packet **") + self._wait_for_packet_type(2, 0xF1) + print("INIT COMPLETE?!") + + # I think this and `_send_packet` should take a `Packet` + def _read_packet(self): + self._read_pin.value = True + + header = Packet.header_from_buffer(self._data_buffer) + + if header.data_length == 0: + self._read_pin.value = False + + raise RuntimeError("Zero bytes ready") + + read_length = header.data_length + self._read(read_length) + self._read_pin.value = False + + # TODO: Allocaiton + new_packet = Packet(self._data_buffer) + if self._debug: + print(new_packet) + self._update_sequence_number(new_packet) + + return new_packet + + ###### Actually send bytes ########## + # Note: I _think_ these can be used for either SPI or I2C in the base class by having the + # subclass set the 'bus_device_object' to a `bus_device`.SPI` or `bus_device.I2C` + + # returns true if all requested data was read + def _read(self, requested_read_length): + self._dbg("trying to read", requested_read_length, "bytes") + unread_bytes = 0 + # +4 for the header + total_read_length = requested_read_length + 4 + if total_read_length > DATA_BUFFER_SIZE: + unread_bytes = total_read_length - DATA_BUFFER_SIZE + total_read_length = DATA_BUFFER_SIZE + + with self.bus_device_obj as spi: + spi.readinto(self._data_buffer, end=total_read_length) + return unread_bytes > 0 + + def _send_packet(self, channel, data): + self._write_pin.value = True + self._dbg("Sending packet to channel", channel) + data_length = len(data) + write_length = data_length + 4 + + # struct.pack_into(fmt, buffer, offset, *values) + pack_into(" 0 @@ -445,9 +455,31 @@ def shake(self): # clear on read if shake_detected: self._readings[BNO_REPORT_SHAKE_DETECTOR] = False + return shake_detected except KeyError: raise RuntimeError("No shake report found, is it enabled?") from None + @property + def stability_classification(self): + """Returns the sensor's assessment of it's current stability, one of: + * "Unknown" - The sensor is unable to classify the current stability + * "On Table" - The sensor is at rest on a stable surface with very little vibration + * "Stationary" - The sensor’s motion is below the stable threshold but + the stable duration requirement has not been met. This output is only available when + gyro calibration is enabled + * "Stable" - The sensor’s motion has met the stable threshold and duration requirements. + * "In motion" - The sensor is moving. + + """ + self._process_available_packets() + try: + stability_classification = self._readings[BNO_REPORT_STABILITY_CLASSIFIER] + return stability_classification + except KeyError: + raise RuntimeError( + "No stability classification report found, is it enabled?" + ) from None + # # decorator? def _process_available_packets(self): processed_count = 0 @@ -549,6 +581,7 @@ def _process_report(self, report_id, report_bytes): if report_id == BNO_REPORT_STEP_COUNTER: self._readings[report_id] = _parse_step_couter_report(report_bytes) return + if report_id == BNO_REPORT_SHAKE_DETECTOR: shake_detected = _parse_shake_report(report_bytes) # shake not previously detected - auto cleared by 'shake' property @@ -559,7 +592,16 @@ def _process_report(self, report_id, report_bytes): pass return + if report_id == BNO_REPORT_STABILITY_CLASSIFIER: + stability_classification = _parse_stability_classifier_report( + report_bytes + ) + self._readings[ + BNO_REPORT_STABILITY_CLASSIFIER + ] = stability_classification + return sensor_data = _parse_sensor_report_data(report_bytes) + # TODO: FIXME; Sensor reports are batched in a LIFO which means that multiple reports # for the same type will end with the oldest/last being kept and the other # newer reports thrown away diff --git a/adafruit_bno08x/debug.py b/adafruit_bno08x/debug.py index 5d655a0..6534152 100644 --- a/adafruit_bno08x/debug.py +++ b/adafruit_bno08x/debug.py @@ -90,7 +90,6 @@ # _BNO_REPORT_TAP_DETECTOR = const(0x10) # _BNO_REPORT_STEP_COUNTER = const(0x11) # _BNO_REPORT_SIGNIFICANT_MOTION = const(0x12) -# _BNO_REPORT_STABILITY_CLASSIFIER = const(0x13)) # _BNO_REPORT_SAR = const(0x17) # _BNO_REPORT_STEP_DETECTOR = const(0x18) @@ -98,7 +97,6 @@ # _BNO_REPORT_FLIP_DETECTOR = const(0x1A) # _BNO_REPORT_PICKUP_DETECTOR = const(0x1B) # _BNO_REPORT_STABILITY_DETECTOR = const(0x1C) -# _BNO_REPORT_PERSONAL_ACTIVITY_CLASSIFIER = const(0x1E) # _BNO_REPORT_SLEEP_DETECTOR = const(0x1F) # _BNO_REPORT_TILT_DETECTOR = const(0x20) # _BNO_REPORT_POCKET_DETECTOR = const(0x21) diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index d340464..d748900 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -73,6 +73,9 @@ print("Steps detected:", bno.steps) print("") + print("Stability classification:", bno.stability_classification) + print("") + if bno.shake: print("SHAKE DETECTED!") print("") From d443ffc53c759e3e9b879a78dbf05982740c80b3 Mon Sep 17 00:00:00 2001 From: siddacious Date: Tue, 8 Sep 2020 16:43:55 -0700 Subject: [PATCH 022/106] started activity classifier --- adafruit_bno080/spi.py | 168 ---------------------------------- adafruit_bno08x/__init__.py | 85 ++++++++++++++++- examples/bno08x_simpletest.py | 4 + 3 files changed, 85 insertions(+), 172 deletions(-) delete mode 100644 adafruit_bno080/spi.py diff --git a/adafruit_bno080/spi.py b/adafruit_bno080/spi.py deleted file mode 100644 index cca5e71..0000000 --- a/adafruit_bno080/spi.py +++ /dev/null @@ -1,168 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries -# -# SPDX-License-Identifier: MIT -""" - - Subclass of `adafruit_bno080.BNO080` to use SPI - -""" -from time import sleep -from struct import pack_into - -import board -from digitalio import DigitalInOut, Direction -import adafruit_bus_device.spi_device as spi_device - -from . import BNO080, DATA_BUFFER_SIZE, const, Packet - -# should be removeable; I _think_ something else should be able to prep the buffers? - -_BNO080_DEFAULT_ADDRESS = const(0x4A) - - -class BNO080_SPI(BNO080): - """Instantiate a `adafruit_bno080.BNO080_SPI` instance to communicate with - the sensor using SPI - - Args: - spi_bus ([busio.SPI]): The SPI bus to use to communicate with the BNO080 - cs_pin ([digitalio.DigitalInOut]): The pin object to use for the SPI Chip Select - debug (bool, optional): Enables print statements used for debugging. Defaults to False. - """ - - # """Library for the BNO080 IMU from Hillcrest Laboratories - - # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. - # :param ~busio.SPI spi_bus: The SPI bus the BNO080 is connected to. - - # """ - - def __init__( - self, spi_bus, cs_pin_obj, int_pin_obj, baudrate=100000, debug=False - ): # pylint:disable=too-many-arguments - self.bus_device_obj = spi_device.SPIDevice( - spi_bus, cs_pin_obj, baudrate=baudrate, polarity=1, phase=1 - ) - self._int_pin = int_pin_obj - - self._int_check_pin = DigitalInOut(board.D9) - self._int_check_pin.direction = Direction.OUTPUT - self._int_check_pin.value = False - - self._read_pin = DigitalInOut(board.D10) - self._read_pin.direction = Direction.OUTPUT - self._read_pin.value = False - - self._write_pin = DigitalInOut(board.D11) - self._write_pin.direction = Direction.OUTPUT - self._write_pin.value = False - - super().__init__(debug) - - def reset(self): - """Reset the sensor to an initial unconfigured state""" - self._dbg("Sleeping") - sleep(2.050) - - self._dbg("**** waiting for advertising packet **") - # read and disregard first initial advertising packet - # The BNO08X uses advertisements to publish the channel maps and the names - # of the built-in applications. - # _advertising_packet = self._wait_for_packet() - self._wait_for_packet_type(0) - - # read and disregard init completed packet - self._dbg("**** received packet; waiting for init complete packet **") - self._wait_for_packet_type(2, 0xF1) - print("INIT COMPLETE?!") - - # I think this and `_send_packet` should take a `Packet` - def _read_packet(self): - self._read_pin.value = True - - header = Packet.header_from_buffer(self._data_buffer) - - if header.data_length == 0: - self._read_pin.value = False - - raise RuntimeError("Zero bytes ready") - - read_length = header.data_length - self._read(read_length) - self._read_pin.value = False - - # TODO: Allocaiton - new_packet = Packet(self._data_buffer) - if self._debug: - print(new_packet) - self._update_sequence_number(new_packet) - - return new_packet - - ###### Actually send bytes ########## - # Note: I _think_ these can be used for either SPI or I2C in the base class by having the - # subclass set the 'bus_device_object' to a `bus_device`.SPI` or `bus_device.I2C` - - # returns true if all requested data was read - def _read(self, requested_read_length): - self._dbg("trying to read", requested_read_length, "bytes") - unread_bytes = 0 - # +4 for the header - total_read_length = requested_read_length + 4 - if total_read_length > DATA_BUFFER_SIZE: - unread_bytes = total_read_length - DATA_BUFFER_SIZE - total_read_length = DATA_BUFFER_SIZE - - with self.bus_device_obj as spi: - spi.readinto(self._data_buffer, end=total_read_length) - return unread_bytes > 0 - - def _send_packet(self, channel, data): - self._write_pin.value = True - self._dbg("Sending packet to channel", channel) - data_length = len(data) - write_length = data_length + 4 - - # struct.pack_into(fmt, buffer, offset, *values) - pack_into(" Date: Wed, 9 Sep 2020 19:48:57 -0700 Subject: [PATCH 023/106] activity classifier working in isolation --- adafruit_bno08x/__init__.py | 70 +++++++++++++------- examples/bno08x_simpletest.py | 120 ++++++++++++++++++---------------- 2 files changed, 110 insertions(+), 80 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 5557c80..f340e8d 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -131,10 +131,12 @@ BNO_REPORT_STEP_COUNTER: (1, 1, 12), BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), BNO_REPORT_STABILITY_CLASSIFIER: (1, 1, 6), - BNO_REPORT_ACTIVITY_CLASSIFIER: (1, 1, 6), + BNO_REPORT_ACTIVITY_CLASSIFIER: (1, 1, 16), } -_ENABLED_ACTIVITIES = 0x1FF #All activities; 1 bit set for each of 8 activities, + Unknown +_ENABLED_ACTIVITIES = ( + 0x1FF # All activities; 1 bit set for each of 8 activities, + Unknown +) DATA_BUFFER_SIZE = const(512) # data buffer size. obviously eats ram PacketHeader = namedtuple( @@ -170,6 +172,7 @@ def wrapper_timer(*args, **kwargs): def _parse_sensor_report_data(report_bytes): + """Parses reports with only 16-bit fields""" data_offset = 4 # this may not always be true report_id = report_bytes[0] scalar, count, _report_length = _AVAIL_SENSOR_REPORTS[report_id] @@ -194,6 +197,8 @@ def _parse_stability_classifier_report(report_bytes): return ["Unknown", "On Table", "Stationary", "Stable", "In motion"][ classification_bitfield ] + + # 0 Report ID = 0x1E # 1 Sequence number # 2 Status @@ -214,21 +219,41 @@ def _parse_stability_classifier_report(report_bytes): # 15 Classification(10 x Page Number) + 9 confidence -def _parse_activity_classifier_report(report_bytes): - # 0 Unknown - # 1 In-Vehicle - # 2 On-Bicycle - # 3 On-Foot - # 4 Still - # 5 Tilting - # 6 Walking - # 7 Running - # 8 OnStairs - most_likely_activity = unpack_from(" 0 + page_number = end_and_page_number & 0x7F + most_likely = unpack_from(" Date: Thu, 10 Sep 2020 15:01:58 -0700 Subject: [PATCH 024/106] activity classifier working with other reports --- adafruit_bno08x/__init__.py | 64 ++++++++++--------- examples/bno08x_simpletest.py | 114 +++++++++++++++++----------------- 2 files changed, 94 insertions(+), 84 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index f340e8d..a04dac2 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -93,6 +93,7 @@ _DEFAULT_REPORT_INTERVAL = const(50000) # in microseconds = 50ms _QUAT_READ_TIMEOUT = 0.500 # timeout in seconds _PACKET_READ_TIMEOUT = 15.000 # timeout in seconds +_FEATURE_ENABLE_TIMEOUT = 2.0 _BNO08X_CMD_RESET = const(0x01) _QUAT_Q_POINT = const(14) _BNO_HEADER_LEN = const(4) @@ -126,13 +127,30 @@ BNO_REPORT_GYROSCOPE: (_Q_POINT_9_SCALAR, 3, 10), BNO_REPORT_MAGNETIC_FIELD: (_Q_POINT_4_SCALAR, 3, 10), BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), - BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14,), + BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14), BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), BNO_REPORT_STEP_COUNTER: (1, 1, 12), BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), BNO_REPORT_STABILITY_CLASSIFIER: (1, 1, 6), BNO_REPORT_ACTIVITY_CLASSIFIER: (1, 1, 16), } +_INITIAL_REPORTS = { + BNO_REPORT_ACTIVITY_CLASSIFIER: { + "Tilting": -1, + "most_likely": "Unknown", + "OnStairs": -1, + "On-Foot": -1, + "Other": -1, + "On-Bicycle": -1, + "Still": -1, + "Walking": -1, + "Unknown": -1, + "Running": -1, + "In-Vehicle": -1, + }, + BNO_REPORT_STABILITY_CLASSIFIER: "Unknown", + BNO_REPORT_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), +} _ENABLED_ACTIVITIES = ( 0x1FF # All activities; 1 bit set for each of 8 activities, + Unknown @@ -199,27 +217,17 @@ def _parse_stability_classifier_report(report_bytes): ] +def _parse_get_feature_response_report(report_bytes): + return unpack_from(" 0 page_number = end_and_page_number & 0x7F most_likely = unpack_from(" Date: Thu, 10 Sep 2020 17:21:06 -0700 Subject: [PATCH 025/106] raw reading working, partially --- adafruit_bno08x/__init__.py | 88 +++++++++++++++++++++++------- adafruit_bno08x/i2c.py | 4 +- examples/bno08x_simpletest.py | 37 ++++++++++++- examples/bno08x_simpletest_uart.py | 2 +- 4 files changed, 105 insertions(+), 26 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index a04dac2..83fa22c 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -70,29 +70,31 @@ # Calibrated gyroscope (rad/s). BNO_REPORT_GYROSCOPE = const(0x02) # Magnetic field calibrated (in µTesla). The fully calibrated magnetic field measurement. -BNO_REPORT_MAGNETIC_FIELD = const(0x03) +BNO_REPORT_MAGNETOMETER = const(0x03) # Linear acceleration (m/s2). Acceleration of the device with gravity removed BNO_REPORT_LINEAR_ACCELERATION = const(0x04) # Rotation Vector BNO_REPORT_ROTATION_VECTOR = const(0x05) BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) BNO_REPORT_STEP_COUNTER = const(0x11) + +BNO_REPORT_RAW_ACCELEROMETER = const(0x14) +BNO_REPORT_RAW_GYROSCOPE = const(0x15) +BNO_REPORT_RAW_MAGNETOMETER = const(0x16) BNO_REPORT_SHAKE_DETECTOR = const(0x19) BNO_REPORT_STABILITY_CLASSIFIER = const(0x13) BNO_REPORT_ACTIVITY_CLASSIFIER = const(0x1E) BNO_REPORT_GYRO_INTEGRATED_ROTATION_VECTOR = const(0x2A) # TODOz: -# Activity Classification # Calibrated Acceleration (m/s2) # Euler Angles (in degrees?) # CALIBRATION -# TIMESTAMP # RAW ACCEL, MAG, GYRO # Sfe says each needs the non-raw enabled to work _DEFAULT_REPORT_INTERVAL = const(50000) # in microseconds = 50ms _QUAT_READ_TIMEOUT = 0.500 # timeout in seconds -_PACKET_READ_TIMEOUT = 15.000 # timeout in seconds +_PACKET_READ_TIMEOUT = 2.000 # timeout in seconds _FEATURE_ENABLE_TIMEOUT = 2.0 _BNO08X_CMD_RESET = const(0x01) _QUAT_Q_POINT = const(14) @@ -110,8 +112,6 @@ _QUAT_SCALAR = _Q_POINT_14_SCALAR _GEO_QUAT_SCALAR = _Q_POINT_12_SCALAR _MAG_SCALAR = _Q_POINT_4_SCALAR -# _QUAT_RADIAN_ACCURACY_SCALAR = _Q_POINT_12_SCALAR -# _ANGULAR_VELOCITY_SCALAR = _Q_POINT_10_SCALAR _REPORT_LENGTHS = { _SHTP_REPORT_PRODUCT_ID_RESPONSE: 16, @@ -121,11 +121,16 @@ _BNO_CMD_BASE_TIMESTAMP: 5, _BNO_CMD_TIMESTAMP_REBASE: 5, } -# length is probably deterministic, like axes * 2 +4 +# these raw reports require their counterpart to be enabled +_RAW_REPORTS = { + BNO_REPORT_RAW_ACCELEROMETER: BNO_REPORT_ACCELEROMETER, + BNO_REPORT_RAW_GYROSCOPE: BNO_REPORT_GYROSCOPE, + BNO_REPORT_RAW_MAGNETOMETER: BNO_REPORT_MAGNETOMETER, +} _AVAIL_SENSOR_REPORTS = { BNO_REPORT_ACCELEROMETER: (_Q_POINT_8_SCALAR, 3, 10), BNO_REPORT_GYROSCOPE: (_Q_POINT_9_SCALAR, 3, 10), - BNO_REPORT_MAGNETIC_FIELD: (_Q_POINT_4_SCALAR, 3, 10), + BNO_REPORT_MAGNETOMETER: (_Q_POINT_4_SCALAR, 3, 10), BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14), BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), @@ -133,6 +138,9 @@ BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), BNO_REPORT_STABILITY_CLASSIFIER: (1, 1, 6), BNO_REPORT_ACTIVITY_CLASSIFIER: (1, 1, 16), + BNO_REPORT_RAW_ACCELEROMETER: (1, 3, 16), + BNO_REPORT_RAW_GYROSCOPE: (1, 3, 16), + BNO_REPORT_RAW_MAGNETOMETER: (1, 3, 16), } _INITIAL_REPORTS = { BNO_REPORT_ACTIVITY_CLASSIFIER: { @@ -189,17 +197,22 @@ def wrapper_timer(*args, **kwargs): return wrapper_timer +############ PACKET PARSING ########################### def _parse_sensor_report_data(report_bytes): """Parses reports with only 16-bit fields""" data_offset = 4 # this may not always be true report_id = report_bytes[0] scalar, count, _report_length = _AVAIL_SENSOR_REPORTS[report_id] - + if report_id in _RAW_REPORTS: + # raw reports are unsigned + format_str = " Date: Thu, 10 Sep 2020 18:27:10 -0700 Subject: [PATCH 026/106] raw reports working with others --- adafruit_bno08x/__init__.py | 115 +++++++++++++++++----------------- examples/bno08x_simpletest.py | 8 +-- 2 files changed, 62 insertions(+), 61 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 83fa22c..1f05917 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -230,6 +230,13 @@ def _parse_stability_classifier_report(report_bytes): ] +# report_id +# feature_report_id +# feature_flags +# change_sensitivity +# report_interval +# batch_interval_word +# sensor_specific_configuration_word def _parse_get_feature_response_report(report_bytes): return unpack_from(" 0 + # last_page = (end_and_page_number & 0b10000000) > 0 page_number = end_and_page_number & 0x7F most_likely = unpack_from("= 0xF0: + self._handle_control_report(report_id, report_bytes) + return + self._dbg("\tProcessing report:", reports[report_id]) + if self._debug: + outstr = "" + for idx, packet_byte in enumerate(report_bytes): + packet_index = idx + if (packet_index % 4) == 0: + outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) + outstr += "0x{:02X} ".format(packet_byte) + print(outstr) + self._dbg("") - if report_id == BNO_REPORT_SHAKE_DETECTOR: - shake_detected = _parse_shake_report(report_bytes) - # shake not previously detected - auto cleared by 'shake' property - try: - if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: - self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected - except KeyError: - pass - return + if report_id == BNO_REPORT_STEP_COUNTER: + self._readings[report_id] = _parse_step_couter_report(report_bytes) + return - if report_id == BNO_REPORT_STABILITY_CLASSIFIER: - stability_classification = _parse_stability_classifier_report( - report_bytes - ) - self._readings[ - BNO_REPORT_STABILITY_CLASSIFIER - ] = stability_classification - return + if report_id == BNO_REPORT_SHAKE_DETECTOR: + shake_detected = _parse_shake_report(report_bytes) + # shake not previously detected - auto cleared by 'shake' property + try: + if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: + self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected + except KeyError: + pass + return - if report_id == BNO_REPORT_ACTIVITY_CLASSIFIER: - activity_classification = _parse_activity_classifier_report( - report_bytes - ) - self._readings[BNO_REPORT_ACTIVITY_CLASSIFIER] = activity_classification - return + if report_id == BNO_REPORT_STABILITY_CLASSIFIER: + stability_classification = _parse_stability_classifier_report(report_bytes) + self._readings[BNO_REPORT_STABILITY_CLASSIFIER] = stability_classification + return - sensor_data = _parse_sensor_report_data(report_bytes) + if report_id == BNO_REPORT_ACTIVITY_CLASSIFIER: + activity_classification = _parse_activity_classifier_report(report_bytes) + self._readings[BNO_REPORT_ACTIVITY_CLASSIFIER] = activity_classification + return - # TODO: FIXME; Sensor reports are batched in a LIFO which means that multiple reports - # for the same type will end with the oldest/last being kept and the other - # newer reports thrown away - self._readings[report_id] = sensor_data - else: - self._handle_control_report(report_id, report_bytes) + sensor_data = _parse_sensor_report_data(report_bytes) + + # TODO: FIXME; Sensor reports are batched in a LIFO which means that multiple reports + # for the same type will end with the oldest/last being kept and the other + # newer reports thrown away + self._readings[report_id] = sensor_data # TODO: Make this a Packet creation @staticmethod @@ -779,8 +787,8 @@ def enable_feature(self, feature_id): set_feature_report = self._get_feature_enable_report(feature_id) feature_dependency = _RAW_REPORTS.get(feature_id, None) - if feature_dependency: - # if feature_dependency and not feature_dependency in self._reports: + # if the feature was enabled it will have a key in the readings dict + if feature_dependency and feature_dependency not in self._readings: self._dbg("Enabling feature depencency:", feature_dependency) self.enable_feature(feature_dependency) @@ -790,15 +798,8 @@ def enable_feature(self, feature_id): start_time = time.monotonic() # 1 while _elapsed(start_time) < _FEATURE_ENABLE_TIMEOUT: - packet = self._wait_for_packet_type( - _BNO_CHANNEL_CONTROL, _BNO_CMD_GET_FEATURE_RESPONSE - ) - print(packet) - if packet.data[1] == feature_id: - # if there is a custom format, get it. Otherwise default to 3 16-bit axes - self._readings[feature_id] = _INITIAL_REPORTS.get( - feature_id, (0.0, 0.0, 0.0) - ) + self._process_available_packets() + if feature_id in self._readings: return raise RuntimeError("Was not able to enable feature", feature_id) diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 6b30637..5027f80 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -12,9 +12,10 @@ reset_pin = DigitalInOut(board.D5) bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) -# bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) -# bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) -# bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) +# TODO: UPDATE UART/SPI +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) @@ -119,4 +120,3 @@ if bno.shake: print("SHAKE DETECTED!") print("") - From fba175b8b3a9aea0a627a235615cb33dc3f6c53b Mon Sep 17 00:00:00 2001 From: siddacious Date: Thu, 10 Sep 2020 19:15:10 -0700 Subject: [PATCH 027/106] added game rotation quaternion --- adafruit_bno08x/__init__.py | 29 ++++++++++++++++++++++++----- examples/bno08x_simpletest.py | 17 ++++++++++++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 1f05917..e938ae0 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -75,7 +75,10 @@ BNO_REPORT_LINEAR_ACCELERATION = const(0x04) # Rotation Vector BNO_REPORT_ROTATION_VECTOR = const(0x05) +BNO_REPORT_GAME_ROTATION_VECTOR = const(0x08) + BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) + BNO_REPORT_STEP_COUNTER = const(0x11) BNO_REPORT_RAW_ACCELEROMETER = const(0x14) @@ -134,6 +137,7 @@ BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), BNO_REPORT_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 14), BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (_Q_POINT_12_SCALAR, 4, 14), + BNO_REPORT_GAME_ROTATION_VECTOR: (_Q_POINT_14_SCALAR, 4, 12), BNO_REPORT_STEP_COUNTER: (1, 1, 12), BNO_REPORT_SHAKE_DETECTOR: (1, 1, 6), BNO_REPORT_STABILITY_CLASSIFIER: (1, 1, 6), @@ -485,6 +489,20 @@ def geomagnetic_quaternion(self): "No geomag quaternion report found, is it enabled?" ) from None + @property + def game_quaternion(self): + """A quaternion representing the current rotation vector expressed as a quaternion with no + specific reference for heading, while roll and pitch are referenced against gravity. To + prevent sudden jumps in heading due to corrections, the `game_quaternion` property is not + corrected using the magnetometer. Some drift is expected""" + self._process_available_packets() + try: + return self._readings[BNO_REPORT_GAME_ROTATION_VECTOR] + except KeyError: + raise RuntimeError( + "No game quaternion report found, is it enabled?" + ) from None + @property def steps(self): """The number of steps detected since the sensor was initialized""" @@ -545,11 +563,12 @@ def shake(self): @property def stability_classification(self): """Returns the sensor's assessment of it's current stability, one of: + * "Unknown" - The sensor is unable to classify the current stability * "On Table" - The sensor is at rest on a stable surface with very little vibration - * "Stationary" - The sensor’s motion is below the stable threshold but - the stable duration requirement has not been met. This output is only available when - gyro calibration is enabled + * "Stationary" - The sensor’s motion is below the stable threshold but\ + the stable duration requirement has not been met. This output is only available when\ + gyro calibration is enabled * "Stable" - The sensor’s motion has met the stable threshold and duration requirements. * "In motion" - The sensor is moving. @@ -565,10 +584,10 @@ def stability_classification(self): @property def activity_classification(self): - """Returns the sensor's assessment of the activity that is creating the motions + """Returns the sensor's assessment of the activity that is creating the motions\ it's sensing, one of: - * "Unknown" - The sensor is unable to classify the current activity + * "Unknown" * "In-Vehicle" * "On-Bicycle" * "On-Foot" diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 5027f80..67486db 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -19,6 +19,7 @@ bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR) bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_STABILITY_CLASSIFIER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACTIVITY_CLASSIFIER) @@ -72,7 +73,21 @@ geo_quat_real, ) = bno.geomagnetic_quaternion # pylint:disable=no-member print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) + "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + % (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real) + ) + # print("") + + print("Game Rotation Vector Quaternion:") + ( + game_quat_i, + game_quat_j, + game_quat_k, + game_quat_real, + ) = bno.game_quaternion # pylint:disable=no-member + print( + "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) ) print("") From 89772692ed699b6e7fd994c0150c10e90f2b4a51 Mon Sep 17 00:00:00 2001 From: siddacious Date: Fri, 11 Sep 2020 19:52:05 -0700 Subject: [PATCH 028/106] saving calibration progress --- adafruit_bno08x/__init__.py | 192 +++++++++++++++++++++++++++++---- examples/bno08x_calibration.py | 45 ++++++++ 2 files changed, 217 insertions(+), 20 deletions(-) create mode 100644 examples/bno08x_calibration.py diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index e938ae0..4171a34 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -44,26 +44,30 @@ _BNO_CHANNEL_WAKE_INPUT_SENSOR_REPORTS = const(4) _BNO_CHANNEL_GYRO_ROTATION_VECTOR = const(5) -_BNO_CMD_GET_FEATURE_REQUEST = const(0xFE) -_BNO_CMD_SET_FEATURE_COMMAND = const(0xFD) -_BNO_CMD_GET_FEATURE_RESPONSE = const(0xFC) -_BNO_CMD_BASE_TIMESTAMP = const(0xFB) +_GET_FEATURE_REQUEST = const(0xFE) +_SET_FEATURE_COMMAND = const(0xFD) +_GET_FEATURE_RESPONSE = const(0xFC) +_BASE_TIMESTAMP = const(0xFB) -_BNO_CMD_TIMESTAMP_REBASE = const(0xFA) +_TIMESTAMP_REBASE = const(0xFA) _SHTP_REPORT_PRODUCT_ID_RESPONSE = const(0xF8) _SHTP_REPORT_PRODUCT_ID_REQUEST = const(0xF9) -_BNO_CMD_FRS_WRITE_REQUEST = const(0xF7) -_BNO_CMD_FRS_WRITE_DATA = const(0xF6) -_BNO_CMD_FRS_WRITE_RESPONSE = const(0xF5) +_FRS_WRITE_REQUEST = const(0xF7) +_FRS_WRITE_DATA = const(0xF6) +_FRS_WRITE_RESPONSE = const(0xF5) -_BNO_CMD_FRS_READ_REQUEST = const(0xF4) -_BNO_CMD_FRS_READ_RESPONSE = const(0xF3) +_FRS_READ_REQUEST = const(0xF4) +_FRS_READ_RESPONSE = const(0xF3) -_BNO_CMD_COMMAND_REQUEST = const(0xF2) -_BNO_CMD_COMMAND_RESPONSE = const(0xF1) +_COMMAND_REQUEST = const(0xF2) +_COMMAND_RESPONSE = const(0xF1) +# DCD/ ME Calibration commands and sub-commands +_SAVE_DCD = const(0x6) +_ME_CALIBRATE = const(0x7) +_ME_CAL_CONFIG = const(0x00) # Calibrated Acceleration (m/s2) BNO_REPORT_ACCELEROMETER = const(0x01) @@ -99,6 +103,7 @@ _QUAT_READ_TIMEOUT = 0.500 # timeout in seconds _PACKET_READ_TIMEOUT = 2.000 # timeout in seconds _FEATURE_ENABLE_TIMEOUT = 2.0 +_DEFAULT_TIMEOUT = 2.0 _BNO08X_CMD_RESET = const(0x01) _QUAT_Q_POINT = const(14) _BNO_HEADER_LEN = const(4) @@ -118,11 +123,11 @@ _REPORT_LENGTHS = { _SHTP_REPORT_PRODUCT_ID_RESPONSE: 16, - _BNO_CMD_GET_FEATURE_RESPONSE: 17, - _BNO_CMD_COMMAND_RESPONSE: 16, + _GET_FEATURE_RESPONSE: 17, + _COMMAND_RESPONSE: 16, _SHTP_REPORT_PRODUCT_ID_RESPONSE: 16, - _BNO_CMD_BASE_TIMESTAMP: 5, - _BNO_CMD_TIMESTAMP_REBASE: 5, + _BASE_TIMESTAMP: 5, + _TIMESTAMP_REBASE: 5, } # these raw reports require their counterpart to be enabled _RAW_REPORTS = { @@ -299,6 +304,41 @@ def parse_sensor_id(buffer): return (sw_part_number, sw_major, sw_minor, sw_patch, sw_build_number) +def _parse_command_response(report_bytes): + + # CMD response report: + # 0 Report ID = 0xF1 + # 1 Sequence number + # 2 Command + # 3 Command sequence number + # 4 Response sequence number + # 5 R0-10 A set of response values. The interpretation of these values is specific + # to the response for each command. + report_body = unpack_from(" 9: + raise AttributeError( + "Command request reports can only have up to 9 arguments but %d were given" + % len(command_params) + ) + for _i in range(12): + buffer[_i] = 0 + buffer[0] = _COMMAND_REQUEST + buffer[1] = next_sequence_number + buffer[2] = command + if command_params is None: + return + + for idx, param in enumerate(command_params): + buffer[4 + 3 + idx] = param + + def _report_length(report_id): if report_id < 0xF0: # it's a sensor report return _AVAIL_SENSOR_REPORTS[report_id][2] @@ -327,6 +367,15 @@ def _separate_batch(packet, report_slices): next_byte_index = next_byte_index + required_bytes +# class Report: +# _buffer = bytearray(DATA_BUFFER_SIZE) +# _report_obj = Report(_buffer) + +# @classmethod +# def get_report(cls) +# return cls._report_obj + + class Packet: """A class representing a Hillcrest LaboratorySensor Hub Transport packet""" @@ -440,10 +489,17 @@ def __init__(self, reset=None, debug=False): self._reset = reset self._dbg("********** __init__ *************") self._data_buffer = bytearray(DATA_BUFFER_SIZE) + self._command_buffer = bytearray(12) self._packet_slices = [] # TODO: this is wrong there should be one per channel per direction self._sequence_number = [0, 0, 0, 0, 0, 0] + self._two_ended_sequence_numbers = { + "send": {}, # holds the next seq number to send with the report id as a key + "receive": {}, + } + self._dcd_saved_at = -1 + self._me_calibration_started_at = -1 # self._sequence_number = {"in": [0, 0, 0, 0, 0, 0], "out": [0, 0, 0, 0, 0, 0]} # sef self._wait_for_initialize = True @@ -639,6 +695,81 @@ def raw_magnetic(self): except KeyError: raise RuntimeError("No raw magnetic report found, is it enabled?") from None + def begin_calibration(self): + # start calibration for accel, gyro, and mag + self._send_me_command( + [ + 1, # calibrate accel + 1, # calibrate gyro + 1, # calibrate mag + _ME_CAL_CONFIG, + 0, # calibrate planar acceleration + 0, # 'on_table' calibration + 0, # reserved + 0, # reserved + 0, # reserved + ] + ) + + def _send_me_command(self, subcommand_params): + + start_time = time.monotonic() + local_buffer = self._command_buffer + _insert_command_request_report( + _ME_CALIBRATE, + self._command_buffer, # should use self._data_buffer :\ but send_packet don't + self.get_report_seq_id(_COMMAND_REQUEST), + subcommand_params, + ) + self._send_packet(_BNO_CHANNEL_CONTROL, local_buffer) + self._increment_report_seq(_COMMAND_REQUEST) + while _elapsed(start_time) < _DEFAULT_TIMEOUT: + self._process_available_packets() + if self._me_calibration_started_at > start_time: + break + print("ME Started?") + + def save_calibration_data(self): + # send a DCD save command + # _COMMAND_REQUEST = const(0xF2) + # _COMMAND_RESPONSE = const(0xF1) + start_time = time.monotonic() + local_buffer = bytearray(12) + _insert_command_request_report( + _SAVE_DCD, + local_buffer, # should use self._data_buffer :\ but send_packet don't + self.get_report_seq_id(_COMMAND_REQUEST), + ) + self._send_packet(_BNO_CHANNEL_CONTROL, local_buffer) + self._increment_report_seq(_COMMAND_REQUEST) + while _elapsed(start_time) < _DEFAULT_TIMEOUT: + self._process_available_packets() + if self._dcd_saved_at > start_time: + break + print("DCD SAVED?") + # Byte Description + # 0 Report ID = 0xF2 + # 1 Sequence number + # 2 Command + # P0-9: a set of command-specific parameters. The interpretation of these + # parameters is defined for each command. + # 3 P0 + # 4 P1 + # 5 P2 + # 6 P3 + # 7 P4 + # 8 P5 + # 9 P6 + # 10 P7 + # 11 P8 + + # poll on DCD calibration status + + # TODO: Make this a Packet creation + + self._increment_report_seq(_COMMAND_REQUEST) + + ############### private/helper methods ############### # # decorator? def _process_available_packets(self): processed_count = 0 @@ -724,12 +855,29 @@ def _handle_control_report(self, report_id, report_bytes): self._dbg("\tBuild: %d" % (sw_build_number)) self._dbg("") - if report_id == _BNO_CMD_GET_FEATURE_RESPONSE: + if report_id == _GET_FEATURE_RESPONSE: get_feature_report = _parse_get_feature_response_report(report_bytes) _report_id, feature_report_id, *_remainder = get_feature_report self._readings[feature_report_id] = _INITIAL_REPORTS.get( feature_report_id, (0.0, 0.0, 0.0) ) + if report_id == _COMMAND_RESPONSE: + self._handle_command_response(report_bytes) + + def _handle_command_response(self, report_bytes): + (report_body, response_values) = _parse_command_response(report_bytes) + print( + "report id: %x sequence number: %x command: %x command sequence number: %x response sequence number: %x" + % report_body + ) + report_id, sequence_number, command, command_sequence_number = report_body + if command == _ME_CALIBRATE: + self._me_calibration_started_at = time.monotonic() + if command == _SAVE_DCD: + if response_values[0] == 0: + self._dcd_saved_at = time.monotonic() + else: + raise RuntimeError("Unable to save calibration data") def _process_report(self, report_id, report_bytes): if report_id >= 0xF0: @@ -784,7 +932,7 @@ def _get_feature_enable_report( ): # TODO !!! ALLOCATION !!! set_feature_report = bytearray(17) - set_feature_report[0] = _BNO_CMD_SET_FEATURE_COMMAND + set_feature_report[0] = _SET_FEATURE_COMMAND set_feature_report[1] = feature_id pack_into(" Date: Mon, 14 Sep 2020 15:18:05 -0700 Subject: [PATCH 029/106] added calibration --- adafruit_bno08x/__init__.py | 105 ++++++++++++++++++--------------- examples/bno08x_calibration.py | 41 ++++++++----- 2 files changed, 84 insertions(+), 62 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 4171a34..047bae5 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -68,6 +68,7 @@ _SAVE_DCD = const(0x6) _ME_CALIBRATE = const(0x7) _ME_CAL_CONFIG = const(0x00) +_ME_GET_CAL = const(0x01) # Calibrated Acceleration (m/s2) BNO_REPORT_ACCELEROMETER = const(0x01) @@ -179,7 +180,12 @@ ["channel_number", "sequence_number", "data_length", "packet_byte_count",], ) -REPORT_STATUS = ["Unreliable", "Accuracy low", "Accuracy medium", "Accuracy high"] +REPORT_ACCURACY_STATUS = [ + "Accuracy Unreliable", + "Low Accuracy", + "Medium Accuracy", + "High Accuracy", +] class PacketError(Exception): @@ -218,14 +224,17 @@ def _parse_sensor_report_data(report_bytes): else: format_str = " start_time: break - print("ME Started?") def save_calibration_data(self): + """Save the self-calibration data""" # send a DCD save command - # _COMMAND_REQUEST = const(0xF2) - # _COMMAND_RESPONSE = const(0xF1) start_time = time.monotonic() local_buffer = bytearray(12) _insert_command_request_report( _SAVE_DCD, local_buffer, # should use self._data_buffer :\ but send_packet don't - self.get_report_seq_id(_COMMAND_REQUEST), + self._get_report_seq_id(_COMMAND_REQUEST), ) self._send_packet(_BNO_CHANNEL_CONTROL, local_buffer) self._increment_report_seq(_COMMAND_REQUEST) while _elapsed(start_time) < _DEFAULT_TIMEOUT: self._process_available_packets() if self._dcd_saved_at > start_time: - break - print("DCD SAVED?") - # Byte Description - # 0 Report ID = 0xF2 - # 1 Sequence number - # 2 Command - # P0-9: a set of command-specific parameters. The interpretation of these - # parameters is defined for each command. - # 3 P0 - # 4 P1 - # 5 P2 - # 6 P3 - # 7 P4 - # 8 P5 - # 9 P6 - # 10 P7 - # 11 P8 - - # poll on DCD calibration status - - # TODO: Make this a Packet creation - - self._increment_report_seq(_COMMAND_REQUEST) + return + raise RuntimeError("Could not save calibration data") ############### private/helper methods ############### # # decorator? - def _process_available_packets(self): + def _process_available_packets(self, max_packets=None): processed_count = 0 while self._data_ready: + if max_packets and processed_count > max_packets: + return # print("reading a packet") try: new_packet = self._read_packet() @@ -866,15 +874,18 @@ def _handle_control_report(self, report_id, report_bytes): def _handle_command_response(self, report_bytes): (report_body, response_values) = _parse_command_response(report_bytes) - print( - "report id: %x sequence number: %x command: %x command sequence number: %x response sequence number: %x" - % report_body - ) - report_id, sequence_number, command, command_sequence_number = report_body - if command == _ME_CALIBRATE: + + # report_id, seq_number, command, command_seq_number, response_seq_number) = report_body + _report_id, _sequence_number, command = report_body + + # status, accel_en, gyro_en, mag_en, planar_en, table_en, *_reserved) = response_values + command_status, *_rest = response_values + + if command == _ME_CALIBRATE and command_status == 0: self._me_calibration_started_at = time.monotonic() + if command == _SAVE_DCD: - if response_values[0] == 0: + if command_status == 0: self._dcd_saved_at = time.monotonic() else: raise RuntimeError("Unable to save calibration data") @@ -917,9 +928,9 @@ def _process_report(self, report_id, report_bytes): activity_classification = _parse_activity_classifier_report(report_bytes) self._readings[BNO_REPORT_ACTIVITY_CLASSIFIER] = activity_classification return - - sensor_data = _parse_sensor_report_data(report_bytes) - + sensor_data, accuracy = _parse_sensor_report_data(report_bytes) + if report_id == BNO_REPORT_MAGNETOMETER: + self._magnetometer_accuracy = accuracy # TODO: FIXME; Sensor reports are batched in a LIFO which means that multiple reports # for the same type will end with the oldest/last being kept and the other # newer reports thrown away @@ -965,7 +976,7 @@ def enable_feature(self, feature_id): start_time = time.monotonic() # 1 while _elapsed(start_time) < _FEATURE_ENABLE_TIMEOUT: - self._process_available_packets() + self._process_available_packets(max_packets=10) if feature_id in self._readings: return raise RuntimeError("Was not able to enable feature", feature_id) @@ -1070,4 +1081,4 @@ def _increment_report_seq(self, report_id): self._two_ended_sequence_numbers[report_id] = (current + 1) % 256 def _get_report_seq_id(self, report_id): - return self._two_ended_sequence_numbers[report_id] + return self._two_ended_sequence_numbers.get(report_id, 0) diff --git a/examples/bno08x_calibration.py b/examples/bno08x_calibration.py index 1227f6c..9a98f10 100644 --- a/examples/bno08x_calibration.py +++ b/examples/bno08x_calibration.py @@ -8,26 +8,23 @@ import adafruit_bno08x from adafruit_bno08x.i2c import BNO08X_I2C -i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) +i2c = busio.I2C(board.SCL, board.SDA) reset_pin = DigitalInOut(board.D5) bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) +bno.begin_calibration() # TODO: UPDATE UART/SPI -bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) -# bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR) -bno.begin_calibration() +start_time = time.monotonic() +calibration_good_at = None while True: time.sleep(0.1) - print("Gyro:") - gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member - print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) - print("") - # print("Magnetometer:") - # mag_x, mag_y, mag_z = bno.magnetic # pylint:disable=no-member - # print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) - # print("") + print("Magnetometer:") + mag_x, mag_y, mag_z = bno.magnetic # pylint:disable=no-member + print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) + print("") print("Game Rotation Vector Quaternion:") ( @@ -40,6 +37,20 @@ "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) ) - print("") - bno.save_calibration_data() - print("calibration done") + calibration_status = bno.calibration_status + print( + "Magnetometer Calibration quality:", + adafruit_bno08x.REPORT_ACCURACY_STATUS[calibration_status], + " (%d)" % calibration_status, + ) + if not calibration_good_at and calibration_status >= 2: + calibration_good_at = time.monotonic() + if calibration_good_at and (time.monotonic() - calibration_good_at > 5.0): + input_str = input("\n\nEnter S to save or anything else to continue: ") + if input_str.strip().lower() == "s": + bno.save_calibration_data() + break + calibration_good_at = None + print("**************************************************************") + +print("calibration done") From 61b709a200bbb228e84395347252a8f360c65ab8 Mon Sep 17 00:00:00 2001 From: siddacious Date: Wed, 23 Sep 2020 10:11:37 -0700 Subject: [PATCH 030/106] linting, cleaning up examples --- adafruit_bno08x/__init__.py | 49 +++++----- adafruit_bno08x/spi.py | 41 ++++---- examples/bno08x_more_reports.py | 137 +++++++++++++++++++++++++++ examples/bno08x_simpletest.py | 115 +++-------------------- examples/bno08x_simpletest_uart.py | 146 +++++++++++++++++++++-------- 5 files changed, 300 insertions(+), 188 deletions(-) create mode 100644 examples/bno08x_more_reports.py diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 047bae5..2535018 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -1,3 +1,4 @@ +# pylint:disable=too-many-lines # SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries # # SPDX-License-Identifier: MIT @@ -198,20 +199,6 @@ def _elapsed(start_time): return time.monotonic() - start_time -def elapsed_time(func): - """Print the runtime of the decorated function""" - - def wrapper_timer(*args, **kwargs): - start_time = time.monotonic() # 1 - value = func(*args, **kwargs) - end_time = time.monotonic() # 2 - run_time = end_time - start_time # 3 - print("Finished", func.__name__, "in", (run_time * 1000.0), "ms") - return value - - return wrapper_timer - - ############ PACKET PARSING ########################### def _parse_sensor_report_data(report_bytes): """Parses reports with only 16-bit fields""" @@ -520,9 +507,15 @@ def __init__(self, reset=None, debug=False): def initialize(self): """Initialize the sensor""" - self.hard_reset() - self.soft_reset() - if not self._check_id(): + for _ in range(3): + self.hard_reset() + self.soft_reset() + try: + if self._check_id(): + break + except: # pylint:disable=bare-except + time.sleep(0.5) + else: raise RuntimeError("Could not read ID") @property @@ -792,7 +785,6 @@ def _process_available_packets(self, max_packets=None): self._dbg("") # print("Processed", processed_count, "packets") self._dbg("") - # we'll probably need an exit here for fast sensor rates self._dbg("") self._dbg(" ** DONE! **") @@ -875,8 +867,13 @@ def _handle_control_report(self, report_id, report_bytes): def _handle_command_response(self, report_bytes): (report_body, response_values) = _parse_command_response(report_bytes) - # report_id, seq_number, command, command_seq_number, response_seq_number) = report_body - _report_id, _sequence_number, command = report_body + ( + _report_id, + _seq_number, + command, + _command_seq_number, + _response_seq_number, + ) = report_body # status, accel_en, gyro_en, mag_en, planar_en, table_en, *_reserved) = response_values command_status, *_rest = response_values @@ -902,7 +899,7 @@ def _process_report(self, report_id, report_bytes): if (packet_index % 4) == 0: outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) outstr += "0x{:02X} ".format(packet_byte) - print(outstr) + self._dbg(outstr) self._dbg("") if report_id == BNO_REPORT_STEP_COUNTER: @@ -941,7 +938,6 @@ def _process_report(self, report_id, report_bytes): def _get_feature_enable_report( feature_id, report_interval=_DEFAULT_REPORT_INTERVAL, sensor_specific_config=0 ): - # TODO !!! ALLOCATION !!! set_feature_report = bytearray(17) set_feature_report[0] = _SET_FEATURE_COMMAND set_feature_report[1] = feature_id @@ -970,7 +966,7 @@ def enable_feature(self, feature_id): self._dbg("Enabling feature depencency:", feature_dependency) self.enable_feature(feature_dependency) - print("Enabling", feature_id) + self._dbg("Enabling", feature_id) self._send_packet(_BNO_CHANNEL_CONTROL, set_feature_report) start_time = time.monotonic() # 1 @@ -1040,7 +1036,6 @@ def hard_reset(self): """Hardware reset the sensor to an initial unconfigured state""" if not self._reset: return - # print("Hard resetting...") import digitalio # pylint:disable=import-outside-toplevel self._reset.direction = digitalio.Direction.OUTPUT @@ -1049,11 +1044,11 @@ def hard_reset(self): self._reset.value = False time.sleep(0.01) self._reset.value = True - time.sleep(0.5) + time.sleep(0.01) def soft_reset(self): """Reset the sensor to an initial unconfigured state""" - print("Soft resetting...", end="") + self._dbg("Soft resetting...", end="") data = bytearray(1) data[0] = 1 _seq = self._send_packet(BNO_CHANNEL_EXE, data) @@ -1067,7 +1062,7 @@ def soft_reset(self): except PacketError: time.sleep(0.5) - print("OK!") + self._dbg("OK!") # all is good! def _send_packet(self, channel, data): diff --git a/adafruit_bno08x/spi.py b/adafruit_bno08x/spi.py index 81efee3..194d439 100644 --- a/adafruit_bno08x/spi.py +++ b/adafruit_bno08x/spi.py @@ -11,7 +11,7 @@ from digitalio import Direction, Pull import adafruit_bus_device.spi_device as spi_device -from . import BNO08X, BNO_CHANNEL_EXE, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError +from . import BNO08X, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError class BNO08X_SPI(BNO08X): @@ -31,24 +31,21 @@ class BNO08X_SPI(BNO08X): # """ def __init__( - self, spi_bus, cspin, intpin, wakepin, resetpin, baudrate=4000000, debug=False + self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False ): # pylint:disable=too-many-arguments self._spi = spi_device.SPIDevice( spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1 ) self._int = intpin - self._wake = wakepin super().__init__(resetpin, debug) def hard_reset(self): """Hardware reset the sensor to an initial unconfigured state""" self._reset.direction = Direction.OUTPUT - self._wake.direction = Direction.OUTPUT self._int.direction = Direction.INPUT self._int.pull = Pull.UP print("Hard resetting...") - self._wake.value = True # set PS0 high (PS1 also must be tied high) self._reset.value = True # perform hardware reset time.sleep(0.01) self._reset.value = False @@ -65,31 +62,32 @@ def _wait_for_int(self): if not self._int.value: break else: - raise RuntimeError("Could not wake up") + self.hard_reset() + # raise RuntimeError("Could not wake up") # print("OK") def soft_reset(self): """Reset the sensor to an initial unconfigured state""" - print("Soft resetting...", end="") - data = bytearray(1) - data[0] = 1 - _seq = self._send_packet(BNO_CHANNEL_EXE, data) - time.sleep(0.5) + # print("Soft resetting...", end="") + # data = bytearray(1) + # data[0] = 1 + # _seq = self._send_packet(BNO_CHANNEL_EXE, data) + # time.sleep(0.5) for _i in range(3): try: _packet = self._read_packet() except PacketError: - time.sleep(0.5) - print("OK!") + time.sleep(0.1) + # print("OK!") # all is good! def _read_into(self, buf, start=0, end=None): self._wait_for_int() with self._spi as spi: - spi.readinto(buf, start=start, end=end) - # print("SPI Read buffer: ", [hex(i) for i in buf[start:end]]) + spi.readinto(buf, start=start, end=end, write_value=0x00) + # print("SPI Read buffer (", end-start, "b )", [hex(i) for i in buf[start:end]]) def _read_header(self): """Reads the first 4 bytes available as a header""" @@ -97,14 +95,17 @@ def _read_header(self): # read header with self._spi as spi: - spi.readinto(self._data_buffer, end=4) + spi.readinto(self._data_buffer, end=4, write_value=0x00) self._dbg("") - # print("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) + self._dbg("SHTP READ packet header: ", [hex(x) for x in self._data_buffer[0:4]]) def _read_packet(self): self._read_header() + halfpacket = False - # print([hex(x) for x in self._data_buffer[0:4]]) + print([hex(x) for x in self._data_buffer[0:4]]) + if self._data_buffer[1] & 0x80: + halfpacket = True header = Packet.header_from_buffer(self._data_buffer) packet_byte_count = header.packet_byte_count channel_number = header.channel_number @@ -126,6 +127,8 @@ def _read_packet(self): self._read_into(self._data_buffer, start=0, end=packet_byte_count) # print("Packet: ", [hex(i) for i in self._data_buffer[0:packet_byte_count]]) + if halfpacket: + raise PacketError("read partial packet") new_packet = Packet(self._data_buffer) if self._debug: print(new_packet) @@ -158,7 +161,7 @@ def _send_packet(self, channel, data): self._wait_for_int() with self._spi as spi: spi.write(self._data_buffer, end=write_length) - # print("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]]) + self._dbg("Sending: ", [hex(x) for x in self._data_buffer[0:write_length]]) self._sequence_number[channel] = (self._sequence_number[channel] + 1) % 256 return self._sequence_number[channel] diff --git a/examples/bno08x_more_reports.py b/examples/bno08x_more_reports.py new file mode 100644 index 0000000..67486db --- /dev/null +++ b/examples/bno08x_more_reports.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: 2020 Bryan Siepert, written for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense +import time +import board +import busio +from digitalio import DigitalInOut +import adafruit_bno08x +from adafruit_bno08x.i2c import BNO08X_I2C + +i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) +reset_pin = DigitalInOut(board.D5) +bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) + +# TODO: UPDATE UART/SPI +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_STABILITY_CLASSIFIER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACTIVITY_CLASSIFIER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_ACCELEROMETER) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_GYROSCOPE) +bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_MAGNETOMETER) + +while True: + time.sleep(0.1) + + print("Acceleration:") + accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member + print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) + print("") + + print("Gyro:") + gyro_x, gyro_y, gyro_z = bno.gyro # pylint:disable=no-member + print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) + print("") + + print("Magnetometer:") + mag_x, mag_y, mag_z = bno.magnetic # pylint:disable=no-member + print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) + print("") + + print("Linear Acceleration:") + ( + linear_accel_x, + linear_accel_y, + linear_accel_z, + ) = bno.linear_acceleration # pylint:disable=no-member + print( + "X: %0.6f Y: %0.6f Z: %0.6f m/s^2" + % (linear_accel_x, linear_accel_y, linear_accel_z) + ) + print("") + + print("Rotation Vector Quaternion:") + quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member + print( + "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) + ) + print("") + + print("Geomagnetic Rotation Vector Quaternion:") + ( + geo_quat_i, + geo_quat_j, + geo_quat_k, + geo_quat_real, + ) = bno.geomagnetic_quaternion # pylint:disable=no-member + print( + "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + % (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real) + ) + # print("") + + print("Game Rotation Vector Quaternion:") + ( + game_quat_i, + game_quat_j, + game_quat_k, + game_quat_real, + ) = bno.game_quaternion # pylint:disable=no-member + print( + "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) + ) + print("") + + print("Steps detected:", bno.steps) + print("") + + print("Stability classification:", bno.stability_classification) + print("") + + activity_classification = bno.activity_classification + most_likely = activity_classification["most_likely"] + print( + "Activity classification:", + most_likely, + "confidence: %d/100" % activity_classification[most_likely], + ) + + print("Raw Acceleration:") + (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_acceleration + print( + "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + raw_accel_x, raw_accel_y, raw_accel_z + ) + ) + print("") + + print("Raw Gyro:") + (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_gyro + print( + "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + raw_accel_x, raw_accel_y, raw_accel_z + ) + ) + print("") + + print("Raw Magnetometer:") + (raw_mag_x, raw_mag_y, raw_mag_z,) = bno.raw_magnetic + print( + "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + raw_mag_x, raw_mag_y, raw_mag_z + ) + ) + print("") + time.sleep(0.4) + if bno.shake: + print("SHAKE DETECTED!") + print("") diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 67486db..2bdad0f 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -4,33 +4,25 @@ import time import board import busio -from digitalio import DigitalInOut -import adafruit_bno08x +from adafruit_bno08x import ( + BNO_REPORT_ACCELEROMETER, + BNO_REPORT_GYROSCOPE, + BNO_REPORT_MAGNETOMETER, + BNO_REPORT_ROTATION_VECTOR, +) from adafruit_bno08x.i2c import BNO08X_I2C i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) -reset_pin = DigitalInOut(board.D5) -bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) +bno = BNO08X_I2C(i2c) -# TODO: UPDATE UART/SPI -bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_STABILITY_CLASSIFIER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACTIVITY_CLASSIFIER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_ACCELEROMETER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_GYROSCOPE) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_MAGNETOMETER) +bno.enable_feature(BNO_REPORT_ACCELEROMETER) +bno.enable_feature(BNO_REPORT_GYROSCOPE) +bno.enable_feature(BNO_REPORT_MAGNETOMETER) +bno.enable_feature(BNO_REPORT_ROTATION_VECTOR) while True: - time.sleep(0.1) + time.sleep(0.5) print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) @@ -46,92 +38,9 @@ print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) print("") - print("Linear Acceleration:") - ( - linear_accel_x, - linear_accel_y, - linear_accel_z, - ) = bno.linear_acceleration # pylint:disable=no-member - print( - "X: %0.6f Y: %0.6f Z: %0.6f m/s^2" - % (linear_accel_x, linear_accel_y, linear_accel_z) - ) - print("") - print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member print( "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) ) print("") - - print("Geomagnetic Rotation Vector Quaternion:") - ( - geo_quat_i, - geo_quat_j, - geo_quat_k, - geo_quat_real, - ) = bno.geomagnetic_quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" - % (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real) - ) - # print("") - - print("Game Rotation Vector Quaternion:") - ( - game_quat_i, - game_quat_j, - game_quat_k, - game_quat_real, - ) = bno.game_quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" - % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) - ) - print("") - - print("Steps detected:", bno.steps) - print("") - - print("Stability classification:", bno.stability_classification) - print("") - - activity_classification = bno.activity_classification - most_likely = activity_classification["most_likely"] - print( - "Activity classification:", - most_likely, - "confidence: %d/100" % activity_classification[most_likely], - ) - - print("Raw Acceleration:") - (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_acceleration - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_accel_x, raw_accel_y, raw_accel_z - ) - ) - print("") - - print("Raw Gyro:") - (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_gyro - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_accel_x, raw_accel_y, raw_accel_z - ) - ) - print("") - - print("Raw Magnetometer:") - (raw_mag_x, raw_mag_y, raw_mag_z,) = bno.raw_magnetic - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_mag_x, raw_mag_y, raw_mag_z - ) - ) - print("") - time.sleep(0.4) - if bno.shake: - print("SHAKE DETECTED!") - print("") diff --git a/examples/bno08x_simpletest_uart.py b/examples/bno08x_simpletest_uart.py index 0d818d9..ab67b1a 100644 --- a/examples/bno08x_simpletest_uart.py +++ b/examples/bno08x_simpletest_uart.py @@ -2,28 +2,44 @@ # # SPDX-License-Identifier: Unlicense import time -import board -import busio import adafruit_bno08x from adafruit_bno08x.uart import BNO08X_UART -# import serial -# uart = serial.Serial("COM49", baudrate=3000000, timeout=1) -# print(uart.name) +import board # pylint:disable=wrong-import-order +import busio # pylint:disable=wrong-import-order + uart = busio.UART(board.TX, board.RX, baudrate=3000000, receiver_buffer_size=2048) -bno = BNO08X_UART(uart, reset=None, debug=False) + +# uncomment and comment out the above for use with Raspberry Pi +# import serial +# uart = serial.Serial("/dev/serial0", 115200) + +# for a USB Serial cable: +# import serial +# uart = serial.Serial("/dev/ttyUSB0", baudrate=115200) + +bno = BNO08X_UART(uart) bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) bno.enable_feature(adafruit_bno08x.BNO_REPORT_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) -bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) + +# More reports! Uncomment the enable line below along with the print +# in the loop below +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_LINEAR_ACCELERATION) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_GAME_ROTATION_VECTOR) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_STEP_COUNTER) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_STABILITY_CLASSIFIER) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACTIVITY_CLASSIFIER) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_SHAKE_DETECTOR) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_ACCELEROMETER) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_GYROSCOPE) +# bno.enable_feature(adafruit_bno08x.BNO_REPORT_RAW_MAGNETOMETER) while True: - time.sleep(0.1) + time.sleep(0.5) print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member @@ -40,18 +56,6 @@ print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) print("") - print("Linear Acceleration:") - ( - linear_accel_x, - linear_accel_y, - linear_accel_z, - ) = bno.linear_acceleration # pylint:disable=no-member - print( - "X: %0.6f Y: %0.6f Z: %0.6f m/s^2" - % (linear_accel_x, linear_accel_y, linear_accel_z) - ) - print("") - print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member print( @@ -59,21 +63,85 @@ ) print("") - print("Geomagnetic Rotation Vector Quaternion:") - ( - geo_quat_i, - geo_quat_j, - geo_quat_k, - geo_quat_real, - ) = bno.geomagnetic_quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) - ) - print("") + # print("Linear Acceleration:") + # ( + # linear_accel_x, + # linear_accel_y, + # linear_accel_z, + # ) = bno.linear_acceleration # pylint:disable=no-member + # print( + # "X: %0.6f Y: %0.6f Z: %0.6f m/s^2" + # % (linear_accel_x, linear_accel_y, linear_accel_z) + # ) + # print("") - print("Steps detected:", bno.steps) - print("") + # print("Geomagnetic Rotation Vector Quaternion:") + # ( + # geo_quat_i, + # geo_quat_j, + # geo_quat_k, + # geo_quat_real, + # ) = bno.geomagnetic_quaternion # pylint:disable=no-member + # print( + # "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + # % (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real) + # ) + # # print("") + + # print("Game Rotation Vector Quaternion:") + # ( + # game_quat_i, + # game_quat_j, + # game_quat_k, + # game_quat_real, + # ) = bno.game_quaternion # pylint:disable=no-member + # print( + # "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" + # % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) + # ) + # print("") + + # print("Steps detected:", bno.steps) + # print("") + + # print("Stability classification:", bno.stability_classification) + # print("") + + # activity_classification = bno.activity_classification + # most_likely = activity_classification["most_likely"] + # print( + # "Activity classification:", + # most_likely, + # "confidence: %d/100" % activity_classification[most_likely], + # ) + + # print("Raw Acceleration:") + # (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_acceleration + # print( + # "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + # raw_accel_x, raw_accel_y, raw_accel_z + # ) + # ) + # print("") + + # print("Raw Gyro:") + # (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_gyro + # print( + # "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + # raw_accel_x, raw_accel_y, raw_accel_z + # ) + # ) + # print("") - if bno.shake: - print("SHAKE DETECTED!") - print("") + # print("Raw Magnetometer:") + # (raw_mag_x, raw_mag_y, raw_mag_z,) = bno.raw_magnetic + # print( + # "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( + # raw_mag_x, raw_mag_y, raw_mag_z + # ) + # ) + # print("") + # time.sleep(0.4) + # if bno.shake: + # print("SHAKE DETECTED!") + # print("") From cac28f28159fa0a5bcee29227179ad5a45156ddf Mon Sep 17 00:00:00 2001 From: siddacious Date: Wed, 23 Sep 2020 10:13:23 -0700 Subject: [PATCH 031/106] adding example with more reports --- examples/bno08x_more_reports.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/examples/bno08x_more_reports.py b/examples/bno08x_more_reports.py index 67486db..74718fc 100644 --- a/examples/bno08x_more_reports.py +++ b/examples/bno08x_more_reports.py @@ -1,18 +1,15 @@ # SPDX-FileCopyrightText: 2020 Bryan Siepert, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT import time import board import busio -from digitalio import DigitalInOut import adafruit_bno08x from adafruit_bno08x.i2c import BNO08X_I2C i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) -reset_pin = DigitalInOut(board.D5) -bno = BNO08X_I2C(i2c, reset=reset_pin, debug=False) +bno = BNO08X_I2C(i2c) -# TODO: UPDATE UART/SPI bno.enable_feature(adafruit_bno08x.BNO_REPORT_ACCELEROMETER) bno.enable_feature(adafruit_bno08x.BNO_REPORT_GYROSCOPE) bno.enable_feature(adafruit_bno08x.BNO_REPORT_MAGNETOMETER) From 4e14ef447e060ee90d8e03c9d5dec0f6c04d09f2 Mon Sep 17 00:00:00 2001 From: siddacious Date: Mon, 19 Oct 2020 14:24:43 -0700 Subject: [PATCH 032/106] fixing PyPi issue in #5 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 2b96a55..8a9fabc 100644 --- a/setup.py +++ b/setup.py @@ -55,5 +55,5 @@ # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=["adafruit_bno08x"], + packages=["adafruit_bno08x"], ) From d12a39567ec04dccea5f01b898bbb5d5147c9a62 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 25 Nov 2020 10:14:36 -0500 Subject: [PATCH 033/106] Making small change to have actions re-run --- adafruit_bno08x/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 2535018..8000f46 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -643,7 +643,7 @@ def stability_classification(self): @property def activity_classification(self): """Returns the sensor's assessment of the activity that is creating the motions\ - it's sensing, one of: + that it is sensing, one of: * "Unknown" * "In-Vehicle" From ad40b5e41d2da1e1f4a63f7ae2ed934eb86df701 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albin=20Cor=C3=A9n?= <2108U9@gmail.com> Date: Tue, 15 Dec 2020 14:46:43 +0000 Subject: [PATCH 034/106] Fix game_rotation_vector initial value Ensures that game_rotation_vector will have a initial value of length 4 to be parsable as a quaternion. --- adafruit_bno08x/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 8000f46..6200b01 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -169,6 +169,7 @@ }, BNO_REPORT_STABILITY_CLASSIFIER: "Unknown", BNO_REPORT_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), + BNO_REPORT_GAME_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), } _ENABLED_ACTIVITIES = ( From dd4847f17b1b9709b16d701f95fa4da7021f0f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albin=20Cor=C3=A9n?= Date: Mon, 21 Dec 2020 20:46:18 +0100 Subject: [PATCH 035/106] Fix geomagnetic_rotation_vector initial value --- adafruit_bno08x/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 6200b01..cf37053 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -170,6 +170,7 @@ BNO_REPORT_STABILITY_CLASSIFIER: "Unknown", BNO_REPORT_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), BNO_REPORT_GAME_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), + BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), } _ENABLED_ACTIVITIES = ( From 8337cdc542b3ceddd78babddc438adcb398bd549 Mon Sep 17 00:00:00 2001 From: Yugesh kc Date: Tue, 5 Jan 2021 13:12:47 +0900 Subject: [PATCH 036/106] bno080x_heading_example Using rotation vectors to find the heading value --- examples/bno08x_find_heading.py | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 examples/bno08x_find_heading.py diff --git a/examples/bno08x_find_heading.py b/examples/bno08x_find_heading.py new file mode 100644 index 0000000..bcbf829 --- /dev/null +++ b/examples/bno08x_find_heading.py @@ -0,0 +1,54 @@ +import time +from math import atan2, sqrt, pi +from board import SCL, SDA +from busio import I2C +from adafruit_bno08x import ( + BNO_REPORT_STEP_COUNTER, + BNO_REPORT_ROTATION_VECTOR, + BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR +) +from adafruit_bno08x.i2c import BNO08X_I2C + +i2c = I2C(SCL, SDA, frequency=800000) +bno = BNO08X_I2C(i2c) +bno.enable_feature(BNO_REPORT_STEP_COUNTER) +bno.enable_feature(BNO_REPORT_ROTATION_VECTOR) +bno.enable_feature(BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) + +# quat_real, quat_i, quat_j, quat_k + + +def find_heading(dqw, dqx, dqy, dqz): + norm = sqrt(dqw*dqw + dqx*dqx + dqy*dqy + dqz*dqz) + dqw = dqw/norm + dqx = dqx/norm + dqy = dqy/norm + dqz = dqz/norm + + ysqr = dqy * dqy + + t3 = +2.0 * (dqw * dqz + dqx * dqy) + t4 = +1.0 - 2.0 * (ysqr + dqz * dqz) + yaw_raw = atan2(t3, t4) + yaw = yaw_raw * 180.0 / pi + if yaw > 0: + yaw = 360 - yaw + else: + yaw = abs(yaw) + return yaw # heading in 360 clockwise + + +while True: + quat_i, quat_j, quat_k, quat_real = bno.quaternion + heading = find_heading(quat_real, quat_i, quat_j, quat_k) + print("Heading using rotation vector:", heading) + + # the geomagnetic sensor is unstable + # Heading is calculated using geomagnetic vector + geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real = bno.geomagnetic_quaternion + heading_geo = find_heading( + geo_quat_real, geo_quat_i, geo_quat_j, geo_quat_k) + print("Heading using geomagnetic rotation vector:", heading_geo) + print("") + time.sleep(0.1) + From c5a4b6e2c86c7a6fb2eef83d7034fe9da9d8231a Mon Sep 17 00:00:00 2001 From: ocouch <43231870+ocouch@users.noreply.github.com> Date: Sat, 23 Jan 2021 19:59:45 +1100 Subject: [PATCH 037/106] Update bno08x_simpletest.py The BNO085 only supports Fast mode I2C (400kHz). However, this frequency setting actually worked on a RasPi 0 (clock stretching issues aside) so it must be disregarded at some point - may not fair so well on other devices. --- examples/bno08x_simpletest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 2bdad0f..ddea6e0 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -12,7 +12,7 @@ ) from adafruit_bno08x.i2c import BNO08X_I2C -i2c = busio.I2C(board.SCL, board.SDA, frequency=800000) +i2c = busio.I2C(board.SCL, board.SDA, frequency=400000) bno = BNO08X_I2C(i2c) bno.enable_feature(BNO_REPORT_ACCELEROMETER) From 3e5c162fb12fec2047917d0de6f5efde0d9149e6 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 24 Feb 2021 15:02:28 -0500 Subject: [PATCH 038/106] Removed pylint process from github workflow Signed-off-by: dherrada --- .github/workflows/build.yml | 4 ---- .pre-commit-config.yaml | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 17b6e2f..0434bc5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,10 +50,6 @@ jobs: - name: Pre-commit hooks run: | pre-commit run --all-files - - name: PyLint - run: | - pylint $( find . -path './adafruit*.py' ) - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" )) - name: Build assets run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - name: Build docs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6cd77e3..d017d7b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,3 +17,18 @@ repos: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace +- repo: https://github.com/pycqa/pylint + rev: pylint-2.7.1 + hooks: + - id: pylint + name: pylint (library code) + types: [python] + exclude: "^(docs/|examples/|setup.py$)" +- repo: local + hooks: + - id: pylint_examples + name: pylint (examples code) + description: Run pylint rules on "examples/*.py" files + entry: /usr/bin/env bash -c + args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name $example; done)'] + language: system From c6bfebd5626c1cd00cc8f46cab0f49b47714f3ce Mon Sep 17 00:00:00 2001 From: Dylan Herrada <33632497+dherrada@users.noreply.github.com> Date: Mon, 1 Mar 2021 18:11:25 -0500 Subject: [PATCH 039/106] Changed black and reuse to correct versions --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d017d7b..354c761 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,11 +4,11 @@ repos: - repo: https://github.com/python/black - rev: 19.10b0 + rev: 20.8b1 hooks: - id: black - repo: https://github.com/fsfe/reuse-tool - rev: latest + rev: v0.12.1 hooks: - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks From 54dfa83a6c94fbb0a1d5982fe3d8180b576e0eb2 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Thu, 4 Mar 2021 07:34:55 -0600 Subject: [PATCH 040/106] pylintrc ignore imports. run black format --- .pylintrc | 2 +- adafruit_bno08x/__init__.py | 9 +++++++-- adafruit_bno08x/i2c.py | 2 +- adafruit_bno08x/uart.py | 2 +- examples/bno08x_more_reports.py | 18 +++++++++++++++--- setup.py | 5 ++++- 6 files changed, 29 insertions(+), 9 deletions(-) diff --git a/.pylintrc b/.pylintrc index 54a9d35..3c07cc6 100644 --- a/.pylintrc +++ b/.pylintrc @@ -250,7 +250,7 @@ ignore-comments=yes ignore-docstrings=yes # Ignore imports when computing similarities. -ignore-imports=no +ignore-imports=yes # Minimum lines number of a similarity. min-similarity-lines=4 diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index cf37053..dff7225 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -180,7 +180,12 @@ DATA_BUFFER_SIZE = const(512) # data buffer size. obviously eats ram PacketHeader = namedtuple( "PacketHeader", - ["channel_number", "sequence_number", "data_length", "packet_byte_count",], + [ + "channel_number", + "sequence_number", + "data_length", + "packet_byte_count", + ], ) REPORT_ACCURACY_STATUS = [ @@ -478,7 +483,7 @@ def is_error(cls, header): class BNO08X: # pylint: disable=too-many-instance-attributes, too-many-public-methods """Library for the BNO08x IMUs from Hillcrest Laboratories - :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. + :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. """ diff --git a/adafruit_bno08x/i2c.py b/adafruit_bno08x/i2c.py index 6b9c59e..059f0bd 100644 --- a/adafruit_bno08x/i2c.py +++ b/adafruit_bno08x/i2c.py @@ -16,7 +16,7 @@ class BNO08X_I2C(BNO08X): """Library for the BNO08x IMUs from Hillcrest Laboratories - :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. + :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. """ diff --git a/adafruit_bno08x/uart.py b/adafruit_bno08x/uart.py index 12a02d2..f968268 100644 --- a/adafruit_bno08x/uart.py +++ b/adafruit_bno08x/uart.py @@ -21,7 +21,7 @@ class BNO08X_UART(BNO08X): """Library for the BNO08x IMUs from Hillcrest Laboratories - :param uart: The UART devce the BNO08x is connected to. + :param uart: The UART devce the BNO08x is connected to. """ diff --git a/examples/bno08x_more_reports.py b/examples/bno08x_more_reports.py index 74718fc..15a6743 100644 --- a/examples/bno08x_more_reports.py +++ b/examples/bno08x_more_reports.py @@ -103,7 +103,11 @@ ) print("Raw Acceleration:") - (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_acceleration + ( + raw_accel_x, + raw_accel_y, + raw_accel_z, + ) = bno.raw_acceleration print( "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( raw_accel_x, raw_accel_y, raw_accel_z @@ -112,7 +116,11 @@ print("") print("Raw Gyro:") - (raw_accel_x, raw_accel_y, raw_accel_z,) = bno.raw_gyro + ( + raw_accel_x, + raw_accel_y, + raw_accel_z, + ) = bno.raw_gyro print( "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( raw_accel_x, raw_accel_y, raw_accel_z @@ -121,7 +129,11 @@ print("") print("Raw Magnetometer:") - (raw_mag_x, raw_mag_y, raw_mag_z,) = bno.raw_magnetic + ( + raw_mag_x, + raw_mag_y, + raw_mag_z, + ) = bno.raw_magnetic print( "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( raw_mag_x, raw_mag_y, raw_mag_z diff --git a/setup.py b/setup.py index 8a9fabc..fc3da88 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,10 @@ # Author details author="Adafruit Industries", author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice",], + install_requires=[ + "Adafruit-Blinka", + "adafruit-circuitpython-busdevice", + ], # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers From 67f9f50d7361a318c21f3e04d420135f2dde7bd8 Mon Sep 17 00:00:00 2001 From: yugyesh Date: Wed, 17 Mar 2021 11:48:40 +0900 Subject: [PATCH 041/106] Add licence --- examples/bno08x_find_heading.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/bno08x_find_heading.py b/examples/bno08x_find_heading.py index bcbf829..5cd2df1 100644 --- a/examples/bno08x_find_heading.py +++ b/examples/bno08x_find_heading.py @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: 2021 KC YUGESH +# SPDX-License-Identifier: Unlicense + import time from math import atan2, sqrt, pi from board import SCL, SDA @@ -51,4 +54,3 @@ def find_heading(dqw, dqx, dqy, dqz): print("Heading using geomagnetic rotation vector:", heading_geo) print("") time.sleep(0.1) - From cb460d5993dca53107924e9b72350628a57a5bb2 Mon Sep 17 00:00:00 2001 From: yugyesh Date: Wed, 17 Mar 2021 11:49:33 +0900 Subject: [PATCH 042/106] refactor: Format code using black --- examples/bno08x_find_heading.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/bno08x_find_heading.py b/examples/bno08x_find_heading.py index 5cd2df1..b156ace 100644 --- a/examples/bno08x_find_heading.py +++ b/examples/bno08x_find_heading.py @@ -8,7 +8,7 @@ from adafruit_bno08x import ( BNO_REPORT_STEP_COUNTER, BNO_REPORT_ROTATION_VECTOR, - BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR + BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR, ) from adafruit_bno08x.i2c import BNO08X_I2C @@ -22,11 +22,11 @@ def find_heading(dqw, dqx, dqy, dqz): - norm = sqrt(dqw*dqw + dqx*dqx + dqy*dqy + dqz*dqz) - dqw = dqw/norm - dqx = dqx/norm - dqy = dqy/norm - dqz = dqz/norm + norm = sqrt(dqw * dqw + dqx * dqx + dqy * dqy + dqz * dqz) + dqw = dqw / norm + dqx = dqx / norm + dqy = dqy / norm + dqz = dqz / norm ysqr = dqy * dqy @@ -49,8 +49,7 @@ def find_heading(dqw, dqx, dqy, dqz): # the geomagnetic sensor is unstable # Heading is calculated using geomagnetic vector geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real = bno.geomagnetic_quaternion - heading_geo = find_heading( - geo_quat_real, geo_quat_i, geo_quat_j, geo_quat_k) + heading_geo = find_heading(geo_quat_real, geo_quat_i, geo_quat_j, geo_quat_k) print("Heading using geomagnetic rotation vector:", heading_geo) print("") time.sleep(0.1) From 980d4f141f960bfab8a650c842eb763f429a5c73 Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 19 Mar 2021 12:55:03 -0400 Subject: [PATCH 043/106] Increase duplicate code check threshold --- .pylintrc | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.pylintrc b/.pylintrc index 3c07cc6..9e69bd0 100644 --- a/.pylintrc +++ b/.pylintrc @@ -22,8 +22,7 @@ ignore-patterns= #init-hook= # Use multiple processes to speed up Pylint. -# jobs=1 -jobs=2 +jobs=1 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. @@ -253,7 +252,7 @@ ignore-docstrings=yes ignore-imports=yes # Minimum lines number of a similarity. -min-similarity-lines=4 +min-similarity-lines=12 [BASIC] From 4f4008fcff177330fbf226807ed3835620922722 Mon Sep 17 00:00:00 2001 From: caternuson Date: Mon, 12 Apr 2021 16:10:22 -0700 Subject: [PATCH 044/106] update README --- README.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 8dfad15..d056559 100644 --- a/README.rst +++ b/README.rst @@ -63,15 +63,16 @@ Usage Example import board import busio - import adafruit_bno08x + from adafruit_bno08x.i2c import BNO08X_I2C + from adafruit_bno08x import BNO_REPORT_ACCELEROMETER i2c = busio.I2C(board.SCL, board.SDA) - bno = adafruit_bno08x.BNO08X(i2c) + bno = BNO08X_I2C(i2c) + bno.enable_feature(BNO_REPORT_ACCELEROMETER) while True: - quat = bno.rotation_vector - print("Rotation Vector Quaternion:") - print("I: %0.3f J: %0.3f K: %0.3f Accuracy: %0.3f"%(quat.i, quat.j, quat.k, quat.accuracy)) + accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member + print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) Contributing ============ From e31da67876ae918116c489ea01b030bd68173a3b Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 19 May 2021 13:32:42 -0400 Subject: [PATCH 045/106] Added pull request template Signed-off-by: dherrada --- .../adafruit_circuitpython_pr.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md new file mode 100644 index 0000000..71ef8f8 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +Thank you for contributing! Before you submit a pull request, please read the following. + +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://circuitpython.readthedocs.io/en/latest/docs/design_guide.html + +If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. From 65fca06f7b8cd854d8614674d61a18a1b0e2a2f8 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 19 May 2021 13:35:18 -0400 Subject: [PATCH 046/106] Added help text and problem matcher Signed-off-by: dherrada --- .github/workflows/build.yml | 2 ++ .github/workflows/failure-help-text.yml | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 .github/workflows/failure-help-text.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0434bc5..bd2441d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -66,3 +66,5 @@ jobs: python setup.py sdist python setup.py bdist_wheel --universal twine check dist/* + - name: Setup problem matchers + uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 diff --git a/.github/workflows/failure-help-text.yml b/.github/workflows/failure-help-text.yml new file mode 100644 index 0000000..0b1194f --- /dev/null +++ b/.github/workflows/failure-help-text.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Failure help text + +on: + workflow_run: + workflows: ["Build CI"] + types: + - completed + +jobs: + post-help: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} + steps: + - name: Post comment to help + uses: adafruit/circuitpython-action-library-ci-failed@v1 From 0303c9a2d54c6246abc11981c97edf47a17bb6cf Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 24 May 2021 09:54:31 -0400 Subject: [PATCH 047/106] Moved CI to Python 3.7 Signed-off-by: dherrada --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bd2441d..5ad8791 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,10 +22,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.6 + - name: Set up Python 3.7 uses: actions/setup-python@v1 with: - python-version: 3.6 + python-version: 3.7 - name: Versions run: | python3 --version From 392a5764672e3280788d943fd5345cdc7e6e7126 Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 2 Jun 2021 14:16:27 -0400 Subject: [PATCH 048/106] Moved default branch to main --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index d056559..9e411a3 100644 --- a/README.rst +++ b/README.rst @@ -78,7 +78,7 @@ Contributing ============ Contributions are welcome! Please read our `Code of Conduct -`_ +`_ before contributing to help this project stay welcoming. Documentation From 8595799c1bd04cd81c88445aefe798bf6a498df3 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 23 Sep 2021 17:52:55 -0400 Subject: [PATCH 049/106] Globally disabled consider-using-f-string pylint check Signed-off-by: dherrada --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 354c761..8810708 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,5 +30,5 @@ repos: name: pylint (examples code) description: Run pylint rules on "examples/*.py" files entry: /usr/bin/env bash -c - args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name $example; done)'] + args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name,consider-using-f-string $example; done)'] language: system From b3c13a3c7318ce40254ba86e03e0c678f57e8531 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 25 Oct 2021 11:14:08 -0500 Subject: [PATCH 050/106] add docs link to readme --- README.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.rst b/README.rst index 9e411a3..f9b6a59 100644 --- a/README.rst +++ b/README.rst @@ -74,6 +74,11 @@ Usage Example accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) +Documentation +============= + +API documentation for this library can be found on `Read the Docs `_. + Contributing ============ From 8f9e5db86ae9ef65fc893048e7c21adc45163faa Mon Sep 17 00:00:00 2001 From: dherrada Date: Wed, 3 Nov 2021 14:40:16 -0400 Subject: [PATCH 051/106] PATCH Pylint and readthedocs patch test Signed-off-by: dherrada --- .github/workflows/build.yml | 4 ++-- .pre-commit-config.yaml | 26 +++++++++++++++++--------- .pylintrc | 2 +- .readthedocs.yml | 2 +- docs/requirements.txt | 5 +++++ 5 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 docs/requirements.txt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5ad8791..f619953 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,9 +42,9 @@ jobs: # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) run: | source actions-ci/install.sh - - name: Pip install pylint, Sphinx, pre-commit + - name: Pip install Sphinx, pre-commit run: | - pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit + pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - name: Library version run: git describe --dirty --always --tags - name: Pre-commit hooks diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8810708..1b9fadc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,17 +18,25 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: pylint-2.7.1 + rev: v2.11.1 hooks: - id: pylint name: pylint (library code) types: [python] - exclude: "^(docs/|examples/|setup.py$)" -- repo: local - hooks: - - id: pylint_examples - name: pylint (examples code) + args: + - --disable=consider-using-f-string + exclude: "^(docs/|examples/|tests/|setup.py$)" + - id: pylint + name: pylint (example code) description: Run pylint rules on "examples/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name,consider-using-f-string $example; done)'] - language: system + types: [python] + files: "^examples/" + args: + - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code + - id: pylint + name: pylint (test code) + description: Run pylint rules on "tests/*.py" files + types: [python] + files: "^tests/" + args: + - --disable=missing-docstring,consider-using-f-string,duplicate-code diff --git a/.pylintrc b/.pylintrc index 9e69bd0..37fda44 100644 --- a/.pylintrc +++ b/.pylintrc @@ -252,7 +252,7 @@ ignore-docstrings=yes ignore-imports=yes # Minimum lines number of a similarity. -min-similarity-lines=12 +min-similarity-lines=4 [BASIC] diff --git a/.readthedocs.yml b/.readthedocs.yml index a1e2575..338427a 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -4,4 +4,4 @@ python: version: 3 -requirements_file: requirements.txt +requirements_file: docs/requirements.txt diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..88e6733 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx>=4.0.0 From 643b7a03cefe4e302d40f5362318d51427cd89b6 Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 5 Nov 2021 14:49:30 -0400 Subject: [PATCH 052/106] Disabled unspecified-encoding pylint check Signed-off-by: dherrada --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 37fda44..bd3976d 100644 --- a/.pylintrc +++ b/.pylintrc @@ -55,7 +55,7 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" # disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation +disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,unspecified-encoding # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option From 06e9cb20156b1b66c5cbb8ffb473d7a8b4c51cb7 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 8 Nov 2021 12:30:53 -0500 Subject: [PATCH 053/106] Linted --- .pre-commit-config.yaml | 2 +- adafruit_bno08x/i2c.py | 2 +- adafruit_bno08x/spi.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1b9fadc..43d1385 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: name: pylint (library code) types: [python] args: - - --disable=consider-using-f-string + - --disable=consider-using-f-string,duplicate-code exclude: "^(docs/|examples/|tests/|setup.py$)" - id: pylint name: pylint (example code) diff --git a/adafruit_bno08x/i2c.py b/adafruit_bno08x/i2c.py index 059f0bd..882acd5 100644 --- a/adafruit_bno08x/i2c.py +++ b/adafruit_bno08x/i2c.py @@ -7,7 +7,7 @@ """ from struct import pack_into -import adafruit_bus_device.i2c_device as i2c_device +from adafruit_bus_device import i2c_device from . import BNO08X, DATA_BUFFER_SIZE, const, Packet, PacketError _BNO08X_DEFAULT_ADDRESS = const(0x4A) diff --git a/adafruit_bno08x/spi.py b/adafruit_bno08x/spi.py index 194d439..9337f0f 100644 --- a/adafruit_bno08x/spi.py +++ b/adafruit_bno08x/spi.py @@ -10,7 +10,7 @@ from struct import pack_into from digitalio import Direction, Pull -import adafruit_bus_device.spi_device as spi_device +from adafruit_bus_device import spi_device from . import BNO08X, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError From b7c2d3903cc8918b4df24376bdc6b8f9a6e3d07a Mon Sep 17 00:00:00 2001 From: dherrada Date: Tue, 9 Nov 2021 15:35:05 -0500 Subject: [PATCH 054/106] Updated readthedocs file --- .readthedocs.yaml | 15 +++++++++++++++ .readthedocs.yml | 7 ------- 2 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 .readthedocs.yaml delete mode 100644 .readthedocs.yml diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..95ec218 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +python: + version: "3.6" + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 338427a..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: docs/requirements.txt From c0fe5a96a04428f2c882925fbb297ee166f26d0c Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 23 Nov 2021 12:59:52 -0600 Subject: [PATCH 055/106] update rtd py version --- .readthedocs.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 95ec218..1335112 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -9,7 +9,7 @@ version: 2 python: - version: "3.6" + version: "3.7" install: - requirements: docs/requirements.txt - requirements: requirements.txt From 5747e5f6bdd75089018edf18570781bc6e65ce17 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 13 Jan 2022 16:27:30 -0500 Subject: [PATCH 056/106] First part of patch Signed-off-by: dherrada --- .../PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md | 2 +- .github/workflows/build.yml | 6 +++--- .github/workflows/release.yml | 8 ++++---- .readthedocs.yaml | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md index 71ef8f8..8de294e 100644 --- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -4,7 +4,7 @@ Thank you for contributing! Before you submit a pull request, please read the following. -Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://circuitpython.readthedocs.io/en/latest/docs/design_guide.html +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f619953..71b3827 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,10 +22,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.7 - uses: actions/setup-python@v1 + - name: Set up Python 3.x + uses: actions/setup-python@v2 with: - python-version: 3.7 + python-version: "3.x" - name: Versions run: | python3 --version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d0015a..a65e5de 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,10 +24,10 @@ jobs: awk -F '\/' '{ print tolower($2) }' | tr '_' '-' ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 + - name: Set up Python 3.x + uses: actions/setup-python@v2 with: - python-version: 3.6 + python-version: "3.x" - name: Versions run: | python3 --version @@ -67,7 +67,7 @@ jobs: echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - name: Set up Python if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - uses: actions/setup-python@v1 + uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 1335112..f8b2891 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -9,7 +9,7 @@ version: 2 python: - version: "3.7" + version: "3.x" install: - requirements: docs/requirements.txt - requirements: requirements.txt From 0790406d212a029e1e6fdc175ba052d7a5f795f1 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 24 Jan 2022 16:46:16 -0500 Subject: [PATCH 057/106] Updated docs link, updated python docs link, updated setup.py --- README.rst | 4 ++-- docs/conf.py | 6 +++--- docs/index.rst | 2 +- setup.py | 2 -- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/README.rst b/README.rst index f9b6a59..9512e68 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-circuitpython-bno08x/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/bno08x/en/latest/ + :target: https://docs.circuitpython.org/projects/bno08x/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/discord/327254708534116352.svg @@ -77,7 +77,7 @@ Usage Example Documentation ============= -API documentation for this library can be found on `Read the Docs `_. +API documentation for this library can be found on `Read the Docs `_. Contributing ============ diff --git a/docs/conf.py b/docs/conf.py index e76ae80..aae0f44 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -25,12 +25,12 @@ intersphinx_mapping = { - "python": ("https://docs.python.org/3.4", None), + "python": ("https://docs.python.org/3", None), "BusDevice": ( - "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + "https://docs.circuitpython.org/projects/busdevice/en/latest/", None, ), - "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), } # Add any paths that contain templates here, relative to this directory. diff --git a/docs/index.rst b/docs/index.rst index 193e210..1b4e7f1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -33,7 +33,7 @@ Table of Contents :caption: Other Links Download - CircuitPython Reference Documentation + CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat Adafruit Learning System diff --git a/setup.py b/setup.py index fc3da88..ecdaa5f 100644 --- a/setup.py +++ b/setup.py @@ -48,8 +48,6 @@ "Topic :: System :: Hardware", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", ], # What does your project relate to? keywords="adafruit blinka circuitpython micropython bno080 IMU BNO055 SENSOR FUSION VR " From 0d602094029b9bb25d44184bd93ada2a1feaaf17 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Wed, 9 Feb 2022 12:41:53 -0500 Subject: [PATCH 058/106] Consolidate Documentation sections of README --- README.rst | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 9512e68..021ed25 100644 --- a/README.rst +++ b/README.rst @@ -79,14 +79,11 @@ Documentation API documentation for this library can be found on `Read the Docs `_. +For information on building library documentation, please check out `this guide `_. + Contributing ============ Contributions are welcome! Please read our `Code of Conduct `_ before contributing to help this project stay welcoming. - -Documentation -============= - -For information on building library documentation, please check out `this guide `_. From f2f9d1d87c1ba18db15d4e2716de5f851e2574e4 Mon Sep 17 00:00:00 2001 From: dherrada Date: Mon, 14 Feb 2022 15:35:02 -0500 Subject: [PATCH 059/106] Fixed readthedocs build Signed-off-by: dherrada --- .readthedocs.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index f8b2891..33c2a61 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,8 +8,12 @@ # Required version: 2 +build: + os: ubuntu-20.04 + tools: + python: "3" + python: - version: "3.x" install: - requirements: docs/requirements.txt - requirements: requirements.txt From 0ead90630bb5782039461c2efae40a52ca35c316 Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Mon, 28 Mar 2022 15:52:04 -0400 Subject: [PATCH 060/106] Update Black to latest. Signed-off-by: Kattni Rembor --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 43d1385..29230db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ repos: - repo: https://github.com/python/black - rev: 20.8b1 + rev: 22.3.0 hooks: - id: black - repo: https://github.com/fsfe/reuse-tool From b9d9a9b1ee508990416cb830b1ab18d8bded5f02 Mon Sep 17 00:00:00 2001 From: Eva Herrada <33632497+evaherrada@users.noreply.github.com> Date: Thu, 21 Apr 2022 18:37:35 -0400 Subject: [PATCH 061/106] Update .gitignore --- .gitignore | 50 +++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index 9c621df..544ec4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,47 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT +# Do not include files and directories created by your personal work environment, such as the IDE +# you use, except for those already listed here. Pull requests including changes to this file will +# not be accepted. + +# This .gitignore file contains rules for files generated by working with CircuitPython libraries, +# including building Sphinx, testing with pip, and creating a virual environment, as well as the +# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. + +# If you find that there are files being generated on your machine that should not be included in +# your git commit, you should create a .gitignore_global file on your computer to include the +# files created by your personal setup. To do so, follow the two steps below. + +# First, create a file called .gitignore_global somewhere convenient for you, and add rules for +# the files you want to exclude from git commits. + +# Second, configure Git to use the exclude file for all Git repositories by running the +# following via commandline, replacing "path/to/your/" with the actual path to your newly created +# .gitignore_global file: +# git config --global core.excludesfile path/to/your/.gitignore_global + +# CircuitPython-specific files *.mpy -.idea + +# Python-specific files __pycache__ -_build *.pyc + +# Sphinx build-specific files +_build + +# This file results from running `pip -e install .` in a local repository +*.egg-info + +# Virtual environment-specific files .env -.python-version -build*/ -bundles + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea .vscode -*notes* +*~ From 0853243fab28775753b0d80f7e76eb5e03d3f26a Mon Sep 17 00:00:00 2001 From: evaherrada Date: Fri, 22 Apr 2022 15:58:28 -0400 Subject: [PATCH 062/106] Patch: Replaced discord badge image --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 021ed25..686d6ef 100644 --- a/README.rst +++ b/README.rst @@ -5,7 +5,7 @@ Introduction :target: https://docs.circuitpython.org/projects/bno08x/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bundle/blob/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord From 3832cb2e976d9e4c283c6c4da629ba52f9660fca Mon Sep 17 00:00:00 2001 From: foamyguy Date: Sun, 24 Apr 2022 13:49:50 -0500 Subject: [PATCH 063/106] change discord badge --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 686d6ef..c864f22 100644 --- a/README.rst +++ b/README.rst @@ -5,7 +5,7 @@ Introduction :target: https://docs.circuitpython.org/projects/bno08x/en/latest/ :alt: Documentation Status -.. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bundle/blob/main/badges/adafruit_discord.svg +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord From 579539960b3cde18138a426f7b3d484d161541e0 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 15 May 2022 12:21:48 -0400 Subject: [PATCH 064/106] Patch .pre-commit-config.yaml --- .pre-commit-config.yaml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 29230db..0a91a11 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,40 +3,40 @@ # SPDX-License-Identifier: Unlicense repos: -- repo: https://github.com/python/black + - repo: https://github.com/python/black rev: 22.3.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - id: black + - repo: https://github.com/fsfe/reuse-tool + rev: v0.14.0 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: reuse + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.2.0 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace -- repo: https://github.com/pycqa/pylint + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/pycqa/pylint rev: v2.11.1 hooks: - - id: pylint + - id: pylint name: pylint (library code) types: [python] args: - --disable=consider-using-f-string,duplicate-code exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint + - id: pylint name: pylint (example code) description: Run pylint rules on "examples/*.py" files types: [python] files: "^examples/" args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint + - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code + - id: pylint name: pylint (test code) description: Run pylint rules on "tests/*.py" files types: [python] files: "^tests/" args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - --disable=missing-docstring,consider-using-f-string,duplicate-code From 9ced461b14f42d97869535003db653e9329680a0 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 22 May 2022 00:18:55 -0400 Subject: [PATCH 065/106] Increase min lines similarity Signed-off-by: Alec Delaney --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index bd3976d..d411a3c 100644 --- a/.pylintrc +++ b/.pylintrc @@ -252,7 +252,7 @@ ignore-docstrings=yes ignore-imports=yes # Minimum lines number of a similarity. -min-similarity-lines=4 +min-similarity-lines=12 [BASIC] From b712fb357480ee9b1ebb2e43ae2adaee3a541bd6 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Sun, 22 May 2022 00:18:23 -0400 Subject: [PATCH 066/106] Switch to inclusive terminology Signed-off-by: Alec Delaney --- .pylintrc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pylintrc b/.pylintrc index d411a3c..66d688f 100644 --- a/.pylintrc +++ b/.pylintrc @@ -9,11 +9,11 @@ # run arbitrary code extension-pkg-whitelist= -# Add files or directories to the blacklist. They should be base names, not +# Add files or directories to the ignore-list. They should be base names, not # paths. ignore=CVS -# Add files or directories matching the regex patterns to the blacklist. The +# Add files or directories matching the regex patterns to the ignore-list. The # regex matches against base names, not paths. ignore-patterns= From 181bf6b6463e7a807fcf6f44112e7df3b876eee5 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 30 May 2022 14:25:04 -0400 Subject: [PATCH 067/106] Set language to "en" for documentation Signed-off-by: Alec Delaney --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index aae0f44..8453c72 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -60,7 +60,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. From 20c70f460a1ed3a6c033d7664bfaac3dd480dac6 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Tue, 7 Jun 2022 15:34:10 -0400 Subject: [PATCH 068/106] Added cp.org link to index.rst --- docs/index.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 1b4e7f1..8d63075 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -32,7 +32,8 @@ Table of Contents .. toctree:: :caption: Other Links - Download + Download from GitHub + Download Library Bundle CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat From 651de900e73a13dfcf67aba66a53eca0440ac314 Mon Sep 17 00:00:00 2001 From: evaherrada Date: Tue, 21 Jun 2022 17:00:37 -0400 Subject: [PATCH 069/106] Removed duplicate-code from library pylint disable Signed-off-by: evaherrada --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0a91a11..3343606 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: name: pylint (library code) types: [python] args: - - --disable=consider-using-f-string,duplicate-code + - --disable=consider-using-f-string exclude: "^(docs/|examples/|tests/|setup.py$)" - id: pylint name: pylint (example code) From d53724d496627ba6ba2045641eaf64df0822851c Mon Sep 17 00:00:00 2001 From: evaherrada Date: Fri, 22 Jul 2022 13:58:37 -0400 Subject: [PATCH 070/106] Changed .env to .venv in README.rst --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index c864f22..e237e41 100644 --- a/README.rst +++ b/README.rst @@ -52,8 +52,8 @@ To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip3 install adafruit-circuitpython-bno08x Usage Example From 9e474bd26dd6583d2f844634c270b19c4eeefeba Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 8 Aug 2022 22:05:52 -0400 Subject: [PATCH 071/106] Switched to pyproject.toml --- .github/workflows/build.yml | 23 +++++++++----- .github/workflows/release.yml | 17 ++++++---- optional_requirements.txt | 3 ++ pyproject.toml | 53 ++++++++++++++++++++++++++++--- requirements.txt | 5 ++- setup.py | 60 ----------------------------------- 6 files changed, 79 insertions(+), 82 deletions(-) create mode 100644 optional_requirements.txt delete mode 100644 setup.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 71b3827..22f6582 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,24 +47,31 @@ jobs: pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - name: Library version run: git describe --dirty --always --tags + - name: Setup problem matchers + uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - name: Pre-commit hooks run: | pre-commit run --all-files - name: Build assets run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . + - name: Archive bundles + uses: actions/upload-artifact@v2 + with: + name: bundles + path: ${{ github.workspace }}/bundles/ - name: Build docs working-directory: docs run: sphinx-build -E -W -b html . _build/html - - name: Check For setup.py + - name: Check For pyproject.toml id: need-pypi run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) + echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal + pip install --upgrade build twine + for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do + sed -i -e "s/0.0.0-auto.0/1.2.3/" $file; + done; + python -m build twine check dist/* - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a65e5de..d1b4f8d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,25 +61,28 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - - name: Check For setup.py + - name: Check For pyproject.toml id: need-pypi run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) + echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') run: | python -m pip install --upgrade pip - pip install setuptools wheel twine + pip install --upgrade build twine - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') + if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') env: TWINE_USERNAME: ${{ secrets.pypi_username }} TWINE_PASSWORD: ${{ secrets.pypi_password }} run: | - python setup.py sdist + for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do + sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; + done; + python -m build twine upload dist/* diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..d4e27c4 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml index f3c35ae..642d22a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,51 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT -[tool.black] -target-version = ['py35'] +[build-system] +requires = [ + "setuptools", + "wheel", +] + +[project] +name = "adafruit-circuitpython-bno08x" +description = "Helper library for the Hillcrest Laboratories BNO08x IMUs" +version = "0.0.0-auto.0" +readme = "README.rst" +authors = [ + {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} +] +urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_BNO08x"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "bno080", + "IMU", + "BNO055", + "SENSOR", + "FUSION", + "VR", + "MOTION", + "TRACK", + "BNO085", +] +license = {text = "MIT"} +classifiers = [ + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Embedded Systems", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", +] +dynamic = ["dependencies", "optional-dependencies"] + +[tool.setuptools] +packages = ["adafruit_bno08x"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index 3207dbb..a45c547 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,6 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # -# SPDX-License-Identifier: MIT +# SPDX-License-Identifier: Unlicense Adafruit-Blinka adafruit-circuitpython-busdevice diff --git a/setup.py b/setup.py deleted file mode 100644 index ecdaa5f..0000000 --- a/setup.py +++ /dev/null @@ -1,60 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -"""A setuptools based setup module. - -See: -https://packaging.python.org/en/latest/distributing.html -https://github.com/pypa/sampleproject -""" - -from setuptools import setup, find_packages - -# To use a consistent encoding -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, "README.rst"), encoding="utf-8") as f: - long_description = f.read() - -setup( - name="adafruit-circuitpython-bno08x", - use_scm_version=True, - setup_requires=["setuptools_scm"], - description="Helper library for the Hillcrest Laboratories BNO08x IMUs", - long_description=long_description, - long_description_content_type="text/x-rst", - # The project's main homepage. - url="https://github.com/adafruit/Adafruit_CircuitPython_BNO08x", - # Author details - author="Adafruit Industries", - author_email="circuitpython@adafruit.com", - install_requires=[ - "Adafruit-Blinka", - "adafruit-circuitpython-busdevice", - ], - # Choose your license - license="MIT", - # See https://pypi.python.org/pypi?%3Aaction=list_classifiers - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries", - "Topic :: System :: Hardware", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", - ], - # What does your project relate to? - keywords="adafruit blinka circuitpython micropython bno080 IMU BNO055 SENSOR FUSION VR " - "MOTION TRACK BNO085", - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, - # CHANGE `py_modules=['...']` TO `packages=['...']` - packages=["adafruit_bno08x"], -) From dd53c2992e488801c7beefb317b97ecda5cd7a3d Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 9 Aug 2022 12:03:54 -0400 Subject: [PATCH 072/106] Add setuptools-scm to build system requirements Signed-off-by: Alec Delaney --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 642d22a..9832dc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,6 +6,7 @@ requires = [ "setuptools", "wheel", + "setuptools-scm", ] [project] From 8f5bdaf3057464172b7d5c64260efc02d910a84b Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 16 Aug 2022 18:09:13 -0400 Subject: [PATCH 073/106] Update version string --- adafruit_bno08x/__init__.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index dff7225..1561a8b 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -25,7 +25,7 @@ * `Adafruit's Bus Device library `_ """ -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https:# github.com/adafruit/Adafruit_CircuitPython_BNO08x.git" from struct import unpack_from, pack_into diff --git a/pyproject.toml b/pyproject.toml index 9832dc6..ad4db79 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ requires = [ [project] name = "adafruit-circuitpython-bno08x" description = "Helper library for the Hillcrest Laboratories BNO08x IMUs" -version = "0.0.0-auto.0" +version = "0.0.0+auto.0" readme = "README.rst" authors = [ {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} From c4a0fca41e846855b7c81a5ac4f35a868c6134f7 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 16 Aug 2022 21:09:13 -0400 Subject: [PATCH 074/106] Fix version strings in workflow files --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 22f6582..cb2f60e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -71,7 +71,7 @@ jobs: run: | pip install --upgrade build twine for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0-auto.0/1.2.3/" $file; + sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; done; python -m build twine check dist/* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1b4f8d..f3a0325 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,7 +82,7 @@ jobs: TWINE_PASSWORD: ${{ secrets.pypi_password }} run: | for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; + sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; done; python -m build twine upload dist/* From 87f0d524bd2d0729a02bfcf72c020b4e8aec9a53 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Mon, 22 Aug 2022 21:36:30 -0400 Subject: [PATCH 075/106] Keep copyright up to date in documentation --- docs/conf.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 8453c72..0ee9ed9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -6,6 +6,7 @@ import os import sys +import datetime sys.path.insert(0, os.path.abspath("..")) @@ -43,7 +44,8 @@ # General information about the project. project = "Adafruit BNO08x Library" -copyright = "2020 Bryan Siepert" +current_year = str(datetime.datetime.now().year) +copyright = current_year + " Bryan Siepert" author = "Bryan Siepert" # The version info for the project you're documenting, acts as replacement for From c8c7cf01199c658db83e00266f84bb13eb3bab99 Mon Sep 17 00:00:00 2001 From: Alec Delaney Date: Tue, 23 Aug 2022 17:26:20 -0400 Subject: [PATCH 076/106] Use year duration range for copyright attribution --- docs/conf.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 0ee9ed9..c9d83fc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -44,8 +44,14 @@ # General information about the project. project = "Adafruit BNO08x Library" +creation_year = "2020" current_year = str(datetime.datetime.now().year) -copyright = current_year + " Bryan Siepert" +year_duration = ( + current_year + if current_year == creation_year + else creation_year + " - " + current_year +) +copyright = year_duration + " Bryan Siepert" author = "Bryan Siepert" # The version info for the project you're documenting, acts as replacement for From 6f941481f94aae4583b1b65ec4c1529055767247 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 00:02:49 -0400 Subject: [PATCH 077/106] Switching to composite actions --- .github/workflows/build.yml | 67 +---------------------- .github/workflows/release.yml | 88 ------------------------------ .github/workflows/release_gh.yml | 14 +++++ .github/workflows/release_pypi.yml | 14 +++++ 4 files changed, 30 insertions(+), 153 deletions(-) delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/release_gh.yml create mode 100644 .github/workflows/release_pypi.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cb2f60e..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,68 +10,5 @@ jobs: test: runs-on: ubuntu-latest steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install Sphinx, pre-commit - run: | - pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Build docs - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Check For pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - pip install --upgrade build twine - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; - done; - python -m build - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index f3a0325..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,88 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install deps - run: | - source actions-ci/install.sh - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Upload Release Assets - # the 'official' actions version does not yet support dynamically - # supplying asset names to upload. @csexton's version chosen based on - # discussion in the issue below, as its the simplest to implement and - # allows for selecting files with a pattern. - # https://github.com/actions/upload-release-asset/issues/4 - #uses: actions/upload-release-asset@v1.0.1 - uses: csexton/release-asset-action@master - with: - pattern: "bundles/*" - github-token: ${{ secrets.GITHUB_TOKEN }} - - upload-pypi: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Check For pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - python -m pip install --upgrade pip - pip install --upgrade build twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; - done; - python -m build - twine upload dist/* diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..041a337 --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml new file mode 100644 index 0000000..041a337 --- /dev/null +++ b/.github/workflows/release_pypi.yml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main From 1d29c3daf1af7eef1f1864d68a088c987dbee7ba Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 00:46:59 -0400 Subject: [PATCH 078/106] Updated pylint version to 2.13.0 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3343606..4c43710 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.11.1 + rev: v2.13.0 hooks: - id: pylint name: pylint (library code) From 121a24b68b0de4ffb4acd9525cfe960b85d5c6a1 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 08:15:19 -0400 Subject: [PATCH 079/106] Update pylint to 2.15.5 --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4c43710..0e5fccc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.13.0 + rev: v2.15.5 hooks: - id: pylint name: pylint (library code) From 4b1e89024a9229b1b745c1cce69cbac7a5d397cc Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 09:12:43 -0400 Subject: [PATCH 080/106] Fix release CI files --- .github/workflows/release_gh.yml | 14 +++++++++----- .github/workflows/release_pypi.yml | 15 ++++++++++----- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml index 041a337..b8aa8d6 100644 --- a/.github/workflows/release_gh.yml +++ b/.github/workflows/release_gh.yml @@ -2,13 +2,17 @@ # # SPDX-License-Identifier: MIT -name: Build CI +name: GitHub Release Actions -on: [pull_request, push] +on: + release: + types: [published] jobs: - test: + upload-release-assets: runs-on: ubuntu-latest steps: - - name: Run Build CI workflow - uses: adafruit/workflows-circuitpython-libs/build@main + - name: Run GitHub Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-gh@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml index 041a337..65775b7 100644 --- a/.github/workflows/release_pypi.yml +++ b/.github/workflows/release_pypi.yml @@ -2,13 +2,18 @@ # # SPDX-License-Identifier: MIT -name: Build CI +name: PyPI Release Actions -on: [pull_request, push] +on: + release: + types: [published] jobs: - test: + upload-release-assets: runs-on: ubuntu-latest steps: - - name: Run Build CI workflow - uses: adafruit/workflows-circuitpython-libs/build@main + - name: Run PyPI Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-pypi@main + with: + pypi-username: ${{ secrets.pypi_username }} + pypi-password: ${{ secrets.pypi_password }} From 5bce99f2816bdb3ecbade810252de58f900a6666 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 4 Nov 2022 18:34:32 -0400 Subject: [PATCH 081/106] Update .pylintrc for v2.15.5 --- .pylintrc | 43 +++---------------------------------------- 1 file changed, 3 insertions(+), 40 deletions(-) diff --git a/.pylintrc b/.pylintrc index 66d688f..40208c3 100644 --- a/.pylintrc +++ b/.pylintrc @@ -26,7 +26,7 @@ jobs=1 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. -load-plugins= +load-plugins=pylint.extensions.no_self_use # Pickle collected data for later comparisons. persistent=yes @@ -54,8 +54,8 @@ confidence= # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" -# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,unspecified-encoding +# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call +disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -225,12 +225,6 @@ max-line-length=100 # Maximum number of lines in a module max-module-lines=1000 -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no @@ -257,38 +251,22 @@ min-similarity-lines=12 [BASIC] -# Naming hint for argument names -argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - # Regular expression matching correct argument names argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ -# Naming hint for attribute names -attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - # Regular expression matching correct attribute names attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ -# Naming hint for class names -# class-name-hint=[A-Z_][a-zA-Z0-9]+$ -class-name-hint=[A-Z_][a-zA-Z0-9_]+$ - # Regular expression matching correct class names # class-rgx=[A-Z_][a-zA-Z0-9]+$ class-rgx=[A-Z_][a-zA-Z0-9_]+$ -# Naming hint for constant names -const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ @@ -296,9 +274,6 @@ const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # ones are exempt. docstring-min-length=-1 -# Naming hint for function names -function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - # Regular expression matching correct function names function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ @@ -309,21 +284,12 @@ good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ # Include a hint for the correct naming format with invalid-name include-naming-hint=no -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ -# Naming hint for method names -method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - # Regular expression matching correct method names method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ @@ -339,9 +305,6 @@ no-docstring-rgx=^_ # to this list to register other decorators that produce valid properties. property-classes=abc.abstractproperty -# Naming hint for variable names -variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - # Regular expression matching correct variable names variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ From e924532a21af35fe46024b5d25310fd83d999104 Mon Sep 17 00:00:00 2001 From: dherrada Date: Fri, 18 Nov 2022 13:05:21 -0500 Subject: [PATCH 082/106] Added commented out board.STEMMA_I2C with explanation --- examples/bno08x_quaternion_service.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/bno08x_quaternion_service.py b/examples/bno08x_quaternion_service.py index fd77924..d4b3415 100644 --- a/examples/bno08x_quaternion_service.py +++ b/examples/bno08x_quaternion_service.py @@ -8,7 +8,8 @@ from adafruit_ble_adafruit.quaternion_service import QuaternionService from adafruit_bno08x import BNO08X -i2c = board.I2C() +i2c = board.I2C() # uses board.SCL and board.SDA +# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller bno = BNO08X(i2c) quat_svc = QuaternionService() From 5d8cb90e7cafac2d1c4cd5739bbea3cafeeb56d5 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Thu, 1 Sep 2022 20:16:31 -0400 Subject: [PATCH 083/106] Add .venv to .gitignore Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com> --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 544ec4a..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ _build # Virtual environment-specific files .env +.venv # MacOS-specific files *.DS_Store From 3f643ca9e7e42f6cde142cbafc50f77596009149 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Thu, 19 Jan 2023 23:39:55 -0500 Subject: [PATCH 084/106] Add upload url to release action Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com> --- .github/workflows/release_gh.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml index b8aa8d6..9acec60 100644 --- a/.github/workflows/release_gh.yml +++ b/.github/workflows/release_gh.yml @@ -16,3 +16,4 @@ jobs: uses: adafruit/workflows-circuitpython-libs/release-gh@main with: github-token: ${{ secrets.GITHUB_TOKEN }} + upload-url: ${{ github.event.release.upload_url }} From 9a42fd50cc6ced9443ec54e6e1f88191bf91413d Mon Sep 17 00:00:00 2001 From: Mike Bruins Date: Tue, 7 Mar 2023 22:23:02 +1030 Subject: [PATCH 085/106] Update bno08x_find_heading.py Remove unused report BNO_REPORT_STEP_COUNTER --- examples/bno08x_find_heading.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/examples/bno08x_find_heading.py b/examples/bno08x_find_heading.py index b156ace..e0c3f1d 100644 --- a/examples/bno08x_find_heading.py +++ b/examples/bno08x_find_heading.py @@ -6,7 +6,6 @@ from board import SCL, SDA from busio import I2C from adafruit_bno08x import ( - BNO_REPORT_STEP_COUNTER, BNO_REPORT_ROTATION_VECTOR, BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR, ) @@ -14,7 +13,6 @@ i2c = I2C(SCL, SDA, frequency=800000) bno = BNO08X_I2C(i2c) -bno.enable_feature(BNO_REPORT_STEP_COUNTER) bno.enable_feature(BNO_REPORT_ROTATION_VECTOR) bno.enable_feature(BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR) From 4046c60a286f5e1780e43bc6aa9b562ab82c0d93 Mon Sep 17 00:00:00 2001 From: EthChil Date: Mon, 3 Apr 2023 23:54:50 -0400 Subject: [PATCH 086/106] added gravity vector validated with BNO085 --- adafruit_bno08x/__init__.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 1561a8b..f2d999e 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -81,6 +81,9 @@ BNO_REPORT_LINEAR_ACCELERATION = const(0x04) # Rotation Vector BNO_REPORT_ROTATION_VECTOR = const(0x05) +# Gravity Vector (m/s2). Vector direction of gravity +BNO_REPORT_GRAVITY = const(0x06) +# Game Rotation Vector BNO_REPORT_GAME_ROTATION_VECTOR = const(0x08) BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR = const(0x09) @@ -139,6 +142,7 @@ } _AVAIL_SENSOR_REPORTS = { BNO_REPORT_ACCELEROMETER: (_Q_POINT_8_SCALAR, 3, 10), + BNO_REPORT_GRAVITY: (_Q_POINT_8_SCALAR, 3, 10), BNO_REPORT_GYROSCOPE: (_Q_POINT_9_SCALAR, 3, 10), BNO_REPORT_MAGNETOMETER: (_Q_POINT_4_SCALAR, 3, 10), BNO_REPORT_LINEAR_ACCELERATION: (_Q_POINT_8_SCALAR, 3, 10), @@ -370,15 +374,6 @@ def _separate_batch(packet, report_slices): next_byte_index = next_byte_index + required_bytes -# class Report: -# _buffer = bytearray(DATA_BUFFER_SIZE) -# _report_obj = Report(_buffer) - -# @classmethod -# def get_report(cls) -# return cls._report_obj - - class Packet: """A class representing a Hillcrest LaboratorySensor Hub Transport packet""" @@ -597,6 +592,16 @@ def acceleration(self): except KeyError: raise RuntimeError("No accel report found, is it enabled?") from None + @property + def gravity(self): + """A tuple representing the gravity vector in the X, Y, and Z components + axes in meters per second squared""" + self._process_available_packets() + try: + return self._readings[BNO_REPORT_GRAVITY] + except KeyError: + raise RuntimeError("No gravity report found, is it enabled?") from None + @property def gyro(self): """A tuple representing Gyro's rotation measurements on the X, Y, and Z From daca094d843adb03b99c85d28415663dd7dcee7e Mon Sep 17 00:00:00 2001 From: Rauha Rahkola Date: Tue, 25 Apr 2023 14:13:29 -0700 Subject: [PATCH 087/106] for #30, adding type annotations --- .gitignore | 6 ++ adafruit_bno08x/__init__.py | 165 +++++++++++++++++++----------------- 2 files changed, 93 insertions(+), 78 deletions(-) diff --git a/.gitignore b/.gitignore index db3d538..87b9508 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,12 @@ __pycache__ # Sphinx build-specific files _build +# MyPy-specific type-checking files +.mypy_cache + +# pip install files +/build/ + # This file results from running `pip -e install .` in a local repository *.egg-info diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index f2d999e..64a5b6d 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -25,6 +25,8 @@ * `Adafruit's Bus Device library `_ """ +from __future__ import annotations + __version__ = "0.0.0+auto.0" __repo__ = "https:# github.com/adafruit/Adafruit_CircuitPython_BNO08x.git" @@ -36,6 +38,12 @@ # TODO: Remove on release from .debug import channels, reports +# For IDE type recognition +try: + from typing import Any, Dict, List, Optional, Tuple, Union +except ImportError: + pass + # TODO: shorten names # Channel 0: the SHTP command channel BNO_CHANNEL_SHTP_COMMAND = const(0) @@ -206,12 +214,12 @@ class PacketError(Exception): pass # pylint:disable=unnecessary-pass -def _elapsed(start_time): +def _elapsed(start_time: float) -> float: return time.monotonic() - start_time ############ PACKET PARSING ########################### -def _parse_sensor_report_data(report_bytes): +def _parse_sensor_report_data(report_bytes: bytearray) -> Tuple[Any, int]: """Parses reports with only 16-bit fields""" data_offset = 4 # this may not always be true report_id = report_bytes[0] @@ -235,11 +243,11 @@ def _parse_sensor_report_data(report_bytes): return (results_tuple, accuracy) -def _parse_step_couter_report(report_bytes): +def _parse_step_couter_report(report_bytes: bytearray) -> int: return unpack_from(" str: classification_bitfield = unpack_from(" Tuple[Any, ...]: return unpack_from(" Dict[str, int]: activities = [ "Unknown", "In-Vehicle", # look @@ -292,12 +300,12 @@ def _parse_activity_classifier_report(report_bytes): return classification -def _parse_shake_report(report_bytes): +def _parse_shake_report(report_bytes: bytearray) -> bool: shake_bitfield = unpack_from(" 0 -def parse_sensor_id(buffer): +def parse_sensor_id(buffer: bytearray) -> Tuple[int, ...]: """Parse the fields of a product id report""" if not buffer[0] == _SHTP_REPORT_PRODUCT_ID_RESPONSE: raise AttributeError("Wrong report id for sensor id: %s" % hex(buffer[0])) @@ -311,8 +319,7 @@ def parse_sensor_id(buffer): return (sw_part_number, sw_major, sw_minor, sw_patch, sw_build_number) -def _parse_command_response(report_bytes): - +def _parse_command_response(report_bytes: bytearray) -> Tuple[Any, Any]: # CMD response report: # 0 Report ID = 0xF1 # 1 Sequence number @@ -327,8 +334,11 @@ def _parse_command_response(report_bytes): def _insert_command_request_report( - command, buffer, next_sequence_number, command_params=None -): + command: int, + buffer: bytearray, + next_sequence_number: int, + command_params: Optional[List[int]] = None, +) -> None: if command_params and len(command_params) > 9: raise AttributeError( "Command request reports can only have up to 9 arguments but %d were given" @@ -346,14 +356,14 @@ def _insert_command_request_report( buffer[3 + idx] = param -def _report_length(report_id): +def _report_length(report_id: int) -> int: if report_id < 0xF0: # it's a sensor report return _AVAIL_SENSOR_REPORTS[report_id][2] return _REPORT_LENGTHS[report_id] -def _separate_batch(packet, report_slices): +def _separate_batch(packet: Packet, report_slices: List[Any]) -> None: # get first report id, loop up its report length # read that many bytes, parse them next_byte_index = 0 @@ -377,13 +387,12 @@ def _separate_batch(packet, report_slices): class Packet: """A class representing a Hillcrest LaboratorySensor Hub Transport packet""" - def __init__(self, packet_bytes): + def __init__(self, packet_bytes: bytearray) -> None: self.header = self.header_from_buffer(packet_bytes) data_end_index = self.header.data_length + _BNO_HEADER_LEN self.data = packet_bytes[_BNO_HEADER_LEN:data_end_index] - def __str__(self): - + def __str__(self) -> str: length = self.header.packet_byte_count outstr = "\n\t\t********** Packet *************\n" outstr += "DBG::\t\t HEADER:\n" @@ -441,17 +450,17 @@ def __str__(self): return outstr @property - def report_id(self): + def report_id(self) -> int: """The Packet's Report ID""" return self.data[0] @property - def channel_number(self): + def channel_number(self) -> int: """The packet channel""" return self.header.channel_number @classmethod - def header_from_buffer(cls, packet_bytes): + def header_from_buffer(cls, packet_bytes: bytearray) -> PacketHeader: """Creates a `PacketHeader` object from a given buffer""" packet_byte_count = unpack_from(" bool: """Returns True if the header is an error condition""" if header.channel_number > 5: @@ -482,32 +491,29 @@ class BNO08X: # pylint: disable=too-many-instance-attributes, too-many-public-m """ - def __init__(self, reset=None, debug=False): - self._debug = debug - self._reset = reset + def __init__(self, reset: Optional[dict] = None, debug: bool = False) -> None: + self._debug: bool = debug + self._reset: Optional[dict] = reset self._dbg("********** __init__ *************") - self._data_buffer = bytearray(DATA_BUFFER_SIZE) - self._command_buffer = bytearray(12) - self._packet_slices = [] + self._data_buffer: bytearray = bytearray(DATA_BUFFER_SIZE) + self._command_buffer: bytearray = bytearray(12) + self._packet_slices: List[Any] = [] # TODO: this is wrong there should be one per channel per direction - self._sequence_number = [0, 0, 0, 0, 0, 0] - self._two_ended_sequence_numbers = { - "send": {}, # holds the next seq number to send with the report id as a key - "receive": {}, - } - self._dcd_saved_at = -1 - self._me_calibration_started_at = -1 + self._sequence_number: List[int] = [0, 0, 0, 0, 0, 0] + self._two_ended_sequence_numbers: Dict[int, int] = {} + self._dcd_saved_at: float = -1 + self._me_calibration_started_at: float = -1 self._calibration_complete = False self._magnetometer_accuracy = 0 self._wait_for_initialize = True self._init_complete = False self._id_read = False # for saving the most recent reading when decoding several packets - self._readings = {} + self._readings: Dict[int, Any] = {} self.initialize() - def initialize(self): + def initialize(self) -> None: """Initialize the sensor""" for _ in range(3): self.hard_reset() @@ -521,7 +527,7 @@ def initialize(self): raise RuntimeError("Could not read ID") @property - def magnetic(self): + def magnetic(self) -> Optional[Tuple[float, float, float]]: """A tuple of the current magnetic field measurements on the X, Y, and Z axes""" self._process_available_packets() # decorator? try: @@ -530,7 +536,7 @@ def magnetic(self): raise RuntimeError("No magfield report found, is it enabled?") from None @property - def quaternion(self): + def quaternion(self) -> Optional[Tuple[float, float, float, float]]: """A quaternion representing the current rotation vector""" self._process_available_packets() try: @@ -539,7 +545,7 @@ def quaternion(self): raise RuntimeError("No quaternion report found, is it enabled?") from None @property - def geomagnetic_quaternion(self): + def geomagnetic_quaternion(self) -> Optional[Tuple[float, float, float, float]]: """A quaternion representing the current geomagnetic rotation vector""" self._process_available_packets() try: @@ -550,7 +556,7 @@ def geomagnetic_quaternion(self): ) from None @property - def game_quaternion(self): + def game_quaternion(self) -> Optional[Tuple[float, float, float, float]]: """A quaternion representing the current rotation vector expressed as a quaternion with no specific reference for heading, while roll and pitch are referenced against gravity. To prevent sudden jumps in heading due to corrections, the `game_quaternion` property is not @@ -564,7 +570,7 @@ def game_quaternion(self): ) from None @property - def steps(self): + def steps(self) -> Optional[int]: """The number of steps detected since the sensor was initialized""" self._process_available_packets() try: @@ -573,7 +579,7 @@ def steps(self): raise RuntimeError("No steps report found, is it enabled?") from None @property - def linear_acceleration(self): + def linear_acceleration(self) -> Optional[Tuple[float, float, float]]: """A tuple representing the current linear acceleration values on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() @@ -583,7 +589,7 @@ def linear_acceleration(self): raise RuntimeError("No lin. accel report found, is it enabled?") from None @property - def acceleration(self): + def acceleration(self) -> Optional[Tuple[float, float, float]]: """A tuple representing the acceleration measurements on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() @@ -593,7 +599,7 @@ def acceleration(self): raise RuntimeError("No accel report found, is it enabled?") from None @property - def gravity(self): + def gravity(self) -> Optional[Tuple[float, float, float]]: """A tuple representing the gravity vector in the X, Y, and Z components axes in meters per second squared""" self._process_available_packets() @@ -603,7 +609,7 @@ def gravity(self): raise RuntimeError("No gravity report found, is it enabled?") from None @property - def gyro(self): + def gyro(self) -> Optional[Tuple[float, float, float]]: """A tuple representing Gyro's rotation measurements on the X, Y, and Z axes in radians per second""" self._process_available_packets() @@ -613,7 +619,7 @@ def gyro(self): raise RuntimeError("No gyro report found, is it enabled?") from None @property - def shake(self): + def shake(self) -> Optional[bool]: """True if a shake was detected on any axis since the last time it was checked This property has a "latching" behavior where once a shake is detected, it will stay in a @@ -631,7 +637,7 @@ def shake(self): raise RuntimeError("No shake report found, is it enabled?") from None @property - def stability_classification(self): + def stability_classification(self) -> Optional[str]: """Returns the sensor's assessment of it's current stability, one of: * "Unknown" - The sensor is unable to classify the current stability @@ -653,7 +659,7 @@ def stability_classification(self): ) from None @property - def activity_classification(self): + def activity_classification(self) -> Optional[dict]: """Returns the sensor's assessment of the activity that is creating the motions\ that it is sensing, one of: @@ -678,7 +684,7 @@ def activity_classification(self): ) from None @property - def raw_acceleration(self): + def raw_acceleration(self) -> Optional[Tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the accelerometer registers""" self._process_available_packets() try: @@ -690,7 +696,7 @@ def raw_acceleration(self): ) from None @property - def raw_gyro(self): + def raw_gyro(self) -> Optional[Tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the gyro registers""" self._process_available_packets() try: @@ -700,7 +706,7 @@ def raw_gyro(self): raise RuntimeError("No raw gyro report found, is it enabled?") from None @property - def raw_magnetic(self): + def raw_magnetic(self) -> Optional[Tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the magnetometer registers""" self._process_available_packets() try: @@ -709,7 +715,7 @@ def raw_magnetic(self): except KeyError: raise RuntimeError("No raw magnetic report found, is it enabled?") from None - def begin_calibration(self): + def begin_calibration(self) -> None: """Begin the sensor's self-calibration routine""" # start calibration for accel, gyro, and mag self._send_me_command( @@ -728,7 +734,7 @@ def begin_calibration(self): self._calibration_complete = False @property - def calibration_status(self): + def calibration_status(self) -> int: """Get the status of the self-calibration""" self._send_me_command( [ @@ -745,8 +751,7 @@ def calibration_status(self): ) return self._magnetometer_accuracy - def _send_me_command(self, subcommand_params): - + def _send_me_command(self, subcommand_params: Optional[List[int]]) -> None: start_time = time.monotonic() local_buffer = self._command_buffer _insert_command_request_report( @@ -762,7 +767,7 @@ def _send_me_command(self, subcommand_params): if self._me_calibration_started_at > start_time: break - def save_calibration_data(self): + def save_calibration_data(self) -> None: """Save the self-calibration data""" # send a DCD save command start_time = time.monotonic() @@ -782,7 +787,7 @@ def save_calibration_data(self): ############### private/helper methods ############### # # decorator? - def _process_available_packets(self, max_packets=None): + def _process_available_packets(self, max_packets: Optional[int] = None) -> None: processed_count = 0 while self._data_ready: if max_packets and processed_count > max_packets: @@ -800,7 +805,9 @@ def _process_available_packets(self, max_packets=None): self._dbg("") self._dbg(" ** DONE! **") - def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): + def _wait_for_packet_type( + self, channel_number: int, report_id: Optional[int] = None, timeout: float = 5.0 + ) -> Packet: if report_id: report_id_str = " with report id %s" % hex(report_id) else: @@ -825,7 +832,7 @@ def _wait_for_packet_type(self, channel_number, report_id=None, timeout=5.0): raise RuntimeError("Timed out waiting for a packet on channel", channel_number) - def _wait_for_packet(self, timeout=_PACKET_READ_TIMEOUT): + def _wait_for_packet(self, timeout: float = _PACKET_READ_TIMEOUT) -> Packet: start_time = time.monotonic() while _elapsed(start_time) < timeout: if not self._data_ready: @@ -837,12 +844,12 @@ def _wait_for_packet(self, timeout=_PACKET_READ_TIMEOUT): # update the cached sequence number so we know what to increment from # TODO: this is wrong there should be one per channel per direction # and apparently per report as well - def _update_sequence_number(self, new_packet): + def _update_sequence_number(self, new_packet: Packet) -> None: channel = new_packet.channel_number seq = new_packet.header.sequence_number self._sequence_number[channel] = seq - def _handle_packet(self, packet): + def _handle_packet(self, packet: Packet) -> None: # split out reports first try: _separate_batch(packet, self._packet_slices) @@ -852,7 +859,7 @@ def _handle_packet(self, packet): print(packet) raise error - def _handle_control_report(self, report_id, report_bytes): + def _handle_control_report(self, report_id: int, report_bytes: bytearray) -> None: if report_id == _SHTP_REPORT_PRODUCT_ID_RESPONSE: ( sw_part_number, @@ -876,7 +883,7 @@ def _handle_control_report(self, report_id, report_bytes): if report_id == _COMMAND_RESPONSE: self._handle_command_response(report_bytes) - def _handle_command_response(self, report_bytes): + def _handle_command_response(self, report_bytes: bytearray) -> None: (report_body, response_values) = _parse_command_response(report_bytes) ( @@ -899,7 +906,7 @@ def _handle_command_response(self, report_bytes): else: raise RuntimeError("Unable to save calibration data") - def _process_report(self, report_id, report_bytes): + def _process_report(self, report_id: int, report_bytes: bytearray) -> None: if report_id >= 0xF0: self._handle_control_report(report_id, report_bytes) return @@ -948,8 +955,10 @@ def _process_report(self, report_id, report_bytes): # TODO: Make this a Packet creation @staticmethod def _get_feature_enable_report( - feature_id, report_interval=_DEFAULT_REPORT_INTERVAL, sensor_specific_config=0 - ): + feature_id: int, + report_interval: Any = _DEFAULT_REPORT_INTERVAL, + sensor_specific_config: int = 0, + ) -> bytearray: set_feature_report = bytearray(17) set_feature_report[0] = _SET_FEATURE_COMMAND set_feature_report[1] = feature_id @@ -961,7 +970,7 @@ def _get_feature_enable_report( # TODO: add docs for available features # TODO2: I think this should call an fn that imports all the bits for the given feature # so we're not carrying around stuff for extra features - def enable_feature(self, feature_id): + def enable_feature(self, feature_id: int) -> None: """Used to enable a given feature of the BNO08x""" self._dbg("\n********** Enabling feature id:", feature_id, "**********") @@ -989,7 +998,7 @@ def enable_feature(self, feature_id): return raise RuntimeError("Was not able to enable feature", feature_id) - def _check_id(self): + def _check_id(self) -> bool: self._dbg("\n********** READ ID **********") if self._id_read: return True @@ -1012,7 +1021,7 @@ def _check_id(self): return False - def _parse_sensor_id(self): + def _parse_sensor_id(self) -> Optional[int]: if not self._data_buffer[4] == _SHTP_REPORT_PRODUCT_ID_RESPONSE: return None @@ -1030,21 +1039,21 @@ def _parse_sensor_id(self): # TODO: this is only one of the numbers! return sw_part_number - def _dbg(self, *args, **kwargs): + def _dbg(self, *args: Any, **kwargs: Any) -> None: if self._debug: print("DBG::\t\t", *args, **kwargs) - def _get_data(self, index, fmt_string): + def _get_data(self, index: int, fmt_string: str) -> Any: # index arg is not including header, so add 4 into data buffer data_index = index + 4 return unpack_from(fmt_string, self._data_buffer, offset=data_index)[0] # pylint:disable=no-self-use @property - def _data_ready(self): + def _data_ready(self) -> None: raise RuntimeError("Not implemented") - def hard_reset(self): + def hard_reset(self) -> None: """Hardware reset the sensor to an initial unconfigured state""" if not self._reset: return @@ -1058,7 +1067,7 @@ def hard_reset(self): self._reset.value = True time.sleep(0.01) - def soft_reset(self): + def soft_reset(self) -> None: """Reset the sensor to an initial unconfigured state""" self._dbg("Soft resetting...", end="") data = bytearray(1) @@ -1077,15 +1086,15 @@ def soft_reset(self): self._dbg("OK!") # all is good! - def _send_packet(self, channel, data): + def _send_packet(self, channel: int, data: bytearray) -> Optional[int]: raise RuntimeError("Not implemented") - def _read_packet(self): + def _read_packet(self) -> Optional[Packet]: raise RuntimeError("Not implemented") - def _increment_report_seq(self, report_id): + def _increment_report_seq(self, report_id: int) -> None: current = self._two_ended_sequence_numbers.get(report_id, 0) self._two_ended_sequence_numbers[report_id] = (current + 1) % 256 - def _get_report_seq_id(self, report_id): + def _get_report_seq_id(self, report_id: int) -> int: return self._two_ended_sequence_numbers.get(report_id, 0) From d29dd9a80a176e8aafe181418560b0de471fea68 Mon Sep 17 00:00:00 2001 From: Tekktrik Date: Tue, 9 May 2023 20:26:25 -0400 Subject: [PATCH 088/106] Update pre-commit hooks Signed-off-by: Tekktrik --- .pre-commit-config.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0e5fccc..70ade69 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,21 +4,21 @@ repos: - repo: https://github.com/python/black - rev: 22.3.0 + rev: 23.3.0 hooks: - id: black - repo: https://github.com/fsfe/reuse-tool - rev: v0.14.0 + rev: v1.1.2 hooks: - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.4.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + rev: v2.17.4 hooks: - id: pylint name: pylint (library code) From fe86645ae5d610ddfcea17c9f8a097b9f23daaa8 Mon Sep 17 00:00:00 2001 From: Tekktrik Date: Wed, 10 May 2023 22:28:58 -0400 Subject: [PATCH 089/106] Run pre-commit --- adafruit_bno08x/__init__.py | 3 --- examples/bno08x_simpletest.py | 1 - 2 files changed, 4 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index f2d999e..d2382d2 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -312,7 +312,6 @@ def parse_sensor_id(buffer): def _parse_command_response(report_bytes): - # CMD response report: # 0 Report ID = 0xF1 # 1 Sequence number @@ -383,7 +382,6 @@ def __init__(self, packet_bytes): self.data = packet_bytes[_BNO_HEADER_LEN:data_end_index] def __str__(self): - length = self.header.packet_byte_count outstr = "\n\t\t********** Packet *************\n" outstr += "DBG::\t\t HEADER:\n" @@ -746,7 +744,6 @@ def calibration_status(self): return self._magnetometer_accuracy def _send_me_command(self, subcommand_params): - start_time = time.monotonic() local_buffer = self._command_buffer _insert_command_request_report( diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index ddea6e0..647c4dc 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -21,7 +21,6 @@ bno.enable_feature(BNO_REPORT_ROTATION_VECTOR) while True: - time.sleep(0.5) print("Acceleration:") accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member From 48d9ebdf571470289d298a57a2a74ce7fd57652f Mon Sep 17 00:00:00 2001 From: Tekktrik Date: Sun, 14 May 2023 13:00:32 -0400 Subject: [PATCH 090/106] Update .pylintrc, fix jQuery for docs Signed-off-by: Tekktrik --- .pylintrc | 2 +- docs/conf.py | 1 + docs/requirements.txt | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 40208c3..f945e92 100644 --- a/.pylintrc +++ b/.pylintrc @@ -396,4 +396,4 @@ min-public-methods=1 # Exceptions that will emit a warning when being caught. Defaults to # "Exception" -overgeneral-exceptions=Exception +overgeneral-exceptions=builtins.Exception diff --git a/docs/conf.py b/docs/conf.py index c9d83fc..491b537 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,6 +17,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", diff --git a/docs/requirements.txt b/docs/requirements.txt index 88e6733..797aa04 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -3,3 +3,4 @@ # SPDX-License-Identifier: Unlicense sphinx>=4.0.0 +sphinxcontrib-jquery From 58bf8499d4493b657e633d10c985b816a565da75 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 30 May 2023 09:36:05 -0500 Subject: [PATCH 091/106] fix a few types --- .gitignore | 6 ------ adafruit_bno08x/__init__.py | 15 +++++++++------ 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 87b9508..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -32,12 +32,6 @@ __pycache__ # Sphinx build-specific files _build -# MyPy-specific type-checking files -.mypy_cache - -# pip install files -/build/ - # This file results from running `pip -e install .` in a local repository *.egg-info diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 64a5b6d..bf6aa50 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -41,6 +41,7 @@ # For IDE type recognition try: from typing import Any, Dict, List, Optional, Tuple, Union + from digitalio import DigitalInOut except ImportError: pass @@ -219,7 +220,7 @@ def _elapsed(start_time: float) -> float: ############ PACKET PARSING ########################### -def _parse_sensor_report_data(report_bytes: bytearray) -> Tuple[Any, int]: +def _parse_sensor_report_data(report_bytes: bytearray) -> Tuple[Tuple, int]: """Parses reports with only 16-bit fields""" data_offset = 4 # this may not always be true report_id = report_bytes[0] @@ -272,7 +273,7 @@ def _parse_get_feature_response_report(report_bytes: bytearray) -> Tuple[Any, .. # 4 Page Number + EOS # 5 Most likely state # 6-15 Classification (10 x Page Number) + confidence -def _parse_activity_classifier_report(report_bytes: bytearray) -> Dict[str, int]: +def _parse_activity_classifier_report(report_bytes: bytearray) -> Dict[str, str]: activities = [ "Unknown", "In-Vehicle", # look @@ -491,9 +492,11 @@ class BNO08X: # pylint: disable=too-many-instance-attributes, too-many-public-m """ - def __init__(self, reset: Optional[dict] = None, debug: bool = False) -> None: + def __init__( + self, reset: Optional[DigitalInOut] = None, debug: bool = False + ) -> None: self._debug: bool = debug - self._reset: Optional[dict] = reset + self._reset: Optional[DigitalInOut] = reset self._dbg("********** __init__ *************") self._data_buffer: bytearray = bytearray(DATA_BUFFER_SIZE) self._command_buffer: bytearray = bytearray(12) @@ -503,7 +506,7 @@ def __init__(self, reset: Optional[dict] = None, debug: bool = False) -> None: self._sequence_number: List[int] = [0, 0, 0, 0, 0, 0] self._two_ended_sequence_numbers: Dict[int, int] = {} self._dcd_saved_at: float = -1 - self._me_calibration_started_at: float = -1 + self._me_calibration_started_at: float = -1.0 self._calibration_complete = False self._magnetometer_accuracy = 0 self._wait_for_initialize = True @@ -956,7 +959,7 @@ def _process_report(self, report_id: int, report_bytes: bytearray) -> None: @staticmethod def _get_feature_enable_report( feature_id: int, - report_interval: Any = _DEFAULT_REPORT_INTERVAL, + report_interval: int = _DEFAULT_REPORT_INTERVAL, sensor_specific_config: int = 0, ) -> bytearray: set_feature_report = bytearray(17) From cfefd9430ffd67d5b912eb1ea7bfa08a859371a8 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 18 Sep 2023 16:22:34 -0500 Subject: [PATCH 092/106] "fix rtd theme " --- docs/conf.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 491b537..7ef4fc9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -107,19 +107,10 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -if not on_rtd: # only import and set the theme if we're building docs locally - try: - import sphinx_rtd_theme - - html_theme = "sphinx_rtd_theme" - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] - except: - html_theme = "default" - html_theme_path = ["."] -else: - html_theme_path = ["."] +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" +html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, From 6daec31074126dc3c80ea3b69dc380a74d54e14d Mon Sep 17 00:00:00 2001 From: Kunal Singla Date: Wed, 22 Nov 2023 17:10:32 -0800 Subject: [PATCH 093/106] fix baud rate for USB Serial --- examples/bno08x_simpletest_uart.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/bno08x_simpletest_uart.py b/examples/bno08x_simpletest_uart.py index ab67b1a..f657bd5 100644 --- a/examples/bno08x_simpletest_uart.py +++ b/examples/bno08x_simpletest_uart.py @@ -12,11 +12,11 @@ # uncomment and comment out the above for use with Raspberry Pi # import serial -# uart = serial.Serial("/dev/serial0", 115200) +# uart = serial.Serial("/dev/serial0", 3000000) -# for a USB Serial cable: +# for USB Serial (via FTDI cable): # import serial -# uart = serial.Serial("/dev/ttyUSB0", baudrate=115200) +# uart = serial.Serial("/dev/ttyUSB0", baudrate=3000000) bno = BNO08X_UART(uart) From 04d938e457994f1eded8d5fd7a49d5662be3ff52 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 16 Oct 2023 14:30:31 -0500 Subject: [PATCH 094/106] unpin sphinx and add sphinx-rtd-theme to docs reqs Signed-off-by: foamyguy --- docs/requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index 797aa04..979f568 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,5 +2,6 @@ # # SPDX-License-Identifier: Unlicense -sphinx>=4.0.0 +sphinx sphinxcontrib-jquery +sphinx-rtd-theme From 5566a1d15da5010f7daffe93a95614f17715f4d4 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 7 Oct 2024 09:24:05 -0500 Subject: [PATCH 095/106] remove deprecated get_html_theme_path() call Signed-off-by: foamyguy --- docs/conf.py | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 7ef4fc9..a28bd23 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -110,7 +110,6 @@ import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" -html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, From 95603550a0c62ccda2e8a8a7bdcf35f5691f99cd Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 14 Jan 2025 11:32:34 -0600 Subject: [PATCH 096/106] add sphinx configuration to rtd.yaml Signed-off-by: foamyguy --- .readthedocs.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 33c2a61..88bca9f 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,6 +8,9 @@ # Required version: 2 +sphinx: + configuration: docs/conf.py + build: os: ubuntu-20.04 tools: From 59d72cc800a57eda0702a6a427e758cad6c3e815 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 13 May 2025 20:09:16 +0000 Subject: [PATCH 097/106] start ruff change --- .gitattributes | 11 + .pre-commit-config.yaml | 43 +-- .pylintrc | 399 -------------------------- README.rst | 6 +- adafruit_bno08x/__init__.py | 81 ++---- adafruit_bno08x/debug.py | 1 + adafruit_bno08x/i2c.py | 11 +- adafruit_bno08x/spi.py | 21 +- adafruit_bno08x/uart.py | 9 +- docs/api.rst | 3 + docs/conf.py | 8 +- examples/bno08x_calibration.py | 2 + examples/bno08x_find_heading.py | 6 +- examples/bno08x_more_reports.py | 29 +- examples/bno08x_quaternion_service.py | 4 +- examples/bno08x_simpletest.py | 6 +- examples/bno08x_simpletest_spi.py | 6 +- examples/bno08x_simpletest_uart.py | 9 +- ruff.toml | 105 +++++++ 19 files changed, 206 insertions(+), 554 deletions(-) create mode 100644 .gitattributes delete mode 100644 .pylintrc create mode 100644 ruff.toml diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70ade69..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 23.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/README.rst b/README.rst index e237e41..e338e3a 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_BNO08x/actions :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff Helper library for the Hillcrest Laboratories BNO08x IMUs diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index bf6aa50..b4f3449 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -1,4 +1,3 @@ -# pylint:disable=too-many-lines # SPDX-FileCopyrightText: Copyright (c) 2020 Bryan Siepert for Adafruit Industries # # SPDX-License-Identifier: MIT @@ -25,14 +24,16 @@ * `Adafruit's Bus Device library `_ """ + from __future__ import annotations __version__ = "0.0.0+auto.0" __repo__ = "https:# github.com/adafruit/Adafruit_CircuitPython_BNO08x.git" -from struct import unpack_from, pack_into -from collections import namedtuple import time +from collections import namedtuple +from struct import pack_into, unpack_from + from micropython import const # TODO: Remove on release @@ -41,6 +42,7 @@ # For IDE type recognition try: from typing import Any, Dict, List, Optional, Tuple, Union + from digitalio import DigitalInOut except ImportError: pass @@ -186,9 +188,7 @@ BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR: (0.0, 0.0, 0.0, 0.0), } -_ENABLED_ACTIVITIES = ( - 0x1FF # All activities; 1 bit set for each of 8 activities, + Unknown -) +_ENABLED_ACTIVITIES = 0x1FF # All activities; 1 bit set for each of 8 activities, + Unknown DATA_BUFFER_SIZE = const(512) # data buffer size. obviously eats ram PacketHeader = namedtuple( @@ -212,7 +212,7 @@ class PacketError(Exception): """Raised when the packet couldnt be parsed""" - pass # pylint:disable=unnecessary-pass + pass def _elapsed(start_time: float) -> float: @@ -250,9 +250,7 @@ def _parse_step_couter_report(report_bytes: bytearray) -> int: def _parse_stability_classifier_report(report_bytes: bytearray) -> str: classification_bitfield = unpack_from(" str: self.report_id, ) else: - outstr += "DBG::\t\t \t** UNKNOWN Report Type **: %s\n" % hex( - self.report_id - ) + outstr += "DBG::\t\t \t** UNKNOWN Report Type **: %s\n" % hex(self.report_id) - if ( - self.report_id > 0xF0 - and len(self.data) >= 6 - and self.data[5] in reports - ): + if self.report_id > 0xF0 and len(self.data) >= 6 and self.data[5] in reports: outstr += "DBG::\t\t \tSensor Report Type: %s(%s)\n" % ( reports[self.data[5]], hex(self.data[5]), ) - if ( - self.report_id == 0xFC - and len(self.data) >= 6 - and self.data[1] in reports - ): + if self.report_id == 0xFC and len(self.data) >= 6 and self.data[1] in reports: outstr += "DBG::\t\t \tEnabled Feature: %s(%s)\n" % ( reports[self.data[1]], hex(self.data[5]), @@ -443,8 +431,8 @@ def __str__(self) -> str: for idx, packet_byte in enumerate(self.data[:length]): packet_index = idx + 4 if (packet_index % 4) == 0: - outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) - outstr += "0x{:02X} ".format(packet_byte) + outstr += f"\nDBG::\t\t[0x{packet_index:02X}] " + outstr += f"0x{packet_byte:02X} " outstr += "\n" outstr += "\t\t*******************************\n" @@ -469,9 +457,7 @@ def header_from_buffer(cls, packet_bytes: bytearray) -> PacketHeader: sequence_number = unpack_from(" bool: return False -class BNO08X: # pylint: disable=too-many-instance-attributes, too-many-public-methods +class BNO08X: """Library for the BNO08x IMUs from Hillcrest Laboratories :param ~busio.I2C i2c_bus: The I2C bus the BNO08x is connected to. """ - def __init__( - self, reset: Optional[DigitalInOut] = None, debug: bool = False - ) -> None: + def __init__(self, reset: Optional[DigitalInOut] = None, debug: bool = False) -> None: self._debug: bool = debug self._reset: Optional[DigitalInOut] = reset self._dbg("********** __init__ *************") @@ -524,7 +508,7 @@ def initialize(self) -> None: try: if self._check_id(): break - except: # pylint:disable=bare-except + except Exception: time.sleep(0.5) else: raise RuntimeError("Could not read ID") @@ -554,9 +538,7 @@ def geomagnetic_quaternion(self) -> Optional[Tuple[float, float, float, float]]: try: return self._readings[BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR] except KeyError: - raise RuntimeError( - "No geomag quaternion report found, is it enabled?" - ) from None + raise RuntimeError("No geomag quaternion report found, is it enabled?") from None @property def game_quaternion(self) -> Optional[Tuple[float, float, float, float]]: @@ -568,9 +550,7 @@ def game_quaternion(self) -> Optional[Tuple[float, float, float, float]]: try: return self._readings[BNO_REPORT_GAME_ROTATION_VECTOR] except KeyError: - raise RuntimeError( - "No game quaternion report found, is it enabled?" - ) from None + raise RuntimeError("No game quaternion report found, is it enabled?") from None @property def steps(self) -> Optional[int]: @@ -657,9 +637,7 @@ def stability_classification(self) -> Optional[str]: stability_classification = self._readings[BNO_REPORT_STABILITY_CLASSIFIER] return stability_classification except KeyError: - raise RuntimeError( - "No stability classification report found, is it enabled?" - ) from None + raise RuntimeError("No stability classification report found, is it enabled?") from None @property def activity_classification(self) -> Optional[dict]: @@ -682,9 +660,7 @@ def activity_classification(self) -> Optional[dict]: activity_classification = self._readings[BNO_REPORT_ACTIVITY_CLASSIFIER] return activity_classification except KeyError: - raise RuntimeError( - "No activity classification report found, is it enabled?" - ) from None + raise RuntimeError("No activity classification report found, is it enabled?") from None @property def raw_acceleration(self) -> Optional[Tuple[int, int, int]]: @@ -694,9 +670,7 @@ def raw_acceleration(self) -> Optional[Tuple[int, int, int]]: raw_acceleration = self._readings[BNO_REPORT_RAW_ACCELEROMETER] return raw_acceleration except KeyError: - raise RuntimeError( - "No raw acceleration report found, is it enabled?" - ) from None + raise RuntimeError("No raw acceleration report found, is it enabled?") from None @property def raw_gyro(self) -> Optional[Tuple[int, int, int]]: @@ -919,8 +893,8 @@ def _process_report(self, report_id: int, report_bytes: bytearray) -> None: for idx, packet_byte in enumerate(report_bytes): packet_index = idx if (packet_index % 4) == 0: - outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) - outstr += "0x{:02X} ".format(packet_byte) + outstr += f"\nDBG::\t\t[0x{packet_index:02X}] " + outstr += f"0x{packet_byte:02X} " self._dbg(outstr) self._dbg("") @@ -1013,9 +987,7 @@ def _check_id(self) -> bool: self._dbg("\n** Waiting for packet **") # _a_ packet arrived, but which one? while True: - self._wait_for_packet_type( - _BNO_CHANNEL_CONTROL, _SHTP_REPORT_PRODUCT_ID_RESPONSE - ) + self._wait_for_packet_type(_BNO_CHANNEL_CONTROL, _SHTP_REPORT_PRODUCT_ID_RESPONSE) sensor_id = self._parse_sensor_id() if sensor_id: self._id_read = True @@ -1051,7 +1023,6 @@ def _get_data(self, index: int, fmt_string: str) -> Any: data_index = index + 4 return unpack_from(fmt_string, self._data_buffer, offset=data_index)[0] - # pylint:disable=no-self-use @property def _data_ready(self) -> None: raise RuntimeError("Not implemented") @@ -1060,7 +1031,7 @@ def hard_reset(self) -> None: """Hardware reset the sensor to an initial unconfigured state""" if not self._reset: return - import digitalio # pylint:disable=import-outside-toplevel + import digitalio # noqa: PLC0415 self._reset.direction = digitalio.Direction.OUTPUT self._reset.value = True diff --git a/adafruit_bno08x/debug.py b/adafruit_bno08x/debug.py index 6534152..571de89 100644 --- a/adafruit_bno08x/debug.py +++ b/adafruit_bno08x/debug.py @@ -2,6 +2,7 @@ # # SPDX-License-Identifier: MIT """A collection of dictionaries for better debug messages""" + # TODO: Remove for size before release channels = { 0x0: "SHTP_COMMAND", diff --git a/adafruit_bno08x/i2c.py b/adafruit_bno08x/i2c.py index 882acd5..582de8d 100644 --- a/adafruit_bno08x/i2c.py +++ b/adafruit_bno08x/i2c.py @@ -3,12 +3,15 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno08x.BNO08X` to use I2C +Subclass of `adafruit_bno08x.BNO08X` to use I2C """ + from struct import pack_into + from adafruit_bus_device import i2c_device -from . import BNO08X, DATA_BUFFER_SIZE, const, Packet, PacketError + +from . import BNO08X, DATA_BUFFER_SIZE, Packet, PacketError, const _BNO08X_DEFAULT_ADDRESS = const(0x4A) @@ -20,9 +23,7 @@ class BNO08X_I2C(BNO08X): """ - def __init__( - self, i2c_bus, reset=None, address=_BNO08X_DEFAULT_ADDRESS, debug=False - ): + def __init__(self, i2c_bus, reset=None, address=_BNO08X_DEFAULT_ADDRESS, debug=False): self.bus_device_obj = i2c_device.I2CDevice(i2c_bus, address) super().__init__(reset, debug) diff --git a/adafruit_bno08x/spi.py b/adafruit_bno08x/spi.py index 9337f0f..dd6ed70 100644 --- a/adafruit_bno08x/spi.py +++ b/adafruit_bno08x/spi.py @@ -3,15 +3,17 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno08x.BNO08X` to use SPI +Subclass of `adafruit_bno08x.BNO08X` to use SPI """ + import time from struct import pack_into -from digitalio import Direction, Pull from adafruit_bus_device import spi_device -from . import BNO08X, DATA_BUFFER_SIZE, _elapsed, Packet, PacketError +from digitalio import Direction, Pull + +from . import BNO08X, DATA_BUFFER_SIZE, Packet, PacketError, _elapsed class BNO08X_SPI(BNO08X): @@ -30,12 +32,8 @@ class BNO08X_SPI(BNO08X): # """ - def __init__( - self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False - ): # pylint:disable=too-many-arguments - self._spi = spi_device.SPIDevice( - spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1 - ) + def __init__(self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False): # pylint:disable=too-many-arguments + self._spi = spi_device.SPIDevice(spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1) self._int = intpin super().__init__(resetpin, debug) @@ -115,10 +113,7 @@ def _read_packet(self): if packet_byte_count == 0: raise PacketError("No packet available") - self._dbg( - "channel %d has %d bytes available" - % (channel_number, packet_byte_count - 4) - ) + self._dbg("channel %d has %d bytes available" % (channel_number, packet_byte_count - 4)) if packet_byte_count > DATA_BUFFER_SIZE: self._data_buffer = bytearray(packet_byte_count) diff --git a/adafruit_bno08x/uart.py b/adafruit_bno08x/uart.py index f968268..3cd10c4 100644 --- a/adafruit_bno08x/uart.py +++ b/adafruit_bno08x/uart.py @@ -3,11 +3,13 @@ # SPDX-License-Identifier: MIT """ - Subclass of `adafruit_bno08x.BNO08X` to use UART +Subclass of `adafruit_bno08x.BNO08X` to use UART """ + import time from struct import pack_into + from . import ( BNO08X, BNO_CHANNEL_EXE, @@ -119,10 +121,7 @@ def _read_packet(self): if packet_byte_count == 0: raise PacketError("No packet available") - self._dbg( - "channel %d has %d bytes available" - % (channel_number, packet_byte_count - 4) - ) + self._dbg("channel %d has %d bytes available" % (channel_number, packet_byte_count - 4)) if packet_byte_count > DATA_BUFFER_SIZE: self._data_buffer = bytearray(packet_byte_count) diff --git a/docs/api.rst b/docs/api.rst index ecae971..94131db 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,5 +4,8 @@ .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" +API Reference +############# + .. automodule:: adafruit_bno08x :members: diff --git a/docs/conf.py b/docs/conf.py index a28bd23..a3fc27e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) @@ -48,9 +46,7 @@ creation_year = "2020" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Bryan Siepert" author = "Bryan Siepert" diff --git a/examples/bno08x_calibration.py b/examples/bno08x_calibration.py index 9a98f10..c6909ee 100644 --- a/examples/bno08x_calibration.py +++ b/examples/bno08x_calibration.py @@ -2,9 +2,11 @@ # # SPDX-License-Identifier: Unlicense import time + import board import busio from digitalio import DigitalInOut + import adafruit_bno08x from adafruit_bno08x.i2c import BNO08X_I2C diff --git a/examples/bno08x_find_heading.py b/examples/bno08x_find_heading.py index e0c3f1d..7a52ef2 100644 --- a/examples/bno08x_find_heading.py +++ b/examples/bno08x_find_heading.py @@ -2,12 +2,14 @@ # SPDX-License-Identifier: Unlicense import time -from math import atan2, sqrt, pi +from math import atan2, pi, sqrt + from board import SCL, SDA from busio import I2C + from adafruit_bno08x import ( - BNO_REPORT_ROTATION_VECTOR, BNO_REPORT_GEOMAGNETIC_ROTATION_VECTOR, + BNO_REPORT_ROTATION_VECTOR, ) from adafruit_bno08x.i2c import BNO08X_I2C diff --git a/examples/bno08x_more_reports.py b/examples/bno08x_more_reports.py index 15a6743..b705dd6 100644 --- a/examples/bno08x_more_reports.py +++ b/examples/bno08x_more_reports.py @@ -2,8 +2,10 @@ # # SPDX-License-Identifier: MIT import time + import board import busio + import adafruit_bno08x from adafruit_bno08x.i2c import BNO08X_I2C @@ -49,17 +51,12 @@ linear_accel_y, linear_accel_z, ) = bno.linear_acceleration # pylint:disable=no-member - print( - "X: %0.6f Y: %0.6f Z: %0.6f m/s^2" - % (linear_accel_x, linear_accel_y, linear_accel_z) - ) + print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (linear_accel_x, linear_accel_y, linear_accel_z)) print("") print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) - ) + print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)) print("") print("Geomagnetic Rotation Vector Quaternion:") @@ -108,11 +105,7 @@ raw_accel_y, raw_accel_z, ) = bno.raw_acceleration - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_accel_x, raw_accel_y, raw_accel_z - ) - ) + print(f"X: 0x{raw_accel_x:04X} Y: 0x{raw_accel_y:04X} Z: 0x{raw_accel_z:04X} LSB") print("") print("Raw Gyro:") @@ -121,11 +114,7 @@ raw_accel_y, raw_accel_z, ) = bno.raw_gyro - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_accel_x, raw_accel_y, raw_accel_z - ) - ) + print(f"X: 0x{raw_accel_x:04X} Y: 0x{raw_accel_y:04X} Z: 0x{raw_accel_z:04X} LSB") print("") print("Raw Magnetometer:") @@ -134,11 +123,7 @@ raw_mag_y, raw_mag_z, ) = bno.raw_magnetic - print( - "X: 0x{0:04X} Y: 0x{1:04X} Z: 0x{2:04X} LSB".format( - raw_mag_x, raw_mag_y, raw_mag_z - ) - ) + print(f"X: 0x{raw_mag_x:04X} Y: 0x{raw_mag_y:04X} Z: 0x{raw_mag_z:04X} LSB") print("") time.sleep(0.4) if bno.shake: diff --git a/examples/bno08x_quaternion_service.py b/examples/bno08x_quaternion_service.py index d4b3415..24ff0ca 100644 --- a/examples/bno08x_quaternion_service.py +++ b/examples/bno08x_quaternion_service.py @@ -2,10 +2,12 @@ # # SPDX-License-Identifier: MIT import time + import board from adafruit_ble import BLERadio from adafruit_ble_adafruit.adafruit_service import AdafruitServerAdvertisement from adafruit_ble_adafruit.quaternion_service import QuaternionService + from adafruit_bno08x import BNO08X i2c = board.I2C() # uses board.SCL and board.SDA @@ -33,7 +35,7 @@ ble.stop_advertising() while ble.connected: - now_msecs = time.monotonic_ns() // 1000000 # pylint: disable=no-member + now_msecs = time.monotonic_ns() // 1000000 if now_msecs - quat_last_read >= quat_svc.measurement_period: quat_svc.quaternion = bno.quaternion diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 647c4dc..0a1e989 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -2,8 +2,10 @@ # # SPDX-License-Identifier: Unlicense import time + import board import busio + from adafruit_bno08x import ( BNO_REPORT_ACCELEROMETER, BNO_REPORT_GYROSCOPE, @@ -39,7 +41,5 @@ print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) - ) + print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)) print("") diff --git a/examples/bno08x_simpletest_spi.py b/examples/bno08x_simpletest_spi.py index 747a7dc..f840349 100644 --- a/examples/bno08x_simpletest_spi.py +++ b/examples/bno08x_simpletest_spi.py @@ -2,9 +2,11 @@ # # SPDX-License-Identifier: Unlicense from time import sleep + import board import busio from digitalio import DigitalInOut, Direction + from adafruit_bno08x.spi import BNO08X_SPI # need to limit clock to 3Mhz @@ -28,8 +30,6 @@ print("getting quat") quat = bno.quaternion # pylint:disable=no-member print("Rotation Vector Quaternion:") - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat.i, quat.j, quat.k, quat.real) - ) + print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat.i, quat.j, quat.k, quat.real)) print("") sleep(0.5) diff --git a/examples/bno08x_simpletest_uart.py b/examples/bno08x_simpletest_uart.py index f657bd5..789030b 100644 --- a/examples/bno08x_simpletest_uart.py +++ b/examples/bno08x_simpletest_uart.py @@ -2,12 +2,13 @@ # # SPDX-License-Identifier: Unlicense import time -import adafruit_bno08x -from adafruit_bno08x.uart import BNO08X_UART import board # pylint:disable=wrong-import-order import busio # pylint:disable=wrong-import-order +import adafruit_bno08x +from adafruit_bno08x.uart import BNO08X_UART + uart = busio.UART(board.TX, board.RX, baudrate=3000000, receiver_buffer_size=2048) # uncomment and comment out the above for use with Raspberry Pi @@ -58,9 +59,7 @@ print("Rotation Vector Quaternion:") quat_i, quat_j, quat_k, quat_real = bno.quaternion # pylint:disable=no-member - print( - "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real) - ) + print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)) print("") # print("Linear Acceleration:") diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..36332ff --- /dev/null +++ b/ruff.toml @@ -0,0 +1,105 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions +] + +[format] +line-ending = "lf" From 5501a0af9f7611a65949f8c8187e44e593811625 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 13 May 2025 15:17:57 -0500 Subject: [PATCH 098/106] ruff lint fixes --- adafruit_bno08x/__init__.py | 58 ++++++++++++++++++------------------- ruff.toml | 2 ++ 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index b4f3449..4cf9f93 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -220,7 +220,7 @@ def _elapsed(start_time: float) -> float: ############ PACKET PARSING ########################### -def _parse_sensor_report_data(report_bytes: bytearray) -> Tuple[Tuple, int]: +def _parse_sensor_report_data(report_bytes: bytearray) -> tuple[tuple, int]: """Parses reports with only 16-bit fields""" data_offset = 4 # this may not always be true report_id = report_bytes[0] @@ -260,7 +260,7 @@ def _parse_stability_classifier_report(report_bytes: bytearray) -> str: # report_interval # batch_interval_word # sensor_specific_configuration_word -def _parse_get_feature_response_report(report_bytes: bytearray) -> Tuple[Any, ...]: +def _parse_get_feature_response_report(report_bytes: bytearray) -> tuple[Any, ...]: return unpack_from(" Tuple[Any, .. # 4 Page Number + EOS # 5 Most likely state # 6-15 Classification (10 x Page Number) + confidence -def _parse_activity_classifier_report(report_bytes: bytearray) -> Dict[str, str]: +def _parse_activity_classifier_report(report_bytes: bytearray) -> dict[str, str]: activities = [ "Unknown", "In-Vehicle", # look @@ -304,7 +304,7 @@ def _parse_shake_report(report_bytes: bytearray) -> bool: return (shake_bitfield & 0x111) > 0 -def parse_sensor_id(buffer: bytearray) -> Tuple[int, ...]: +def parse_sensor_id(buffer: bytearray) -> tuple[int, ...]: """Parse the fields of a product id report""" if not buffer[0] == _SHTP_REPORT_PRODUCT_ID_RESPONSE: raise AttributeError("Wrong report id for sensor id: %s" % hex(buffer[0])) @@ -318,7 +318,7 @@ def parse_sensor_id(buffer: bytearray) -> Tuple[int, ...]: return (sw_part_number, sw_major, sw_minor, sw_patch, sw_build_number) -def _parse_command_response(report_bytes: bytearray) -> Tuple[Any, Any]: +def _parse_command_response(report_bytes: bytearray) -> tuple[Any, Any]: # CMD response report: # 0 Report ID = 0xF1 # 1 Sequence number @@ -336,7 +336,7 @@ def _insert_command_request_report( command: int, buffer: bytearray, next_sequence_number: int, - command_params: Optional[List[int]] = None, + command_params: Optional[list[int]] = None, ) -> None: if command_params and len(command_params) > 9: raise AttributeError( @@ -362,7 +362,7 @@ def _report_length(report_id: int) -> int: return _REPORT_LENGTHS[report_id] -def _separate_batch(packet: Packet, report_slices: List[Any]) -> None: +def _separate_batch(packet: Packet, report_slices: list[Any]) -> None: # get first report id, loop up its report length # read that many bytes, parse them next_byte_index = 0 @@ -401,10 +401,10 @@ def __str__(self) -> str: channels[self.channel_number], self.channel_number, ) - if self.channel_number in [ + if self.channel_number in { _BNO_CHANNEL_CONTROL, _BNO_CHANNEL_INPUT_SENSOR_REPORTS, - ]: + }: if self.report_id in reports: outstr += "DBG::\t\t \tReport Type: %s (0x%x)\n" % ( reports[self.report_id], @@ -484,11 +484,11 @@ def __init__(self, reset: Optional[DigitalInOut] = None, debug: bool = False) -> self._dbg("********** __init__ *************") self._data_buffer: bytearray = bytearray(DATA_BUFFER_SIZE) self._command_buffer: bytearray = bytearray(12) - self._packet_slices: List[Any] = [] + self._packet_slices: list[Any] = [] # TODO: this is wrong there should be one per channel per direction - self._sequence_number: List[int] = [0, 0, 0, 0, 0, 0] - self._two_ended_sequence_numbers: Dict[int, int] = {} + self._sequence_number: list[int] = [0, 0, 0, 0, 0, 0] + self._two_ended_sequence_numbers: dict[int, int] = {} self._dcd_saved_at: float = -1 self._me_calibration_started_at: float = -1.0 self._calibration_complete = False @@ -497,7 +497,7 @@ def __init__(self, reset: Optional[DigitalInOut] = None, debug: bool = False) -> self._init_complete = False self._id_read = False # for saving the most recent reading when decoding several packets - self._readings: Dict[int, Any] = {} + self._readings: dict[int, Any] = {} self.initialize() def initialize(self) -> None: @@ -514,7 +514,7 @@ def initialize(self) -> None: raise RuntimeError("Could not read ID") @property - def magnetic(self) -> Optional[Tuple[float, float, float]]: + def magnetic(self) -> Optional[tuple[float, float, float]]: """A tuple of the current magnetic field measurements on the X, Y, and Z axes""" self._process_available_packets() # decorator? try: @@ -523,7 +523,7 @@ def magnetic(self) -> Optional[Tuple[float, float, float]]: raise RuntimeError("No magfield report found, is it enabled?") from None @property - def quaternion(self) -> Optional[Tuple[float, float, float, float]]: + def quaternion(self) -> Optional[tuple[float, float, float, float]]: """A quaternion representing the current rotation vector""" self._process_available_packets() try: @@ -532,7 +532,7 @@ def quaternion(self) -> Optional[Tuple[float, float, float, float]]: raise RuntimeError("No quaternion report found, is it enabled?") from None @property - def geomagnetic_quaternion(self) -> Optional[Tuple[float, float, float, float]]: + def geomagnetic_quaternion(self) -> Optional[tuple[float, float, float, float]]: """A quaternion representing the current geomagnetic rotation vector""" self._process_available_packets() try: @@ -541,7 +541,7 @@ def geomagnetic_quaternion(self) -> Optional[Tuple[float, float, float, float]]: raise RuntimeError("No geomag quaternion report found, is it enabled?") from None @property - def game_quaternion(self) -> Optional[Tuple[float, float, float, float]]: + def game_quaternion(self) -> Optional[tuple[float, float, float, float]]: """A quaternion representing the current rotation vector expressed as a quaternion with no specific reference for heading, while roll and pitch are referenced against gravity. To prevent sudden jumps in heading due to corrections, the `game_quaternion` property is not @@ -562,7 +562,7 @@ def steps(self) -> Optional[int]: raise RuntimeError("No steps report found, is it enabled?") from None @property - def linear_acceleration(self) -> Optional[Tuple[float, float, float]]: + def linear_acceleration(self) -> Optional[tuple[float, float, float]]: """A tuple representing the current linear acceleration values on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() @@ -572,7 +572,7 @@ def linear_acceleration(self) -> Optional[Tuple[float, float, float]]: raise RuntimeError("No lin. accel report found, is it enabled?") from None @property - def acceleration(self) -> Optional[Tuple[float, float, float]]: + def acceleration(self) -> Optional[tuple[float, float, float]]: """A tuple representing the acceleration measurements on the X, Y, and Z axes in meters per second squared""" self._process_available_packets() @@ -582,7 +582,7 @@ def acceleration(self) -> Optional[Tuple[float, float, float]]: raise RuntimeError("No accel report found, is it enabled?") from None @property - def gravity(self) -> Optional[Tuple[float, float, float]]: + def gravity(self) -> Optional[tuple[float, float, float]]: """A tuple representing the gravity vector in the X, Y, and Z components axes in meters per second squared""" self._process_available_packets() @@ -592,7 +592,7 @@ def gravity(self) -> Optional[Tuple[float, float, float]]: raise RuntimeError("No gravity report found, is it enabled?") from None @property - def gyro(self) -> Optional[Tuple[float, float, float]]: + def gyro(self) -> Optional[tuple[float, float, float]]: """A tuple representing Gyro's rotation measurements on the X, Y, and Z axes in radians per second""" self._process_available_packets() @@ -663,7 +663,7 @@ def activity_classification(self) -> Optional[dict]: raise RuntimeError("No activity classification report found, is it enabled?") from None @property - def raw_acceleration(self) -> Optional[Tuple[int, int, int]]: + def raw_acceleration(self) -> Optional[tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the accelerometer registers""" self._process_available_packets() try: @@ -673,7 +673,7 @@ def raw_acceleration(self) -> Optional[Tuple[int, int, int]]: raise RuntimeError("No raw acceleration report found, is it enabled?") from None @property - def raw_gyro(self) -> Optional[Tuple[int, int, int]]: + def raw_gyro(self) -> Optional[tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the gyro registers""" self._process_available_packets() try: @@ -683,7 +683,7 @@ def raw_gyro(self) -> Optional[Tuple[int, int, int]]: raise RuntimeError("No raw gyro report found, is it enabled?") from None @property - def raw_magnetic(self) -> Optional[Tuple[int, int, int]]: + def raw_magnetic(self) -> Optional[tuple[int, int, int]]: """Returns the sensor's raw, unscaled value from the magnetometer registers""" self._process_available_packets() try: @@ -728,7 +728,7 @@ def calibration_status(self) -> int: ) return self._magnetometer_accuracy - def _send_me_command(self, subcommand_params: Optional[List[int]]) -> None: + def _send_me_command(self, subcommand_params: Optional[list[int]]) -> None: start_time = time.monotonic() local_buffer = self._command_buffer _insert_command_request_report( @@ -800,10 +800,10 @@ def _wait_for_packet_type( return new_packet else: return new_packet - if new_packet.channel_number not in ( + if new_packet.channel_number not in { BNO_CHANNEL_EXE, BNO_CHANNEL_SHTP_COMMAND, - ): + }: self._dbg("passing packet to handler for de-slicing") self._handle_packet(new_packet) @@ -1060,10 +1060,10 @@ def soft_reset(self) -> None: self._dbg("OK!") # all is good! - def _send_packet(self, channel: int, data: bytearray) -> Optional[int]: + def _send_packet(self, channel: int, data: bytearray) -> Optional[int]: # noqa: PLR6301 raise RuntimeError("Not implemented") - def _read_packet(self) -> Optional[Packet]: + def _read_packet(self) -> Optional[Packet]: # noqa: PLR6301 raise RuntimeError("Not implemented") def _increment_report_seq(self, report_id: int) -> None: diff --git a/ruff.toml b/ruff.toml index 36332ff..e4564d3 100644 --- a/ruff.toml +++ b/ruff.toml @@ -99,6 +99,8 @@ ignore = [ "PLR0904", # too-many-public-methods "PLR0912", # too-many-branches "PLR0916", # too-many-boolean-expressions + "UP007", # use x | y for type + "UP031", # use format instead of percent ] [format] From a0a217e7ac0a211f4e05dc3c501039f5fe03d00a Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 13 May 2025 15:23:37 -0500 Subject: [PATCH 099/106] remove pylint disables --- README.rst | 2 +- adafruit_bno08x/spi.py | 2 +- adafruit_bno08x/uart.py | 2 -- examples/bno08x_calibration.py | 4 ++-- examples/bno08x_more_reports.py | 14 +++++++------- examples/bno08x_simpletest.py | 8 ++++---- examples/bno08x_simpletest_spi.py | 2 +- examples/bno08x_simpletest_uart.py | 18 +++++++++--------- 8 files changed, 25 insertions(+), 27 deletions(-) diff --git a/README.rst b/README.rst index e338e3a..dcb42c7 100644 --- a/README.rst +++ b/README.rst @@ -71,7 +71,7 @@ Usage Example bno.enable_feature(BNO_REPORT_ACCELEROMETER) while True: - accel_x, accel_y, accel_z = bno.acceleration # pylint:disable=no-member + accel_x, accel_y, accel_z = bno.acceleration print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) Documentation diff --git a/adafruit_bno08x/spi.py b/adafruit_bno08x/spi.py index dd6ed70..9e57416 100644 --- a/adafruit_bno08x/spi.py +++ b/adafruit_bno08x/spi.py @@ -32,7 +32,7 @@ class BNO08X_SPI(BNO08X): # """ - def __init__(self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False): # pylint:disable=too-many-arguments + def __init__(self, spi_bus, cspin, intpin, resetpin, baudrate=1000000, debug=False): self._spi = spi_device.SPIDevice(spi_bus, cspin, baudrate=baudrate, polarity=1, phase=1) self._int = intpin super().__init__(resetpin, debug) diff --git a/adafruit_bno08x/uart.py b/adafruit_bno08x/uart.py index 3cd10c4..706d62b 100644 --- a/adafruit_bno08x/uart.py +++ b/adafruit_bno08x/uart.py @@ -37,7 +37,6 @@ def _send_packet(self, channel, data): byte_buffer = bytearray(1) # request available size - # pylint:disable=pointless-string-statement """ self._uart.write(b'\x7e') # start byte time.sleep(0.001) @@ -48,7 +47,6 @@ def _send_packet(self, channel, data): if avail[0] != 0x7e and avail[1] != 0x01 and avail[4] != 0x7e: raise RuntimeError("Couldn't get available buffer size") """ - # pylint:enable=pointless-string-statement pack_into(" Date: Tue, 13 May 2025 15:25:17 -0500 Subject: [PATCH 100/106] remove unused type imports --- adafruit_bno08x/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 4cf9f93..fb909f7 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -41,7 +41,7 @@ # For IDE type recognition try: - from typing import Any, Dict, List, Optional, Tuple, Union + from typing import Any, Optional from digitalio import DigitalInOut except ImportError: From 929e8a3d9aa27a6786e360f9f1c64aff1c1a418b Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 13 May 2025 15:29:03 -0500 Subject: [PATCH 101/106] fix copy errors --- examples/bno08x_more_reports.py | 14 +++++++------- examples/bno08x_simpletest.py | 8 ++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/examples/bno08x_more_reports.py b/examples/bno08x_more_reports.py index 2095e2b..3624887 100644 --- a/examples/bno08x_more_reports.py +++ b/examples/bno08x_more_reports.py @@ -31,17 +31,17 @@ time.sleep(0.1) print("Acceleration:") - accel_x, accel_y, accel_z = bno.accelerationdict + accel_x, accel_y, accel_z = bno.acceleration print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) print("") print("Gyro:") - gyro_x, gyro_y, gyro_z = bno.gyrodict + gyro_x, gyro_y, gyro_z = bno.gyro print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) print("") print("Magnetometer:") - mag_x, mag_y, mag_z = bno.magneticdict + mag_x, mag_y, mag_z = bno.magnetic print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) print("") @@ -50,12 +50,12 @@ linear_accel_x, linear_accel_y, linear_accel_z, - ) = bno.linear_accelerationdict + ) = bno.linear_acceleration print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (linear_accel_x, linear_accel_y, linear_accel_z)) print("") print("Rotation Vector Quaternion:") - quat_i, quat_j, quat_k, quat_real = bno.quaterniondict + quat_i, quat_j, quat_k, quat_real = bno.quaternion print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)) print("") @@ -65,7 +65,7 @@ geo_quat_j, geo_quat_k, geo_quat_real, - ) = bno.geomagnetic_quaterniondict + ) = bno.geomagnetic_quaternion print( "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (geo_quat_i, geo_quat_j, geo_quat_k, geo_quat_real) @@ -78,7 +78,7 @@ game_quat_j, game_quat_k, game_quat_real, - ) = bno.game_quaterniondict + ) = bno.game_quaternion print( "I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (game_quat_i, game_quat_j, game_quat_k, game_quat_real) diff --git a/examples/bno08x_simpletest.py b/examples/bno08x_simpletest.py index 72bfa65..4335994 100644 --- a/examples/bno08x_simpletest.py +++ b/examples/bno08x_simpletest.py @@ -25,21 +25,21 @@ while True: time.sleep(0.5) print("Acceleration:") - accel_x, accel_y, accel_z = bno.accelerationdict + accel_x, accel_y, accel_z = bno.acceleration print("X: %0.6f Y: %0.6f Z: %0.6f m/s^2" % (accel_x, accel_y, accel_z)) print("") print("Gyro:") - gyro_x, gyro_y, gyro_z = bno.gyrodict + gyro_x, gyro_y, gyro_z = bno.gyro print("X: %0.6f Y: %0.6f Z: %0.6f rads/s" % (gyro_x, gyro_y, gyro_z)) print("") print("Magnetometer:") - mag_x, mag_y, mag_z = bno.magneticdict + mag_x, mag_y, mag_z = bno.magnetic print("X: %0.6f Y: %0.6f Z: %0.6f uT" % (mag_x, mag_y, mag_z)) print("") print("Rotation Vector Quaternion:") - quat_i, quat_j, quat_k, quat_real = bno.quaterniondict + quat_i, quat_j, quat_k, quat_real = bno.quaternion print("I: %0.6f J: %0.6f K: %0.6f Real: %0.6f" % (quat_i, quat_j, quat_k, quat_real)) print("") From 2722274c7bf471f47a0620e92792d141aba52f6b Mon Sep 17 00:00:00 2001 From: foamyguy Date: Wed, 4 Jun 2025 10:00:20 -0500 Subject: [PATCH 102/106] update rtd.yml file Signed-off-by: foamyguy --- .readthedocs.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 88bca9f..255dafd 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -12,7 +12,7 @@ sphinx: configuration: docs/conf.py build: - os: ubuntu-20.04 + os: ubuntu-lts-latest tools: python: "3" From 556721e2e5d71be776c3afa891f995554ca9671e Mon Sep 17 00:00:00 2001 From: Ren Date: Thu, 3 Jul 2025 18:42:37 -0400 Subject: [PATCH 103/106] Option set report interval manually --- adafruit_bno08x/__init__.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index fb909f7..88d4f26 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -933,7 +933,7 @@ def _process_report(self, report_id: int, report_bytes: bytearray) -> None: @staticmethod def _get_feature_enable_report( feature_id: int, - report_interval: int = _DEFAULT_REPORT_INTERVAL, + report_interval: int, sensor_specific_config: int = 0, ) -> bytearray: set_feature_report = bytearray(17) @@ -947,16 +947,20 @@ def _get_feature_enable_report( # TODO: add docs for available features # TODO2: I think this should call an fn that imports all the bits for the given feature # so we're not carrying around stuff for extra features - def enable_feature(self, feature_id: int) -> None: + def enable_feature( + self, + feature_id: int, + report_interval: int = _DEFAULT_REPORT_INTERVAL, + ) -> None: """Used to enable a given feature of the BNO08x""" self._dbg("\n********** Enabling feature id:", feature_id, "**********") if feature_id == BNO_REPORT_ACTIVITY_CLASSIFIER: set_feature_report = self._get_feature_enable_report( - feature_id, sensor_specific_config=_ENABLED_ACTIVITIES + feature_id, report_interval, _ENABLED_ACTIVITIES ) else: - set_feature_report = self._get_feature_enable_report(feature_id) + set_feature_report = self._get_feature_enable_report(feature_id, report_interval) feature_dependency = _RAW_REPORTS.get(feature_id, None) # if the feature was enabled it will have a key in the readings dict From 0ec3b32df63043203d78b8634ab1ded4b429b2cb Mon Sep 17 00:00:00 2001 From: Ren Date: Thu, 3 Jul 2025 18:45:27 -0400 Subject: [PATCH 104/106] Fix readme to apply the change --- README.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index dcb42c7..ba85739 100644 --- a/README.rst +++ b/README.rst @@ -66,9 +66,11 @@ Usage Example from adafruit_bno08x.i2c import BNO08X_I2C from adafruit_bno08x import BNO_REPORT_ACCELEROMETER + REPORT_INTERVAL = const(100000) # 100 Hz + i2c = busio.I2C(board.SCL, board.SDA) bno = BNO08X_I2C(i2c) - bno.enable_feature(BNO_REPORT_ACCELEROMETER) + bno.enable_feature(BNO_REPORT_ACCELEROMETER, REPORT_INTERVAL) while True: accel_x, accel_y, accel_z = bno.acceleration From 865c2220c8a98353b215babcd2c1b679b4fab058 Mon Sep 17 00:00:00 2001 From: Ren Date: Thu, 3 Jul 2025 19:04:08 -0400 Subject: [PATCH 105/106] Fix white space issue --- README.rst | 1 - adafruit_bno08x/__init__.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/README.rst b/README.rst index ba85739..847d7e8 100644 --- a/README.rst +++ b/README.rst @@ -67,7 +67,6 @@ Usage Example from adafruit_bno08x import BNO_REPORT_ACCELEROMETER REPORT_INTERVAL = const(100000) # 100 Hz - i2c = busio.I2C(board.SCL, board.SDA) bno = BNO08X_I2C(i2c) bno.enable_feature(BNO_REPORT_ACCELEROMETER, REPORT_INTERVAL) diff --git a/adafruit_bno08x/__init__.py b/adafruit_bno08x/__init__.py index 88d4f26..77ed577 100644 --- a/adafruit_bno08x/__init__.py +++ b/adafruit_bno08x/__init__.py @@ -948,7 +948,7 @@ def _get_feature_enable_report( # TODO2: I think this should call an fn that imports all the bits for the given feature # so we're not carrying around stuff for extra features def enable_feature( - self, + self, feature_id: int, report_interval: int = _DEFAULT_REPORT_INTERVAL, ) -> None: From 1ed529213c61b0e035e31b7f7580d6f73a4e78ad Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 10 Oct 2025 16:18:40 -0500 Subject: [PATCH 106/106] remove deprecated ruff rule, workaround RTD theme property inline issue. Signed-off-by: foamyguy --- docs/_static/custom.css | 8 ++++++++ docs/conf.py | 3 +++ ruff.toml | 1 - 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 docs/_static/custom.css diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..d60cf4b --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,8 @@ +/* SPDX-FileCopyrightText: 2025 Sam Blenny + * SPDX-License-Identifier: MIT + */ + +/* Monkey patch the rtd theme to prevent horizontal stacking of short items + * see https://github.com/readthedocs/sphinx_rtd_theme/issues/1301 + */ +.py.property{display: block !important;} diff --git a/docs/conf.py b/docs/conf.py index a3fc27e..2a31881 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -112,6 +112,9 @@ # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] +# Include extra css to work around rtd theme glitches +html_css_files = ["custom.css"] + # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. diff --git a/ruff.toml b/ruff.toml index e4564d3..b4460e1 100644 --- a/ruff.toml +++ b/ruff.toml @@ -17,7 +17,6 @@ extend-select = [ "PLC2401", # non-ascii-name "PLC2801", # unnecessary-dunder-call "PLC3002", # unnecessary-direct-lambda-call - "E999", # syntax-error "PLE0101", # return-in-init "F706", # return-outside-function "F704", # yield-outside-function