예제 #1
0
    def generate_jwt(self, ttl=43200, algo="RS256"):
        """Generates a JSON Web Token (https://jwt.io/) using network time.
        :param int jwt_ttl: When the JWT token expires, defaults to 43200 minutes (or 12 hours).
        :param str algo: Algorithm used to create a JSON Web Token.

        Example usage of generating and setting a JSON-Web-Token:
        ..code-block:: python

            jwt = CloudCore.generate_jwt()
            print("Generated JWT: ", jwt)

        """
        if self.logger:
            self.logger.debug("Generating JWT...")
        ntp = NTP.NTP(self._esp)
        ntp.set_time()
        claims = {
            # The time that the token was issued at
            "iat": time.time(),
            # The time the token expires.
            "exp": time.time() + ttl,
            # The audience field should always be set to the GCP project id.
            "aud": self._proj_id,
        }
        jwt = JWT.generate(claims, self._private_key, algo)
        return jwt
예제 #2
0
 def __init__(self, mqtt_client):
     # Check that provided object is a MiniMQTT client object
     mqtt_client_type = str(type(mqtt_client))
     if "MQTT" in mqtt_client_type:
         self._client = mqtt_client
     else:
         raise TypeError(
             "This class requires a MiniMQTT client object, please create one."
         )
     # Verify that the MiniMQTT client was setup correctly.
     try:
         self.user = self._client.user
     except Exception as err:
         raise TypeError(
             "Google Cloud Core IoT MQTT API requires a username.") from err
     # Validate provided JWT before connecting
     try:
         JWT.validate(self._client.password)
     except Exception as err:
         raise TypeError("Invalid JWT provided.") from err
     # If client has KeepAlive =0 or if KeepAlive > 20min,
     # set KeepAlive to 19 minutes to avoid disconnection
     # due to Idle Time (https://cloud.google.com/iot/quotas).
     if self._client.keep_alive == 0 or self._client.keep_alive >= 1200:
         self._client.keep_alive = 1140
     # User-defined MQTT callback methods must be init'd to None
     self.on_connect = None
     self.on_disconnect = None
     self.on_message = None
     self.on_subscribe = None
     self.on_unsubscribe = None
     # MQTT event callbacks
     self._client.on_connect = self._on_connect_mqtt
     self._client.on_disconnect = self._on_disconnect_mqtt
     self._client.on_message = self._on_message_mqtt
     self._client.on_subscribe = self._on_subscribe_mqtt
     self._client.on_unsubscribe = self._on_unsubscribe_mqtt
     self.logger = False
     if self._client.logger is not None:
         # Allow MQTT_API to utilize MiniMQTT Client's logger
         self.logger = True
         self._client.set_logger_level("DEBUG")
     self._connected = False
     # Set up a device identifier by splitting out the full CID
     self.device_id = self._client.client_id.split("/")[7]