Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjrobinson/9725f1ef6192025056af1acfe15c83eb to your computer and use it in GitHub Desktop.
Save darrenjrobinson/9725f1ef6192025056af1acfe15c83eb to your computer and use it in GitHub Desktop.
Send IoT Events from Device to Cloud over HTTPS and REST. Associated blogpost https://blog.darrenjrobinson.com/sending-events-from-iot-devices-to-azure-iot-hub-using-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