Skip to content
This repository was archived by the owner on Nov 16, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions Adafruit_BME280.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,25 @@ def __init__(self, t_mode=BME280_OSAMPLE_1, p_mode=BME280_OSAMPLE_1, h_mode=BME2
self._logger = logging.getLogger('Adafruit_BMP.BMP085')
# Check that t_mode is valid.
if t_mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
raise ValueError(
'Unexpected t_mode value {0}.'.format(t_mode))
self._t_mode = t_mode
# Check that p_mode is valid.
if p_mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
raise ValueError(
'Unexpected p_mode value {0}.'.format(p_mode))
self._p_mode = p_mode
# Check that h_mode is valid.
if h_mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
raise ValueError(
'Unexpected h_mode value {0}.'.format(h_mode))
self._h_mode = h_mode
# Check that standby is valid.
if standby not in [BME280_STANDBY_0p5, BME280_STANDBY_62p5, BME280_STANDBY_125, BME280_STANDBY_250,
BME280_STANDBY_500, BME280_STANDBY_1000, BME280_STANDBY_10, BME280_STANDBY_20]:
BME280_STANDBY_500, BME280_STANDBY_1000, BME280_STANDBY_10, BME280_STANDBY_20]:
raise ValueError(
'Unexpected standby value {0}.'.format(standby))
self._standby = standby
Expand All @@ -136,10 +136,14 @@ def __init__(self, t_mode=BME280_OSAMPLE_1, p_mode=BME280_OSAMPLE_1, h_mode=BME2
self._load_calibration()
self._device.write8(BME280_REGISTER_CONTROL, 0x24) # Sleep mode
time.sleep(0.002)
self._device.write8(BME280_REGISTER_CONFIG, ((standby << 5) | (filter << 2)))
self._device.write8(BME280_REGISTER_CONFIG,
((standby << 5) | (filter << 2)))
time.sleep(0.002)
self._device.write8(BME280_REGISTER_CONTROL_HUM, h_mode) # Set Humidity Oversample
self._device.write8(BME280_REGISTER_CONTROL, ((t_mode << 5) | (p_mode << 2) | 3)) # Set Temp/Pressure Oversample and enter Normal mode
self._device.write8(BME280_REGISTER_CONTROL_HUM,
h_mode) # Set Humidity Oversample
# Set Temp/Pressure Oversample and enter Normal mode
self._device.write8(BME280_REGISTER_CONTROL,
((t_mode << 5) | (p_mode << 2) | 3))
self.t_fine = 0.0

def _load_calibration(self):
Expand Down Expand Up @@ -170,7 +174,7 @@ def _load_calibration(self):
h5 = self._device.readS8(BME280_REGISTER_DIG_H6)
h5 = (h5 << 4)
self.dig_H5 = h5 | (
self._device.readU8(BME280_REGISTER_DIG_H5) >> 4 & 0x0F)
self._device.readU8(BME280_REGISTER_DIG_H5) >> 4 & 0x0F)

'''
print '0xE4 = {0:2x}'.format (self._device.readU8 (BME280_REGISTER_DIG_H4))
Expand All @@ -192,14 +196,16 @@ def read_raw_temp(self):
while (self._device.readU8(BME280_REGISTER_STATUS) & 0x08): # Wait for conversion to complete (TODO : add timeout)
time.sleep(0.002)
self.BME280Data = self._device.readList(BME280_REGISTER_DATA, 8)
raw = ((self.BME280Data[3] << 16) | (self.BME280Data[4] << 8) | self.BME280Data[5]) >> 4
raw = ((self.BME280Data[3] << 16) | (
self.BME280Data[4] << 8) | self.BME280Data[5]) >> 4
return raw

def read_raw_pressure(self):
"""Returns the raw (uncompensated) pressure level from the sensor."""
"""Assumes that the temperature has already been read """
"""i.e. that BME280Data[] has been populated."""
raw = ((self.BME280Data[0] << 16) | (self.BME280Data[1] << 8) | self.BME280Data[2]) >> 4
raw = ((self.BME280Data[0] << 16) | (
self.BME280Data[1] << 8) | self.BME280Data[2]) >> 4
return raw

def read_raw_humidity(self):
Expand All @@ -213,9 +219,10 @@ def read_temperature(self):
"""Gets the compensated temperature in degrees celsius."""
# float in Python is double precision
UT = float(self.read_raw_temp())
var1 = (UT / 16384.0 - float(self.dig_T1) / 1024.0) * float(self.dig_T2)
var1 = (UT / 16384.0 - float(self.dig_T1) / 1024.0) * \
float(self.dig_T2)
var2 = ((UT / 131072.0 - float(self.dig_T1) / 8192.0) * (
UT / 131072.0 - float(self.dig_T1) / 8192.0)) * float(self.dig_T3)
UT / 131072.0 - float(self.dig_T1) / 8192.0)) * float(self.dig_T3)
self.t_fine = int(var1 + var2)
temp = (var1 + var2) / 5120.0
return temp
Expand All @@ -228,7 +235,7 @@ def read_pressure(self):
var2 = var2 + var1 * float(self.dig_P5) * 2.0
var2 = var2 / 4.0 + float(self.dig_P4) * 65536.0
var1 = (
float(self.dig_P3) * var1 * var1 / 524288.0 + float(self.dig_P2) * var1) / 524288.0
float(self.dig_P3) * var1 * var1 / 524288.0 + float(self.dig_P2) * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * float(self.dig_P1)
if var1 == 0:
return 0
Expand All @@ -244,8 +251,8 @@ def read_humidity(self):
# print 'Raw humidity = {0:d}'.format (adc)
h = float(self.t_fine) - 76800.0
h = (adc - (float(self.dig_H4) * 64.0 + float(self.dig_H5) / 16384.0 * h)) * (
float(self.dig_H2) / 65536.0 * (1.0 + float(self.dig_H6) / 67108864.0 * h * (
1.0 + float(self.dig_H3) / 67108864.0 * h)))
float(self.dig_H2) / 65536.0 * (1.0 + float(self.dig_H6) / 67108864.0 * h * (
1.0 + float(self.dig_H3) / 67108864.0 * h)))
h = h * (1.0 - float(self.dig_H1) * h / 524288.0)
if h > 100:
h = 100
Expand Down
2 changes: 1 addition & 1 deletion BME280SensorSimulator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# coding: utf-8
import random


class BME280SensorSimulator:

def __init__(self):
Expand All @@ -11,4 +12,3 @@ def read_temperature(self):

def read_humidity(self):
return random.uniform(60, 80)

115 changes: 68 additions & 47 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,97 +56,108 @@
telemetry = Telemetry()

if len(sys.argv) < 2:
print ( "You need to provide the device connection string as command line arguments." )
telemetry.send_telemetry_data(None, EVENT_FAILED, "Device connection string is not provided")
print("You need to provide the device connection string as command line arguments.")
telemetry.send_telemetry_data(
None, EVENT_FAILED, "Device connection string is not provided")
sys.exit(0)


def is_correct_connection_string():
m = re.search("HostName=.*;DeviceId=.*;", CONNECTION_STRING)
if m:
return True
else:
return False


CONNECTION_STRING = sys.argv[1]

if not is_correct_connection_string():
print ( "Device connection string is not correct." )
telemetry.send_telemetry_data(None, EVENT_FAILED, "Device connection string is not correct.")
print("Device connection string is not correct.")
telemetry.send_telemetry_data(
None, EVENT_FAILED, "Device connection string is not correct.")
sys.exit(0)

MSG_TXT = "{\"deviceId\": \"Raspberry Pi - Python\",\"temperature\": %f,\"humidity\": %f}"

GPIO.setmode(GPIO.BCM)
GPIO.setup(config.GPIO_PIN_ADDRESS, GPIO.OUT)


def receive_message_callback(message, counter):
global RECEIVE_CALLBACKS
message_buffer = message.get_bytearray()
size = len(message_buffer)
print ( "Received Message [%d]:" % counter )
print ( " Data: <<<%s>>> & Size=%d" % (message_buffer[:size].decode("utf-8"), size) )
print("Received Message [%d]:" % counter)
print(" Data: <<<%s>>> & Size=%d" %
(message_buffer[:size].decode("utf-8"), size))
map_properties = message.properties()
key_value_pair = map_properties.get_internals()
print ( " Properties: %s" % key_value_pair )
print(" Properties: %s" % key_value_pair)
counter += 1
RECEIVE_CALLBACKS += 1
print ( " Total calls received: %d" % RECEIVE_CALLBACKS )
print(" Total calls received: %d" % RECEIVE_CALLBACKS)
return IoTHubMessageDispositionResult.ACCEPTED


def send_confirmation_callback(message, result, user_context):
global SEND_CALLBACKS
print ( "Confirmation[%d] received for message with result = %s" % (user_context, result) )
print("Confirmation[%d] received for message with result = %s" % (
user_context, result))
map_properties = message.properties()
print ( " message_id: %s" % message.message_id )
print ( " correlation_id: %s" % message.correlation_id )
print(" message_id: %s" % message.message_id)
print(" correlation_id: %s" % message.correlation_id)
key_value_pair = map_properties.get_internals()
print ( " Properties: %s" % key_value_pair )
print(" Properties: %s" % key_value_pair)
SEND_CALLBACKS += 1
print ( " Total calls confirmed: %d" % SEND_CALLBACKS )
print(" Total calls confirmed: %d" % SEND_CALLBACKS)
led_blink()


def device_twin_callback(update_state, payload, user_context):
global TWIN_CALLBACKS
print ( "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s" % (update_state, payload, user_context) )
print("\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s" % (
update_state, payload, user_context))
TWIN_CALLBACKS += 1
print ( "Total calls confirmed: %d\n" % TWIN_CALLBACKS )
print("Total calls confirmed: %d\n" % TWIN_CALLBACKS)


def send_reported_state_callback(status_code, user_context):
global SEND_REPORTED_STATE_CALLBACKS
print ( "Confirmation for reported state received with:\nstatus_code = [%d]\ncontext = %s" % (status_code, user_context) )
print("Confirmation for reported state received with:\nstatus_code = [%d]\ncontext = %s" % (
status_code, user_context))
SEND_REPORTED_STATE_CALLBACKS += 1
print ( " Total calls confirmed: %d" % SEND_REPORTED_STATE_CALLBACKS )
print(" Total calls confirmed: %d" % SEND_REPORTED_STATE_CALLBACKS)


def device_method_callback(method_name, payload, user_context):
global METHOD_CALLBACKS,MESSAGE_SWITCH
print ( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context) )
global METHOD_CALLBACKS, MESSAGE_SWITCH
print("\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (
method_name, payload, user_context))
METHOD_CALLBACKS += 1
print ( "Total calls confirmed: %d\n" % METHOD_CALLBACKS )
print("Total calls confirmed: %d\n" % METHOD_CALLBACKS)
device_method_return_value = DeviceMethodReturnValue()
device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }"
device_method_return_value.status = 200
if method_name == "start":
MESSAGE_SWITCH = True
print ( "Start sending message\n" )
print("Start sending message\n")
device_method_return_value.response = "{ \"Response\": \"Successfully started\" }"
return device_method_return_value
if method_name == "stop":
MESSAGE_SWITCH = False
print ( "Stop sending message\n" )
print("Stop sending message\n")
device_method_return_value.response = "{ \"Response\": \"Successfully stopped\" }"
return device_method_return_value
return device_method_return_value


def blob_upload_conf_callback(result, user_context):
global BLOB_CALLBACKS
print ( "Blob upload confirmation[%d] received for message with result = %s" % (user_context, result) )
print("Blob upload confirmation[%d] received for message with result = %s" % (
user_context, result))
BLOB_CALLBACKS += 1
print ( " Total calls confirmed: %d" % BLOB_CALLBACKS )
print(" Total calls confirmed: %d" % BLOB_CALLBACKS)


def iothub_client_init():
Expand Down Expand Up @@ -174,82 +185,92 @@ def iothub_client_init():
def print_last_message_time(client):
try:
last_message = client.get_last_message_receive_time()
print ( "Last Message: %s" % time.asctime(time.localtime(last_message)) )
print ( "Actual time : %s" % time.asctime() )
print("Last Message: %s" % time.asctime(time.localtime(last_message)))
print("Actual time : %s" % time.asctime())
except IoTHubClientError as iothub_client_error:
if iothub_client_error.args[0].result == IoTHubClientResult.INDEFINITE_TIME:
print ( "No message received" )
print("No message received")
else:
print ( iothub_client_error )
print(iothub_client_error)


def iothub_client_sample_run():
try:
client = iothub_client_init()

if client.protocol == IoTHubTransportProvider.MQTT:
print ( "IoTHubClient is reporting state" )
print("IoTHubClient is reporting state")
reported_state = "{\"newState\":\"standBy\"}"
client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
client.send_reported_state(reported_state, len(
reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)

if not config.SIMULATED_DATA:
sensor = BME280(address = config.I2C_ADDRESS)
sensor = BME280(address=config.I2C_ADDRESS)
else:
sensor = BME280SensorSimulator()

telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")
telemetry.send_telemetry_data(parse_iot_hub_name(
), EVENT_SUCCESS, "IoT hub connection is established")
while True:
global MESSAGE_COUNT,MESSAGE_SWITCH
global MESSAGE_COUNT, MESSAGE_SWITCH
if MESSAGE_SWITCH:
# send a few messages every minute
print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )
print("IoTHubClient sending %d messages" % MESSAGE_COUNT)
temperature = sensor.read_temperature()
humidity = sensor.read_humidity()
msg_txt_formatted = MSG_TXT % (
temperature,
humidity)
print (msg_txt_formatted)
print(msg_txt_formatted)
message = IoTHubMessage(msg_txt_formatted)
# optional: assign ids
message.message_id = "message_%d" % MESSAGE_COUNT
message.correlation_id = "correlation_%d" % MESSAGE_COUNT
# optional: assign properties
prop_map = message.properties()
prop_map.add("temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false")
prop_map.add("temperatureAlert", "true" if temperature >
TEMPERATURE_ALERT else "false")

client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT)
print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT )
client.send_event_async(
message, send_confirmation_callback, MESSAGE_COUNT)
print(
"IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT)

status = client.get_send_status()
print ( "Send status: %s" % status )
print("Send status: %s" % status)
MESSAGE_COUNT += 1
time.sleep(config.MESSAGE_TIMESPAN / 1000.0)

except IoTHubError as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
print("Unexpected error %s from IoTHub" % iothub_error)
telemetry.send_telemetry_data(parse_iot_hub_name(
), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
return
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
print("IoTHubClient sample stopped")

print_last_message_time(client)


def led_blink():
GPIO.output(config.GPIO_PIN_ADDRESS, GPIO.HIGH)
time.sleep(config.BLINK_TIMESPAN / 1000.0)
GPIO.output(config.GPIO_PIN_ADDRESS, GPIO.LOW)


def usage():
print ( "Usage: iothub_client_sample.py -p <protocol> -c <connectionstring>" )
print ( " protocol : <amqp, amqp_ws, http, mqtt, mqtt_ws>" )
print ( " connectionstring: <HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>>" )
print("Usage: iothub_client_sample.py -p <protocol> -c <connectionstring>")
print(" protocol : <amqp, amqp_ws, http, mqtt, mqtt_ws>")
print(" connectionstring: <HostName=<host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>>")


def parse_iot_hub_name():
m = re.search("HostName=(.*?)\.", CONNECTION_STRING)
return m.group(1)


if __name__ == "__main__":
print ( "\nPython %s" % sys.version )
print ( "IoT Hub Client for Python" )
print("\nPython %s" % sys.version)
print("IoT Hub Client for Python")

iothub_client_sample_run()
Loading