Skip to content

Commit 2467f04

Browse files
authored
Merge pull request #12 from jimbobbennett/master
Change from library dependency to code to save 37K of memory
2 parents 18b7c50 + 3c3e4fc commit 2467f04

19 files changed

+712
-85
lines changed

README.rst

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,16 +45,12 @@ This driver depends on:
4545

4646
* `Adafruit CircuitPython <https://github.com/adafruit/circuitpython>`_
4747
* `Adafruit CircuitPython MiniMQTT <https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT>`_
48-
49-
* `CircuitPython Base64 <https://github.com/jimbobbennett/CircuitPython_Base64>`_
50-
* `CircuitPython HMAC <https://github.com/jimbobbennett/CircuitPython_HMAC>`_
51-
* `CircuitPython Parse <https://github.com/jimbobbennett/CircuitPython_Parse>`_
48+
* `Adafruit CircuitPython Requests <https://github.com/adafruit/Adafruit_CircuitPython_Requests>`_
49+
* `Adafruit CircuitPython BinASCII <https://github.com/adafruit/Adafruit_CircuitPython_Binascii>`_
5250

5351
Please ensure all dependencies are available on the CircuitPython filesystem.
5452
This is easily achieved by downloading
55-
`the Adafruit library and driver bundle <https://github.com/adafruit/Adafruit_CircuitPython_Bundle>`_
56-
and
57-
`the CircuitPython community library and driver bundle <https://github.com/adafruit/CircuitPython_Community_Bundle>`_
53+
`the Adafruit library and driver bundle <https://github.com/adafruit/Adafruit_CircuitPython_Bundle>`_.
5854

5955
Usage Example
6056
=============

adafruit_azureiot/__init__.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,6 @@
3737
3838
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
3939
* Adafruit's ESP32SPI library: https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI
40-
* Community HMAC library: https://github.com/jimbobbennett/CircuitPython_HMAC
41-
* Community base64 library: https://github.com/jimbobbennett/CircuitPython_Base64
42-
* Community Parse library: https://github.com/jimbobbennett/CircuitPython_Parse
4340
"""
4441

4542
from .iot_error import IoTError

adafruit_azureiot/base64.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# The MIT License (MIT)
2+
#
3+
# Copyright (c) 2020 Jim Bennett
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in
13+
# all copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
# THE SOFTWARE.
22+
"""
23+
`base64`
24+
================================================================================
25+
26+
RFC 3548: Base64 Data Encodings
27+
28+
29+
* Author(s): Jim Bennett
30+
31+
Implementation Notes
32+
--------------------
33+
34+
**Software and Dependencies:**
35+
36+
* Adafruit CircuitPython firmware for the supported boards:
37+
https://github.com/adafruit/circuitpython/releases
38+
39+
"""
40+
41+
import adafruit_binascii as binascii
42+
43+
__all__ = ["b64encode", "b64decode"]
44+
45+
46+
def _bytes_from_decode_data(data: str):
47+
try:
48+
return data.encode("ascii")
49+
except:
50+
raise ValueError("string argument should contain only ASCII characters")
51+
52+
53+
def b64encode(toencode: bytes) -> bytes:
54+
"""Encode a byte string using Base64.
55+
56+
toencode is the byte string to encode. Optional altchars must be a byte
57+
string of length 2 which specifies an alternative alphabet for the
58+
'+' and '/' characters. This allows an application to
59+
e.g. generate url or filesystem safe Base64 strings.
60+
61+
The encoded byte string is returned.
62+
"""
63+
# Strip off the trailing newline
64+
return binascii.b2a_base64(toencode)[:-1]
65+
66+
67+
def b64decode(todecode: str) -> bytes:
68+
"""Decode a Base64 encoded byte string.
69+
70+
todecode is the byte string to decode. Optional altchars must be a
71+
string of length 2 which specifies the alternative alphabet used
72+
instead of the '+' and '/' characters.
73+
74+
The decoded string is returned. A binascii.Error is raised if todecode is
75+
incorrectly padded.
76+
77+
If validate is False (the default), non-base64-alphabet characters are
78+
discarded prior to the padding check. If validate is True,
79+
non-base64-alphabet characters in the input result in a binascii.Error.
80+
"""
81+
return binascii.a2b_base64(_bytes_from_decode_data(todecode))

adafruit_azureiot/device_registration.py

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,12 @@
3232
import gc
3333
import json
3434
import time
35-
import circuitpython_base64 as base64
36-
import circuitpython_hmac as hmac
37-
import circuitpython_parse as parse
3835
import adafruit_requests as requests
3936
import adafruit_logging as logging
4037
from adafruit_logging import Logger
41-
import adafruit_hashlib as hashlib
4238
from . import constants
39+
from .quote import quote
40+
from .keys import compute_derived_symmetric_key
4341

4442
# Azure HTTP error status codes
4543
AZURE_HTTP_ERROR_CODES = [400, 401, 404, 403, 412, 429, 500]
@@ -89,17 +87,6 @@ def __init__(self, socket, id_scope: str, device_id: str, key: str, logger: Logg
8987

9088
requests.set_socket(socket)
9189

92-
@staticmethod
93-
def compute_derived_symmetric_key(secret: str, msg: str) -> bytes:
94-
"""Computes a derived symmetric key from a secret and a message
95-
:param str secret: The secret to use for the key
96-
:param str msg: The message to use for the key
97-
:returns: The derived symmetric key
98-
:rtype: bytes
99-
"""
100-
secret = base64.b64decode(secret)
101-
return base64.b64encode(hmac.new(secret, msg=msg.encode("utf8"), digestmod=hashlib.sha256).digest())
102-
10390
def _loop_assign(self, operation_id, headers) -> str:
10491
uri = "https://%s/%s/registrations/%s/operations/%s?api-version=%s" % (
10592
constants.DPS_END_POINT,
@@ -109,9 +96,8 @@ def _loop_assign(self, operation_id, headers) -> str:
10996
constants.DPS_API_VERSION,
11097
)
11198
self._logger.info("- iotc :: _loop_assign :: " + uri)
112-
target = parse.urlparse(uri)
11399

114-
response = self._run_get_request_with_retry(target.geturl(), headers)
100+
response = self._run_get_request_with_retry(uri, headers)
115101

116102
try:
117103
data = response.json()
@@ -205,8 +191,8 @@ def register_device(self, expiry: int) -> str:
205191
"""
206192
# pylint: disable=C0103
207193
sr = self._id_scope + "%2Fregistrations%2F" + self._device_id
208-
sig_no_encode = DeviceRegistration.compute_derived_symmetric_key(self._key, sr + "\n" + str(expiry))
209-
sig_encoded = parse.quote(sig_no_encode, "~()*!.'")
194+
sig_no_encode = compute_derived_symmetric_key(self._key, sr + "\n" + str(expiry))
195+
sig_encoded = quote(sig_no_encode, "~()*!.'")
210196
auth_string = "SharedAccessSignature sr=" + sr + "&sig=" + sig_encoded + "&se=" + str(expiry) + "&skn=registration"
211197

212198
headers = {
@@ -226,13 +212,12 @@ def register_device(self, expiry: int) -> str:
226212
self._device_id,
227213
constants.DPS_API_VERSION,
228214
)
229-
target = parse.urlparse(uri)
230215

231216
self._logger.info("Connecting...")
232-
self._logger.info("URL: " + target.geturl())
217+
self._logger.info("URL: " + uri)
233218
self._logger.info("body: " + json.dumps(body))
234219

235-
response = self._run_put_request_with_retry(target.geturl(), body, headers)
220+
response = self._run_put_request_with_retry(uri, body, headers)
236221

237222
data = None
238223
try:

0 commit comments

Comments
 (0)