|
| 1 | +# SPDX-FileCopyrightText: 2021 Jose David M |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Unlicense |
| 4 | +""" |
| 5 | +Example showing the use of Fake_requests to access a Temperature Sensor information |
| 6 | +Database. Inspired on the I2C buddy and a Discussion with Hugo Dahl |
| 7 | +""" |
| 8 | +import board |
| 9 | +from adafruit_fakerequests import Fake_Requests |
| 10 | + |
| 11 | +# Create the fakerequest request and get the temperature sensor definitions |
| 12 | +# It will look through the database and print the name of the sensor and |
| 13 | +# the temperature |
| 14 | +response = Fake_Requests("fakerequests_i2c_database.txt") |
| 15 | +definitions = response.text.split("\n") |
| 16 | + |
| 17 | +# We create the i2c object and set a flag to let us know if the sensor is found |
| 18 | +found = False |
| 19 | +i2c = board.I2C() |
| 20 | + |
| 21 | +# We look for all the sensor address and added to a list |
| 22 | +print("Looking for addresses") |
| 23 | +i2c.unlock() # used here, to avoid problems with the I2C bus |
| 24 | +i2c.try_lock() |
| 25 | +sensor_address = int(i2c.scan()[-1]) |
| 26 | +print("Sensor address is:", hex(sensor_address)) |
| 27 | +i2c.unlock() # unlock the bus |
| 28 | + |
| 29 | +# Create an empty list for the sensors found in the database |
| 30 | +sensor_choices = list() |
| 31 | + |
| 32 | +# Compare the sensor found vs the database. this is done because |
| 33 | +# we could have the case that the same address corresponds to |
| 34 | +# two or more temperature sensors |
| 35 | +for sensor in definitions: |
| 36 | + elements = sensor.split(",") |
| 37 | + if int(elements[0]) == sensor_address: |
| 38 | + sensor_choices.append(sensor) |
| 39 | + |
| 40 | +# This is the main logic to found the sensor and try to |
| 41 | +# initiate it. It would raise some exceptions depending |
| 42 | +# on the situation. As an example this is not perfect |
| 43 | +# and only serves to show the library capabilities |
| 44 | +# and nothing more |
| 45 | +for find_sensor in sensor_choices: |
| 46 | + module = find_sensor.split(",") |
| 47 | + package = module[2] |
| 48 | + class_name = str(module[3]).strip(" ") |
| 49 | + try: |
| 50 | + module = __import__(package) |
| 51 | + variable = getattr(module, class_name) |
| 52 | + try: |
| 53 | + sensor = variable(i2c) |
| 54 | + print( |
| 55 | + "The sensor {} gives a temperature of {} Celsius".format( |
| 56 | + class_name, sensor.temperature |
| 57 | + ) |
| 58 | + ) |
| 59 | + found = True |
| 60 | + except ValueError: |
| 61 | + pass |
| 62 | + except Exception as e: |
| 63 | + raise ImportError( |
| 64 | + "Could not find the module {} in your lib folder.".format(package) |
| 65 | + ) from e |
| 66 | + |
| 67 | +if found: |
| 68 | + print("Congratulations") |
| 69 | +else: |
| 70 | + print("We could not find a valid Temperature Sensor") |
0 commit comments