Skip to content

Commit 582426f

Browse files
authored
Merge pull request #36 from tcfranks/main
Add missing type annotations
2 parents e41e501 + 4836a59 commit 582426f

File tree

1 file changed

+49
-31
lines changed

1 file changed

+49
-31
lines changed

adafruit_vl53l0x.py

Lines changed: 49 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,13 @@
3434
from adafruit_bus_device import i2c_device
3535
from micropython import const
3636

37+
try:
38+
from typing import Optional, Tuple, Type
39+
from types import TracebackType
40+
from busio import I2C
41+
except ImportError:
42+
pass
43+
3744
__version__ = "0.0.0+auto.0"
3845
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_VL53L0X.git"
3946

@@ -100,12 +107,12 @@
100107
_VCSEL_PERIOD_FINAL_RANGE = const(1)
101108

102109

103-
def _decode_timeout(val):
110+
def _decode_timeout(val: int) -> float:
104111
# format: "(LSByte * 2^MSByte) + 1"
105112
return float(val & 0xFF) * math.pow(2.0, ((val & 0xFF00) >> 8)) + 1
106113

107114

108-
def _encode_timeout(timeout_mclks):
115+
def _encode_timeout(timeout_mclks: float) -> int:
109116
# format: "(LSByte * 2^MSByte) + 1"
110117
timeout_mclks = int(timeout_mclks) & 0xFFFF
111118
ls_byte = 0
@@ -119,12 +126,16 @@ def _encode_timeout(timeout_mclks):
119126
return 0
120127

121128

122-
def _timeout_mclks_to_microseconds(timeout_period_mclks, vcsel_period_pclks):
129+
def _timeout_mclks_to_microseconds(
130+
timeout_period_mclks: int, vcsel_period_pclks: int
131+
) -> int:
123132
macro_period_ns = ((2304 * (vcsel_period_pclks) * 1655) + 500) // 1000
124133
return ((timeout_period_mclks * macro_period_ns) + (macro_period_ns // 2)) // 1000
125134

126135

127-
def _timeout_microseconds_to_mclks(timeout_period_us, vcsel_period_pclks):
136+
def _timeout_microseconds_to_mclks(
137+
timeout_period_us: int, vcsel_period_pclks: int
138+
) -> int:
128139
macro_period_ns = ((2304 * (vcsel_period_pclks) * 1655) + 500) // 1000
129140
return ((timeout_period_us * 1000) + (macro_period_ns // 2)) // macro_period_ns
130141

@@ -140,7 +151,7 @@ class VL53L0X:
140151
# Is VL53L0X is currently continuous mode? (Needed by `range` property)
141152
_continuous_mode = False
142153

143-
def __init__(self, i2c, address=41, io_timeout_s=0):
154+
def __init__(self, i2c: I2C, address: int = 41, io_timeout_s: float = 0) -> None:
144155
# pylint: disable=too-many-statements
145156
self._i2c = i2c
146157
self._device = i2c_device.I2CDevice(i2c, address)
@@ -304,38 +315,38 @@ def __init__(self, i2c, address=41, io_timeout_s=0):
304315
# "restore the previous Sequence Config"
305316
self._write_u8(_SYSTEM_SEQUENCE_CONFIG, 0xE8)
306317

307-
def _read_u8(self, address):
318+
def _read_u8(self, address: int) -> int:
308319
# Read an 8-bit unsigned value from the specified 8-bit address.
309320
with self._device:
310321
self._BUFFER[0] = address & 0xFF
311322
self._device.write(self._BUFFER, end=1)
312323
self._device.readinto(self._BUFFER, end=1)
313324
return self._BUFFER[0]
314325

315-
def _read_u16(self, address):
326+
def _read_u16(self, address: int) -> int:
316327
# Read a 16-bit BE unsigned value from the specified 8-bit address.
317328
with self._device:
318329
self._BUFFER[0] = address & 0xFF
319330
self._device.write(self._BUFFER, end=1)
320331
self._device.readinto(self._BUFFER)
321332
return (self._BUFFER[0] << 8) | self._BUFFER[1]
322333

323-
def _write_u8(self, address, val):
334+
def _write_u8(self, address: int, val: int) -> None:
324335
# Write an 8-bit unsigned value to the specified 8-bit address.
325336
with self._device:
326337
self._BUFFER[0] = address & 0xFF
327338
self._BUFFER[1] = val & 0xFF
328339
self._device.write(self._BUFFER, end=2)
329340

330-
def _write_u16(self, address, val):
341+
def _write_u16(self, address: int, val: int) -> None:
331342
# Write a 16-bit BE unsigned value to the specified 8-bit address.
332343
with self._device:
333344
self._BUFFER[0] = address & 0xFF
334345
self._BUFFER[1] = (val >> 8) & 0xFF
335346
self._BUFFER[2] = val & 0xFF
336347
self._device.write(self._BUFFER)
337348

338-
def _get_spad_info(self):
349+
def _get_spad_info(self) -> Tuple[int, bool]:
339350
# Get reference SPAD count and type, returned as a 2-tuple of
340351
# count and boolean is_aperture. Based on code from:
341352
# https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
@@ -368,7 +379,7 @@ def _get_spad_info(self):
368379
self._write_u8(pair[0], pair[1])
369380
return (count, is_aperture)
370381

371-
def _perform_single_ref_calibration(self, vhv_init_byte):
382+
def _perform_single_ref_calibration(self, vhv_init_byte: int) -> None:
372383
# based on VL53L0X_perform_single_ref_calibration() from ST API.
373384
self._write_u8(_SYSRANGE_START, 0x01 | vhv_init_byte & 0xFF)
374385
start = time.monotonic()
@@ -381,7 +392,7 @@ def _perform_single_ref_calibration(self, vhv_init_byte):
381392
self._write_u8(_SYSTEM_INTERRUPT_CLEAR, 0x01)
382393
self._write_u8(_SYSRANGE_START, 0x00)
383394

384-
def _get_vcsel_pulse_period(self, vcsel_period_type):
395+
def _get_vcsel_pulse_period(self, vcsel_period_type: int) -> int:
385396
# pylint: disable=no-else-return
386397
# Disable should be removed when refactor can be tested
387398
if vcsel_period_type == _VCSEL_PERIOD_PRE_RANGE:
@@ -392,7 +403,7 @@ def _get_vcsel_pulse_period(self, vcsel_period_type):
392403
return (((val) + 1) & 0xFF) << 1
393404
return 255
394405

395-
def _get_sequence_step_enables(self):
406+
def _get_sequence_step_enables(self) -> Tuple[bool, bool, bool, bool, bool]:
396407
# based on VL53L0X_GetSequenceStepEnables() from ST API
397408
sequence_config = self._read_u8(_SYSTEM_SEQUENCE_CONFIG)
398409
tcc = (sequence_config >> 4) & 0x1 > 0
@@ -402,7 +413,9 @@ def _get_sequence_step_enables(self):
402413
final_range = (sequence_config >> 7) & 0x1 > 0
403414
return (tcc, dss, msrc, pre_range, final_range)
404415

405-
def _get_sequence_step_timeouts(self, pre_range):
416+
def _get_sequence_step_timeouts(
417+
self, pre_range: int
418+
) -> Tuple[int, int, int, int, float]:
406419
# based on get_sequence_step_timeout() from ST API but modified by
407420
# pololu here:
408421
# https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
@@ -439,21 +452,21 @@ def _get_sequence_step_timeouts(self, pre_range):
439452
)
440453

441454
@property
442-
def signal_rate_limit(self):
455+
def signal_rate_limit(self) -> float:
443456
"""The signal rate limit in mega counts per second."""
444457
val = self._read_u16(_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT)
445458
# Return value converted from 16-bit 9.7 fixed point to float.
446459
return val / (1 << 7)
447460

448461
@signal_rate_limit.setter
449-
def signal_rate_limit(self, val):
462+
def signal_rate_limit(self, val: float) -> None:
450463
assert 0.0 <= val <= 511.99
451464
# Convert to 16-bit 9.7 fixed point value from a float.
452465
val = int(val * (1 << 7))
453466
self._write_u16(_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, val)
454467

455468
@property
456-
def measurement_timing_budget(self):
469+
def measurement_timing_budget(self) -> int:
457470
"""The measurement timing budget in microseconds."""
458471
budget_us = 1910 + 960 # Start overhead + end overhead.
459472
tcc, dss, msrc, pre_range, final_range = self._get_sequence_step_enables()
@@ -473,7 +486,7 @@ def measurement_timing_budget(self):
473486
return budget_us
474487

475488
@measurement_timing_budget.setter
476-
def measurement_timing_budget(self, budget_us):
489+
def measurement_timing_budget(self, budget_us: int) -> None:
477490
# pylint: disable=too-many-locals
478491
assert budget_us >= 20000
479492
used_budget_us = 1320 + 960 # Start (diff from get) + end overhead
@@ -494,7 +507,7 @@ def measurement_timing_budget(self, budget_us):
494507
# "Note that the final range timeout is determined by the timing
495508
# budget and the sum of all other timeouts within the sequence.
496509
# If there is no room for the final range timeout, then an error
497-
# will be set. Otherwise the remaining time will be applied to
510+
# will be set. Otherwise, the remaining time will be applied to
498511
# the final range."
499512
if used_budget_us > budget_us:
500513
raise ValueError("Requested timeout too big.")
@@ -511,14 +524,14 @@ def measurement_timing_budget(self, budget_us):
511524
self._measurement_timing_budget_us = budget_us
512525

513526
@property
514-
def distance(self):
527+
def distance(self) -> float:
515528
"""Perform a single reading of the range for an object in front of
516529
the sensor and return the distance in centimeters.
517530
"""
518531
return self.range / 10
519532

520533
@property
521-
def range(self):
534+
def range(self) -> int:
522535
"""Perform a single (or continuous if `start_continuous` called)
523536
reading of the range for an object in front of the sensor and
524537
return the distance in millimeters.
@@ -530,15 +543,15 @@ def range(self):
530543
return self.read_range()
531544

532545
@property
533-
def data_ready(self):
546+
def data_ready(self) -> bool:
534547
"""Check if data is available from the sensor. If true a call to .range
535548
will return quickly. If false, calls to .range will wait for the sensor's
536549
next reading to be available."""
537550
if not self._data_ready:
538551
self._data_ready = self._read_u8(_RESULT_INTERRUPT_STATUS) & 0x07 != 0
539552
return self._data_ready
540553

541-
def do_range_measurement(self):
554+
def do_range_measurement(self) -> None:
542555
"""Perform a single reading of the range for an object in front of the
543556
sensor, but without return the distance.
544557
"""
@@ -563,7 +576,7 @@ def do_range_measurement(self):
563576
):
564577
raise RuntimeError("Timeout waiting for VL53L0X!")
565578

566-
def read_range(self):
579+
def read_range(self) -> int:
567580
"""Return a range reading in millimeters.
568581
Note: Avoid calling this directly. If you do single mode, you need
569582
to call `do_range_measurement` first. Or your program will stuck or
@@ -586,24 +599,29 @@ def read_range(self):
586599
return range_mm
587600

588601
@property
589-
def is_continuous_mode(self):
602+
def is_continuous_mode(self) -> bool:
590603
"""Is the sensor currently in continuous mode?"""
591604
return self._continuous_mode
592605

593-
def continuous_mode(self):
606+
def continuous_mode(self) -> "VL53L0X":
594607
"""Activate the continuous mode manager"""
595608
return self
596609

597-
def __enter__(self):
610+
def __enter__(self) -> "VL53L0X":
598611
"""For continuous mode manager, called when used on `with` keyword"""
599612
self.start_continuous()
600613
return self
601614

602-
def __exit__(self, exc_type, exc_value, traceback):
615+
def __exit__(
616+
self,
617+
exc_type: Optional[Type[BaseException]],
618+
exc_value: Optional[BaseException],
619+
traceback: Optional[TracebackType],
620+
) -> None:
603621
"""For continuous mode manager, called at the end of `with` scope"""
604622
self.stop_continuous()
605623

606-
def start_continuous(self):
624+
def start_continuous(self) -> None:
607625
"""Perform a continuous reading of the range for an object in front of
608626
the sensor.
609627
"""
@@ -629,7 +647,7 @@ def start_continuous(self):
629647
raise RuntimeError("Timeout waiting for VL53L0X!")
630648
self._continuous_mode = True
631649

632-
def stop_continuous(self):
650+
def stop_continuous(self) -> None:
633651
"""Stop continuous readings."""
634652
# Adapted from stopContinuous in pololu code at:
635653
# https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
@@ -647,7 +665,7 @@ def stop_continuous(self):
647665
# restore the sensor to single ranging mode
648666
self.do_range_measurement()
649667

650-
def set_address(self, new_address):
668+
def set_address(self, new_address: int) -> None:
651669
"""Set a new I2C address to the instantaited object. This is only called when using
652670
multiple VL53L0X sensors on the same I2C bus (SDA & SCL pins). See also the
653671
`example <examples.html#multiple-vl53l0x-on-same-i2c-bus>`_ for proper usage.

0 commit comments

Comments
 (0)