Skip to content

Commit 9a67533

Browse files
committed
Small improvements to lib
- Fix mkdocs warnings - Fix Python SyntaxWarning - Add static exceptions for colour sensor - Log warning when colour chip not present
1 parent afb680e commit 9a67533

16 files changed

+56
-24
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Contributors
6060
* `Serge Schneider`_
6161
* `Dave Jones`_
6262
* `Tyler Laws`_
63+
* `George Boukeas`_
6364

6465
Open Source
6566
===========

docs/api.md

+9-3
Original file line numberDiff line numberDiff line change
@@ -819,7 +819,7 @@ Note that, in the current implementation, the four values accessed through the `
819819

820820
In sensors, the term "gain" can be understood as being synonymous to _sensitivity_. A higher gain setting means the output values will be greater for the same input.
821821

822-
There are four possible gain values for the colour sensor: `1`, `4`, `16` and `60`, with the default value being `1`. You can get or set the sensor gain through the `gain` property of the `ColourSensor` object. An attempt to set the gain to a value that is not valid will result in a `ValueError` exception being raised.
822+
There are four possible gain values for the colour sensor: `1`, `4`, `16` and `60`, with the default value being `1`. You can get or set the sensor gain through the `gain` property of the `ColourSensor` object. An attempt to set the gain to a value that is not valid will result in an `InvalidGainError` exception being raised.
823823

824824
```python
825825
from sense_hat import SenseHAT
@@ -846,7 +846,7 @@ When there is very little ambient light and the RGBC values are low, it makes se
846846

847847
You can specify the number of _integration cycles_ required to generate a new set of sensor readings. Each integration cycle is 2.4 milliseconds long, so the number of integration cycles determines the _minimum_ amount of time required between consecutive readings.
848848

849-
You can set the number of integration cycles to any integer between `1` and `256`, through the `integration_cycles` property of the `ColourSensor` object. The default value is `1`. An attempt to set the number of integration cycles to a value that is not valid will result in a `ValueError` or `TypeError` exception being raised.
849+
You can set the number of integration cycles to any integer between `1` and `256`, through the `integration_cycles` property of the `ColourSensor` object. The default value is `1`. An attempt to set the number of integration cycles to a value that is not valid will result in a `InvalidIntegrationCyclesError` or `TypeError` exception being raised.
850850

851851
```python
852852
from sense_hat import SenseHAT
@@ -895,4 +895,10 @@ print(f"Maximum raw sensor reading: {sense.colour.max_raw}")
895895
sleep(sense.colour.integration_time + 0.1) # try omitting this
896896
print(f"Current raw sensor readings: {sense.colour.colour_raw}")
897897
print(f"Scaled values: {sense.colour.colour}")
898-
```
898+
```
899+
900+
## Exceptions
901+
902+
Custom Sense HAT exceptions are statically defined in the `sense_hat.exceptions` module.
903+
The exceptions relate to problems encountered while initialising the colour chip or due to setting invalid parameters.
904+
Each exception includes a message describing the issue encountered, and is subclassed from the base class `SenseHatException`.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

mkdocs.yml

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ repo_url: https://github.com/RPi-Distro/python-sense-hat
55
site_description: Python module to control the Raspberry Pi Sense HAT used in the Astro Pi mission
66
site_author: David Honess
77
site_dir: pythonhosted
8-
google_analytics: ['UA-46270871-5', 'pythonhosted.org/sense-hat']
9-
pages:
8+
#google_analytics: ['UA-46270871-5', 'pythonhosted.org/sense-hat']
9+
nav:
1010
- 'Home': 'index.md'
1111
- 'API Reference': 'api.md'
12+
- 'Examples': 'examples/README.md'
1213
- 'Changelog': 'changelog.md'

sense_hat/colour.py

+13-16
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
"""
55

66
from time import sleep
7-
8-
_error_str = "Failed to initialise TCS34725 colour sensor."
7+
from .exceptions import ColourSensorInitialisationError, InvalidGainError, \
8+
InvalidIntegrationCyclesError
99

1010

1111
class HardwareInterface:
@@ -84,31 +84,31 @@ def get_raw(self):
8484

8585
def get_red(self):
8686
"""
87-
Return a the raw value of the R (red) channel.
87+
Return the raw value of the R (red) channel.
8888
The maximum for this raw value depends on the number of
8989
integration cycles and can be computed using `max_value`.
9090
"""
9191
raise NotImplementedError
9292

9393
def get_green(self):
9494
"""
95-
Return a the raw value of the G (green) channel.
95+
Return the raw value of the G (green) channel.
9696
The maximum for this raw value depends on the number of
9797
integration cycles and can be computed using `max_value`.
9898
"""
9999
raise NotImplementedError
100100

101101
def get_blue(self):
102102
"""
103-
Return a the raw value of the B (blue) channel.
103+
Return the raw value of the B (blue) channel.
104104
The maximum for this raw value depends on the number of
105105
integration cycles and can be computed using `max_value`.
106106
"""
107107
raise NotImplementedError
108108

109109
def get_clear(self):
110110
"""
111-
Return a the raw value of the C (clear light) channel.
111+
Return the raw value of the C (clear light) channel.
112112
The maximum for this raw value depends on the number of
113113
integration cycles and can be computed using `max_value`.
114114
"""
@@ -176,19 +176,16 @@ def __init__(self):
176176
try:
177177
self.bus = smbus.SMBus(self.BUS)
178178
except Exception as e:
179-
explanation = " (I2C is not enabled)" if not self.i2c_enabled() else ""
180-
raise RuntimeError(f'{_error_str}{explanation}') from e
181-
179+
explanation = "(I2C is not enabled)" if not self.i2c_enabled() else ""
180+
raise ColourSensorInitialisationError(explanation=explanation) from e
182181
try:
183182
id = self._read(self.ID)
184183
except Exception as e:
185-
explanation = " (sensor not present)"
186-
raise RuntimeError(f'{_error_str}{explanation}') from e
187-
184+
explanation = "(sensor not present)"
185+
raise ColourSensorInitialisationError(explanation=explanation) from e
188186
if id != 0x44:
189187
explanation = f" (different device id detected: {id})"
190-
raise RuntimeError(f'{_error_str}{explanation}')
191-
188+
raise ColourSensorInitialisationError(explanation=explanation) from e
192189
@staticmethod
193190
def i2c_enabled():
194191
"""Returns True if I2C is enabled or False otherwise."""
@@ -314,7 +311,7 @@ def gain(self, gain):
314311
if gain in self.interface.GAIN_VALUES:
315312
self.interface.set_gain(gain)
316313
else:
317-
raise ValueError(f'Cannot set gain to {gain}. Values: {self.interface.GAIN_VALUES}')
314+
raise InvalidGainError(gain=gain, values=self.interface.GAIN_VALUES)
318315

319316
@property
320317
def integration_cycles(self):
@@ -326,7 +323,7 @@ def integration_cycles(self, integration_cycles):
326323
self.interface.set_integration_cycles(integration_cycles)
327324
sleep(self.interface.CLOCK_STEP)
328325
else:
329-
raise ValueError(f'Cannot set integration cycles to {integration_cycles} (1-256)')
326+
raise InvalidIntegrationCyclesError(integration_cycles=integration_cycles)
330327

331328
@property
332329
def integration_time(self):

sense_hat/exceptions.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class SenseHatException(Exception):
2+
"""
3+
The base exception class for all SenseHat exceptions.
4+
"""
5+
fmt = 'An unspecified error occurred'
6+
7+
def __init__(self, **kwargs):
8+
msg = self.fmt.format(**kwargs)
9+
Exception.__init__(self, msg)
10+
self.kwargs = kwargs
11+
12+
13+
class ColourSensorInitialisationError(SenseHatException):
14+
fmt = "Failed to initialise TCS34725 colour sensor. {explanation}"
15+
16+
17+
class InvalidGainError(SenseHatException):
18+
fmt = "Cannot set gain to '{gain}'. Values: {values}"
19+
20+
21+
class InvalidIntegrationCyclesError(SenseHatException):
22+
fmt = "Cannot set integration cycles to {integration_cycles} (1-256)"

sense_hat/sense_hat.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/python
2+
import logging
23
import struct
34
import os
45
import sys
@@ -16,6 +17,7 @@
1617

1718
from .stick import SenseStick
1819
from .colour import ColourSensor
20+
from .exceptions import ColourSensorInitialisationError
1921

2022
class SenseHat(object):
2123

@@ -94,7 +96,8 @@ def __init__(
9496
# initialise the TCS34725 colour sensor (if possible)
9597
try:
9698
self._colour = ColourSensor()
97-
except:
99+
except Exception as e:
100+
logging.warning(e)
98101
pass
99102

100103
####
@@ -206,7 +209,9 @@ def colour(self):
206209
try:
207210
return self._colour
208211
except AttributeError as e:
209-
raise RuntimeError('This Sense HAT does not have a color sensor') from e
212+
raise ColourSensorInitialisationError(
213+
explanation="This Sense HAT" +
214+
" does not have a color sensor") from e
210215

211216
color = colour
212217

@@ -531,7 +536,7 @@ def gamma(self):
531536

532537
@gamma.setter
533538
def gamma(self, buffer):
534-
if len(buffer) is not 32:
539+
if len(buffer) != 32:
535540
raise ValueError('Gamma array must be of length 32')
536541

537542
if not all(b <= 31 for b in buffer):

0 commit comments

Comments
 (0)