Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import time
- import sys
- import iothub_client
- # pylint: disable=E0611
- from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
- from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError, DeviceMethodReturnValue
- import board
- import busio
- from digitalio import DigitalInOut
- from adafruit_pn532.i2c import PN532_I2C
- reset_pin = DigitalInOut(board.D6)
- req_pin = DigitalInOut(board.D12)
- i2c = busio.I2C(board.SCL, board.SDA)
- pn532 = PN532_I2C(i2c, debug=False, reset=reset_pin, req=req_pin)
- pn532.SAM_configuration()
- # Your IoT hub device connection string:
- CONNECTION_STRING = "HostName=mb-iot-hub.azure-devices.net;DeviceId=RaspberryPi;SharedAccessKey=lu3szoJReJwqvAbXgAqopQ4V6TKnXSYkKN0wP6e4BtI="
- # Using the MQTT protocol.
- PROTOCOL = IoTHubTransportProvider.MQTT
- MESSAGE_TIMEOUT = 10000
- # Define the JSON message to send to IoT Hub.
- ###TEMPERATURE = 20.0
- ###HUMIDITY = 60
- ###MSG_TXT = "{\"temperature\": %.2f,\"humidity\": %.2f}"
- def send_confirmation_callback(message, result, user_context):
- print ( "IoT Hub responded to message with status: %s" % (result) )
- def iothub_client_init():
- # Create an IoT Hub client
- client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
- return client
- def iothub_client_telemetry_sample_run():
- try:
- client = iothub_client_init()
- print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
- while True:
- # Build the message with simulated telemetry values.
- uid = pn532.read_passive_target(timeout=0.5)
- print(end="", flush=True)
- if uid is None:
- continue
- MSG_TXT = bytearray([int(i) for i in uid])
- #temperature = TEMPERATURE + (random.random() * 15)
- #humidity = HUMIDITY + (random.random() * 20)
- msg_txt_formatted = MSG_TXT
- message = IoTHubMessage(msg_txt_formatted)
- # Add a custom application property to the message.
- # An IoT hub can filter on these properties without access to the message body.
- #prop_map = message.properties()
- #if temperature > 30:
- #prop_map.add("temperatureAlert", "true")
- #else:
- #prop_map.add("temperatureAlert", "false")
- # Send the message.
- print( "Sending message: %s" % message.get_string() )
- client.send_event_async(message, send_confirmation_callback, None)
- time.sleep(1)
- except IoTHubError as iothub_error:
- print ( "Unexpected error %s from IoTHub" % iothub_error )
- return
- except KeyboardInterrupt:
- print ( "IoTHubClient sample stopped" )
- if __name__ == '__main__':
- print ( "IoT Hub Quickstart #1 - Simulated device" )
- print ( "Press Ctrl-C to exit" )
- iothub_client_telemetry_sample_run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement