Created
April 19, 2016 09:56
-
-
Save bear256/1054b17c422f869775d066e4345840e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import hmac | |
import hashlib | |
import time | |
import requests | |
import urllib | |
class D2CMsgSender: | |
API_VERSION = '2016-02-03' | |
TOKEN_VALID_SECS = 10 | |
TOKEN_FORMAT = 'SharedAccessSignature sig=%s&se=%s&skn=%s&sr=%s' | |
def __init__(self, connectionString=None): | |
if connectionString != None: | |
iotHost, keyName, keyValue = [sub[sub.index('=') + 1:] for sub in connectionString.split(";")] | |
self.iotHost = iotHost | |
self.keyName = keyName | |
self.keyValue = keyValue | |
def _buildExpiryOn(self): | |
return '%d' % (time.time() + self.TOKEN_VALID_SECS) | |
def _buildIoTHubSasToken(self, deviceId): | |
resourceUri = '%s/devices/%s' % (self.iotHost, deviceId) | |
targetUri = resourceUri.lower() | |
expiryTime = self._buildExpiryOn() | |
toSign = '%s\n%s' % (targetUri, expiryTime) | |
key = base64.b64decode(self.keyValue.encode('utf-8')) | |
signature = urllib.quote( | |
base64.b64encode( | |
hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest() | |
) | |
).replace('/', '%2F') | |
return self.TOKEN_FORMAT % (signature, expiryTime, self.keyName, targetUri) | |
def sendD2CMsg(self, deviceId, message): | |
sasToken = self._buildIoTHubSasToken(deviceId) | |
url = 'https://%s/devices/%s/messages/events?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION) | |
r = requests.post(url, headers={'Authorization': sasToken}, data=message) | |
return r.text, r.status_code | |
if __name__ == '__main__': | |
connectionString = 'HostName=<iot-hub-name>.azure-devices.net;SharedAccessKeyName=device;SharedAccessKey=<device-policy-key>' | |
d2cMsgSender = D2CMsgSender(connectionString) | |
deviceId = 'iotdevice1' | |
message = 'Hello, IoT Hub' | |
print d2cMsgSender.sendD2CMsg(deviceId, message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment