I'm using the w1thermsensor on a Raspberry Pi. It works, but I want to make my code robust to errors, such as hardware failure, the sensor being unplugged etc.
There doesn't seem to be any specific help in the Github repository (although I can see from the code that it can raise exceptions), nor have I found any examples online processing errors.
My code is:
try:
sensor = W1ThermSensor() # Assumes just one sensor available
sensor_detect = "Detected"
except:
sensor_detect = "Detect Error"
if sensor_detect == "Detected":
try:
air_temperature = sensor.get_temperature()
except:
air_temperature = "Get temperature Error"
Initially I didn't have the try/except checks and get failures if the sensor is either not there/removed. But I'd like to be a bit more precise by using the error conditions that the library returns. Is there a concise list of exceptions that might occur / example code for processing errors?
The exceptions which can be raised by the w1thermsensor package are documented in the docstrings of the methods. Eg for get_temperature()
:
>>> help(w1thermsensor.core.W1ThermSensor.get_temperature)
Help on function get_temperature in module w1thermsensor.core:
get_temperature(self, unit=1)
Returns the temperature in the specified unit
:param int unit: the unit of the temperature requested
:returns: the temperature in the given unit
:rtype: float
:raises UnsupportedUnitError: if the unit is not supported
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.