10000 Change from library dependency to code to save 37K of memory by jimbobbennett · Pull Request #12 · adafruit/Adafruit_CircuitPython_AzureIoT · GitHub
[go: up one dir, main page]

Skip to content

Change from library dependency to code to save 37K of memory #12

New issue
8000

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,12 @@ This driver depends on:

* `Adafruit CircuitPython <https://github.com/adafruit/circuitpython>`_
* `Adafruit CircuitPython MiniMQTT <https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT>`_

* `CircuitPython Base64 <https://github.com/jimbobbennett/CircuitPython_Base64>`_
* `CircuitPython HMAC <https://github.com/jimbobbennett/CircuitPython_HMAC>`_
* `CircuitPython Parse <https://github.com/jimbobbennett/CircuitPython_Parse>`_
* `Adafruit CircuitPython Requests <https://github.com/adafruit/Adafruit_CircuitPython_Requests>`_
* `Adafruit CircuitPython BinASCII <https://github.com/adafruit/Adafruit_CircuitPython_Binascii>`_

Please ensure all dependencies are available on the CircuitPython filesystem.
This is easily achieved by downloading
`the Adafruit library and driver bundle <https://github.com/adafruit/Adafruit_CircuitPython_Bundle>`_
and
`the CircuitPython community library and driver bundle <https://github.com/adafruit/CircuitPython_Community_Bundle>`_
`the Adafruit library and driver bundle <https://github.com/adafruit/Adafruit_CircuitPython_Bundle>`_.

Usage Example
=============
Expand Down
3 changes: 0 additions & 3 deletions adafruit_azureiot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@

* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
* Adafruit's ESP32SPI library: https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI
* Community HMAC library: https://github.com/jimbobbennett/CircuitPython_HMAC
* Community base64 library: https://github.com/jimbobbennett/CircuitPython_Base64
* Community Parse library: https://github.com/jimbobbennett/CircuitPython_Parse
"""

from .iot_error import IoTError
Expand Down
81 changes: 81 additions & 0 deletions adafruit_azureiot/base64.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# The MIT License (MIT)
#
# Copyright (c) 2020 Jim Bennett
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`base64`
================================================================================

RFC 3548: Base64 Data Encodings


* Author(s): Jim Bennett

Implementation Notes
--------------------

**Software and Dependencies:**

* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases

"""

import adafruit_binascii as binascii

__all__ = ["b64encode", "b64decode"]


def _bytes_from_decode_data(data: str):
try:
return data.encode("ascii")
except:
raise ValueError("string argument should contain only ASCII characters")


def b64encode(toencode: bytes) -> bytes:
"""Encode a byte string using Base64.

toencode is the byte string to encode. Optional altchars must be a byte
string of length 2 which specifies an alternative alphabet for the
'+' and '/' characters. This allows an application to
e.g. generate url or filesystem safe Base64 strings.

The encoded byte string is returned.
"""
# Strip off the trailing newline
return binascii.b2a_base64(toencode)[:-1]


def b64decode(todecode: str) -> bytes:
"""Decode a Base64 encoded byte string.

todecode is the byte string to decode. Optional altchars must be a
string of length 2 which specifies the alternative alphabet used
instead of the '+' and '/' characters.

The decoded string is returned. A binascii.Error is raised if todecode is
incorrectly padded.

If validate is False (the default), non-base64-alphabet characters are
discarded prior to the padding check. If validate is True,
non-base64-alphabet characters in the input result in a binascii.Error.
"""
return binascii.a2b_base64(_bytes_from_decode_data(todecode))
29 changes: 7 additions & 22 deletions adafruit_azureiot/device_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@
import gc
import json
import time
import circuitpython_base64 as base64
import circuitpython_hmac as hmac
import circuitpython_parse as parse
import adafruit_requests as requests
import adafruit_logging as logging
from adafruit_logging import Logger
import adafruit_hashlib as hashlib
from . import constants
from .quote import quote
from .keys import compute_derived_symmetric_key

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

requests.set_socket(socket)

@staticmethod
def compute_derived_symmetric_key(secret: str, msg: str) -> bytes:
"""Computes a derived symmetric key from a secret and a message
:param str secret: The secret to use for the key
:param str msg: The message to use for the key
:returns: The derived symmetric key
:rtype: bytes
"""
secret = base64.b64decode(secret)
return base64.b64encode(hmac.new(secret, msg=msg.encode("utf8"), digestmod=hashlib.sha256).digest())

def _loop_assign(self, operation_id, headers) -> str:
uri = "https://%s/%s/registrations/%s/operations/%s?api-version=%s" % (
constants.DPS_END_POINT,
Expand All @@ -109,9 +96,8 @@ def _loop_assign(self, operation_id, headers) -> str:
constants.DPS_API_VERSION,
)
self._logger.info("- iotc :: _loop_assign :: " + uri)
target = parse.urlparse(uri)

response = self._run_get_request_with_retry(target.geturl(), headers)
response = self._run_get_request_with_retry(uri, headers)

try:
data = response.json()
Expand Down Expand Up @@ -205,8 +191,8 @@ def register_device(self, expiry: int) -> str:
"""
# pylint: disable=C0103
sr = self._id_scope + "%2Fregistrations%2F" + self._device_id
sig_no_encode = DeviceRegistration.compute_derived_symmetric_key(self._key, sr + "\n" + str(expiry))
sig_encoded = parse.quote(sig_no_encode, "~()*!.'")
sig_no_encode = compute_derived_symmetric_key(self._key, sr + "\n" + str(expiry))
sig_encoded = quote(sig_no_encode, "~()*!.'")
auth_string = "SharedAccessSignature sr=" + sr + "&sig=" + sig_encoded + "&se=" + str(expiry) + "&skn=registration"

headers = {
Expand All @@ -226,13 +212,12 @@ def register_device(self, expiry: int) -> str:
self._device_id,
constants.DPS_API_VERSION,
)
target = parse.urlparse(uri)

self._logger.info("Connecting...")
self._logger.info("URL: " + target.geturl())
self._logger.info("URL: " + uri)
self._logger.info("body: " + json.dumps(body))

response = self._run_put_request_with_retry(target.geturl(), body, headers)
response = self._run_put_request_with_retry(uri, body, headers)

data = None
try:
Expand Down
Loading
0