Instantly share code, notes, and snippets.

Embed
What would you like to do?
Send IoT Events from Device to Cloud over HTTPS and REST
# Send Message Device to IoTHub over HTTPS via Rest
import datetime, requests
# IoT DeviceID
deviceID = "MyIoTDevice"
# Iot Hub Name
IoTHubName = "MyIoTHub"
# RestAPI Version
iotHubAPIVer = "2018-04-01"
iotHubRestURI = "https://" + IoTHubName + ".azure-devices.net/devices/" + deviceID + "/messages/events?api-version=" + iotHubAPIVer
# SAS Token Generated via Azure CLI or Device Explorer
SASToken = 'SharedAccessSignature sr=MyIoTHub.azure-devices.net%2Fdevices%2FMyIoTDevice&sig=gqitFLvPA9Avxe6sugiPVG%2F8cx8cBOXCSDFGHJK8E%3D&se=1560379444'
# Headers
Headers = {}
Headers['Authorization'] = SASToken
Headers['Content-Type'] = "application/json"
# Message Payload
datetime = datetime.datetime.now()
body = {}
body['datetime'] = str(datetime)
body['deviceClient'] = deviceID
body['Message'] = 'Python Device to Cloud Message'
# Send Message
resp = requests.post(iotHubRestURI, json=body, headers=Headers)
print(resp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment