Example #1
0
def awsiot_loop():
    prctl.set_name("awsiot_loop")

    logger.info('Starting AWS IoT loop...')

    awsiot = AWSIoTMQTTShadowClient(DEVICE_NAME)
    awsiot.configureEndpoint(awsiot_endpoint, 8883)
    awsiot.configureCredentials(awsiot_ca, awsiot_key, awsiot_cert)
    awsiot.configureConnectDisconnectTimeout(10)
    awsiot.configureMQTTOperationTimeout(5)

    awsiot.connect()
    shadow = awsiot.createShadowHandlerWithName(DEVICE_NAME, True)

    while True:
        time.sleep(0.1)

        if awsiot_shutdown:
            break

        try:
            packet = awsiot_queue.get(timeout = 0.1)

            o = msgpack.unpackb(packet)

            doc = {
                "state": {
                    "reported": {
                        "temperature": o[b't'],
                        "humidity": o[b'h']
                    }
                }
            }

            s = json.dumps(doc)

            shadow.shadowUpdate(s, None, 5)
        except Empty:
            pass
        except Exception:
            logger.exception("Failed to push sensor packet to AWS IoT")

    awsiot.disconnect()
Example #2
0
    return json.dumps(string)


shadowClient.toJSON = toJSON

shadowMessage = {"state": {"desired": {"headLight": "On"}}}
shadowMessage = json.dumps(shadowMessage)


#Function to encode a payload into JSON
def json_encode(string):
    return json.dumps(string)


#Function to print message
def on_message(message, response, token):
    print(message)


shadowClientHandler.on_message = on_message
shadowClientHandler.json_encode = json_encode

#sending first shadow update
shadowClient.connect()
print("Baglandi")
shadowClientHandler.shadowUpdate(shadowMessage, on_message, 5)
print("Shadow Guncelleme Gonderildi")
shadowClient.disconnect()
print("Baglandi Kesildi")
time.sleep(2)
                            '"Power": "' + Power_Status + '"'+\
                        '} '+\
                    '} '+\
                '}'
    myDeviceShadow.shadowUpdate(JSONPayload, IoTShadowCallback_Update, 5)
    time.sleep(3)




# Listen on deltas from the IoT Shadow
myDeviceShadow.shadowGet(IoTShadowCallback_Get, 5)
myDeviceShadow.shadowRegisterDeltaCallback(IoTShadowCallback_Delta)
loopCount = 0

if __name__ == '__main__':
    try:
        print 'RasPi started, Press Ctrl-C to quit.'
        checkPlug()
        while True:
                 #pass
                 jsonChecker()
                
            # Listen on deltas from the IoT Shadow
            #myDeviceShadow.shadowGet(IoTShadowCallback_Get, 5)
            #myDeviceShadow.shadowRegisterDeltaCallback(IoTShadowCallback_Delta)            
    finally:
        myAWSIoTMQTTShadowClient.shadowUnregisterDeltaCallback()
        myAWSIoTMQTTShadowClient.disconnect()
        print 'RasPi stopped.'
Example #4
0
    
    # Only send motor vibration data if the motor is on.
    if MOTOR_STATUS == "ON":
        vibration = randint(-500, 500)
        message = {
            'vibration' : vibration
        }
        message = mqttClient.json_encode(message)
        mqttClient.publish("data/vibration", message, 0)
        print("Motor is running, Vibration Message Published")


#Connect to the gateway
mqttShadowClient.connect()
print ("Connected")

#Set the initial motor status in the device shadow
updateDeviceShadow()

# Listen for delta changes
shadowClient.shadowRegisterDeltaCallback(customShadowCallback_Delta)

#Loop until terminated
while True:
    send()
    time.sleep(5)

mqttShadowClient.disconnect()

#To check and see if your message was published to the message broker go to the MQTT Client and subscribe to the iot topic and you should see your JSON Payload
Example #5
0
shadowMessage = json.dumps(shadowMessage)


#Function to encode a payload into JSON
def json_encode(string):
    return json.dumps(string)


#Function to print message
def on_message(message, response, token):
    print(" response : " + response + " , message : " + message)


#Function to print message
def delete_message(message, response, token):
    print(" response : " + response + " , message : " + message)


shadowClient.on_message = on_message
shadowClient.json_encode = json_encode

#sending vechile shadow update
mqttc.connect()
print("Connected")
#delete the existing desire state from shadow
shadowClient.shadowDelete(delete_message, 5)
shadowClient.shadowUpdate(shadowMessage, on_message, 5)
print("Shadow Update Sent")
time.sleep(5)
mqttc.disconnect()
Example #6
0
        print("%r -> %r" % (switchId, relayState))
        URL="http://10.2.1.%d/toggle-relay" % (switchId,)
        response = requests.post(URL, data = {})
        print(response)

myShadowClient = AWSIoTMQTTShadowClient("Switch8266-east-v1", useWebsocket=True)
# myShadowClient.configureEndpoint("a2arj82jdj67sr.iot.us-west-2.amazonaws.com", 443)
myShadowClient.configureEndpoint("a2arj82jdj67sr-ats.iot.us-east-1.amazonaws.com", 443)
myShadowClient.configureCredentials("./certs/aws-east/AmazonRootCA1.pem")#, "./certs/aws/850d42b0ff-private.pem.key", "./certs/aws/850d42b0ff-certificate.pem.crt")

myShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec


myShadowClient.connect()

def customCallback(state ,r2, r3):
  print("Result=%r, %r, %r"%(state,r2, r3))


deviceShadow = myShadowClient.createShadowHandlerWithName("Switch8266-east-v1", True)
# deviceShadow.shadowGet(customCallback, 5)

deviceShadow.shadowRegisterDeltaCallback(customShadowCallback_Delta)

while 1:
  time.sleep(1)

myDeviceShadow.shadowUnregisterDeltaCallback()
myShadowClient.disconnect()
Example #7
0
class AWSClient(EdgeClient):
    """Class responsible for handling an Amazon AWS client used for plain MQTT
    communication with AWS IoT."""

    _TIMEOUT_s = 10
    """Timeout for discovering information."""

    _NUMBER_OF_THREADS = 5
    """Number of threads to be used to notify the listeners."""

    def __init__(self, client_name, device_certificate_path, \
        device_private_key_path, group_ca_path, core_info):
        """Constructor.

        AWSClient has to be instantiated through a call to the
        :meth:`edge_st_sdk.aws.aws_greengrass.AWSGreengrass.get_client` method.

        :param client_name: Name of the client, as it is on the cloud.
        :type client_name: str

        :param device_certificate_path: Relative path of the device's
            certificate stored on the core device.
        :type device_certificate_path: str

        :param device_private_key_path: Relative path of the device's private
            key stored on the core device.
        :type device_private_key_path: str

        :param group_ca_path: Relative path of the certification authority's
            certificate stored on the core device.
        :type group_ca_path: str

        :param core_info: Information related to the core of the group to which
            the client belongs.
        :type core_info: list

        :raises EdgeSTInvalidOperationException: is raised if the discovery of
            the core has not been completed yet, i.e. if the AWSClient has not
            been instantiated through a call to the
            :meth:`edge_st_sdk.aws.aws_greengrass.AWSGreengrass.get_client`
            method.
        """
        self._status = EdgeClientStatus.INIT
        """Status."""

        self._thread_pool = ThreadPoolExecutor(AWSClient._NUMBER_OF_THREADS)
        """Pool of thread used to notify the listeners."""

        self._listeners = []
        """List of listeners to the feature changes.
        It is a thread safe list, so a listener can subscribe itself through a
        callback."""

        # Check the client is created with the right pattern (Builder).
        if not edge_st_sdk.aws.aws_greengrass.AWSGreengrass.discovery_completed(
        ):
            raise EdgeSTInvalidOperationException('Amazon AWS clients must be ' \
                'obtained through a call to the \'get_client()\' method of an ' \
                '\'AWSGreengrass\' object.')

        # Saving informations.
        self._connected = False
        self._client_name = client_name
        self._core_info = core_info

        # Creating a shadow client.
        self._shadow_client = AWSIoTMQTTShadowClient(client_name)
        self._shadow_client.configureCredentials(group_ca_path,
                                                 device_private_key_path,
                                                 device_certificate_path)

        # Getting the underneath client and configurint it.
        self._client = self._shadow_client.getMQTTConnection()
        self._client.configureOfflinePublishQueueing(-1)  # Infinite queueing.
        self._client.configureDrainingFrequency(2)  # Draining: 2 Hz.

        # Creating a shadow handler with persistent subscription.
        self._shadow_handler = self._shadow_client.createShadowHandlerWithName(
            self._client_name, True)

        # Updating client.
        self._update_status(EdgeClientStatus.IDLE)

    def get_name(self):
        """Get the client name. 

        :returns: The client name, i.e. the name of the client.
        :rtype: str
        """
        return self._client_name

    def connect(self):
        """Connect to the core.

        :returns: True if the connection was successful, False otherwise.
        :rtype: bool
        """
        # Updating client.
        self._update_status(EdgeClientStatus.CONNECTING)

        # Connecting.
        if not self._connected:
            # Iterate through the connection options for the core and use the
            # first successful one.
            for connectivity_info in self._core_info.connectivityInfoList:
                self._current_host = connectivity_info.host
                self._current_port = connectivity_info.port
                self._shadow_client.configureEndpoint(self._current_host,
                                                      self._current_port)
                self._shadow_client.configureAutoReconnectBackoffTime(
                    1, 32, 20)
                self._shadow_client.configureConnectDisconnectTimeout(
                    self._TIMEOUT_s)
                self._shadow_client.configureMQTTOperationTimeout(
                    self._TIMEOUT_s / 2.0)
                try:
                    self._shadow_client.connect()
                    self._connected = True
                    break
                except BaseException as e:
                    self._connected = False
        if self._connected:
            self._update_status(EdgeClientStatus.CONNECTED)
        else:
            self._update_status(EdgeClientStatus.UNREACHABLE)

        return self._connected

    def disconnect(self):
        """Disconnect from the core."""
        # Updating client.
        self._update_status(EdgeClientStatus.DISCONNECTING)

        # Disconnecting.
        if self._connected:
            self._shadow_client.disconnect()
            self._connected = False

        # Updating client.
        self._update_status(EdgeClientStatus.DISCONNECTED)

    def publish(self, topic, payload, qos):
        """Publish a new message to the desired topic with the given quality of
        service.

        :param topic: Topic name to publish to.
        :type topic: str

        :param payload: Payload to publish (JSON formatted string).
        :type payload: str

        :param qos: Quality of Service. Could be "0" or "1".
        :type qos: int
        """
        if self._connected:
            self._client.publish(topic, payload, qos)

    def subscribe(self, topic, qos, callback):
        """Subscribe to the desired topic with the given quality of service and
        register a callback to handle the published messages.

        :param topic: Topic name to publish to.
        :type topic: str

        :param qos: Quality of Service. Could be "0" or "1".
        :type qos: int

        :param callback: Function to be called when a new message for the
            subscribed topic comes in.
        """
        if self._connected:
            self._client.subscribe(topic, qos, callback)

    def unsubscribe(self, topic):
        """Unsubscribe to the desired topic.

        :param topic: Topic name to unsubscribe to.
        :type topic: str
        """
        if self._connected:
            self._client.unsubscribe(topic)

    def get_shadow_state(self, callback, timeout_s):
        """Get the state of the shadow client.

        Retrieve the device shadow JSON document from the cloud by publishing an
        empty JSON document to the corresponding shadow topics.

        :param callback: Function to be called when the response for a shadow
            request comes back.

        :param timeout_s: Timeout in seconds to perform the request.
        :type timeout_s: int
        """
        if self._connected:
            self._shadow_handler.shadowGet(callback, timeout_s)

    def update_shadow_state(self, payload, callback, timeout_s):
        """Update the state of the shadow client.

        Update the device shadow JSON document string on the cloud by publishing
        the provided JSON document to the corresponding shadow topics.

        :param payload: JSON document string used to update the shadow JSON
            document on the cloud.
        :type payload: json

        :param callback: Function to be called when the response for a shadow
            request comes back.

        :param timeout_s: Timeout in seconds to perform the request.
        :type timeout_s: int
        """
        if self._connected:
            self._shadow_handler.shadowUpdate(payload, callback, timeout_s)

    def delete_shadow_state(self, callback, timeout_s):
        """Delete the state of the shadow client.
        
        Delete the device shadow from the cloud by publishing an empty JSON
        document to the corresponding shadow topics.

        :param callback: Function to be called when the response for a shadow
            request comes back.

        :param timeout_s: Timeout in seconds to perform the request.
        :type timeout_s: int
        """
        if self._connected:
            self._shadow_handler.shadowDelete(callback, timeout_s)

    def add_listener(self, listener):
        """Add a listener.
        
        :param listener: Listener to be added.
        :type listener: :class:`edge_st_sdk.edge_client.EdgeClientListener`
        """
        if listener is not None:
            with lock(self):
                if not listener in self._listeners:
                    self._listeners.append(listener)

    def remove_listener(self, listener):
        """Remove a listener.

        :param listener: Listener to be removed.
        :type listener: :class:`edge_st_sdk.edge_client.EdgeClientListener`
        """
        if listener is not None:
            with lock(self):
                if listener in self._listeners:
                    self._listeners.remove(listener)

    def _update_status(self, new_status):
        """Update the status of the client.

        :param new_status: New status.
        :type new_status: :class:`edge_st_sdk.edge_client.EdgeClientStatus`
        """
        old_status = self._status
        self._status = new_status
        for listener in self._listeners:
            # Calling user-defined callback.
            self._thread_pool.submit(
                listener.on_status_change(self, new_status.value,
                                          old_status.value))
Example #8
0
class Iota:
    # Device State
    outlet1 = "off"
    outlet2 = "off"
    motion = "false"
    temperature = 0.0
    sense = None

    thingEndpoint = "a3lybv9v64fkof.iot.us-west-2.amazonaws.com"
    awsDir = "/home/dennis/.aws"
    # awsDir = "/users/denni/aws"
    credentialFiles = (awsDir + "/aws-iot-root-ca.pem",
                       awsDir + "/b498bb82fa-private.pem.key",
                       awsDir + "/b498bb82fa-certificate.pem.crt")

    def __init__(self):

        logging.basicConfig(filename='iota.log', level=logging.DEBUG)
        #logging.basicConfig(stream=sys.__stdout__, level=logging.INFO)
        self.log = logging
        self.log.info('init(): creating an instance of Iota')
        self.connect()
        self.log.info('init(): retrieving AWS Shadow')
        self.shadow = self.client.createShadowHandlerWithName("iota", True)
        self.log.info('init(): registering delta callback')
        self.log.info('init(): Iota created')

        # Setup the Arduino Firmata interface
        self.log.info('init(): setting-up firmata')
        self.board = None
        for i in range(0, 10):
            if os.path.exists('/dev/ttyACM' + str(i)):
                self.log.info('init(): firmata: found serial device: ' +
                              '/dev/ttyACM' + str(i))
                self.board = Arduino('/dev/ttyACM' + str(i))
                break

        self.log.info('init(): getting iterator for board')
        it = util.Iterator(self.board)
        it.start()
        self.log.info('init(): started iterator for board')
        self.board.analog[0].enable_reporting()
        self.board.analog[1].enable_reporting()
        self.d7 = self.board.get_pin('d:7:i')
        self.d8 = self.board.get_pin('d:8:o')
        self.d9 = self.board.get_pin('d:9:o')
        self.log.info('init(): finished firmata setup')

    def __del__(self):
        self.log.info("del(): disconnecting")
        self.disconnect()

    def connect(self):
        self.log.info('init(): connecting to AWS Shadow')
        self.client = AWSIoTMQTTShadowClient("iota")
        self.client.configureEndpoint(self.thingEndpoint, 8883)
        self.client.configureCredentials(*self.credentialFiles)
        self.client.configureConnectDisconnectTimeout(10)  # 10 sec
        self.client.configureMQTTOperationTimeout(5)  # 5 sec
        self.client.connect()
        self.log.info('init(): connected to AWS Shadow')

    def disconnect(self):
        self.log.info('disconnect(): disconnecting device client from AWS')
        self.client.disconnect()
        self.log.info('disconnect(): disconnected device client from AWS')

    def onResponse(self, payload, responseStatus, token):
        try:
            self.log.info("iota.onResponse(): responseStatus: " +
                          responseStatus)
            # logging.debug("iota.onResponse(): responseStatus: " + responseStatus)

            response = json.loads(payload)
            pretty = json.dumps(response, indent=4)

            self.log.info("onResponse(): responseStatus: " +
                          str(responseStatus) + ", token: " + str(token) +
                          ", payload: " + str(pretty))
            # logging.debug("onResponse(): responseStatus: " + str(responseStatus) + ", token: " + str(token) + ", payload: " + str(ps))
            self.log.info("iota.onResponse(): payload: " + str(pretty))
        except Exception as ex:
            self.log.info("onResponse() exception: " + str(ex))

    def onDelta(self, payload, responseStatus, token):
        try:
            self.log.info("iota.onDelta(): responseStatus: " + responseStatus)

            changes = []
            deltas = json.loads(payload)
            pretty = json.dumps(deltas, indent=4)

            for delta in deltas['state'].keys():
                if delta == "outlet1":
                    value = deltas['state'][delta]
                    if value in ['on', 'off']:
                        self.setOutlet1(value)
                        changes.append((
                            delta,
                            value,
                        ))
                    else:
                        self.log.info(
                            'onDelta() invalid value for delta update to: ' +
                            str(value))
                elif delta == "outlet2":
                    value = deltas['state'][delta]
                    if value in ['on', 'off']:
                        self.setOutlet2(value)
                        changes.append((
                            delta,
                            value,
                        ))
                    else:
                        self.log.info(
                            'onDelta() invalid value for delta update to: ' +
                            str(value))
            if len(changes) > 0:
                self.log.info('onDelta() detected changes to: ' + str(changes))
                self.shadowUpdate(reported=changes)
            self.log.info("onDelta(): responseStatus: " + str(responseStatus) +
                          ", token: " + str(token) + ", payload: " +
                          str(pretty))
        except Exception as ex:
            self.log.info("onDelta() exception: " + str(ex))

    def shadowUpdate(self, reported=None, desired=None):
        self.log.info(
            'iota.shadowUpdate(): starting. preparing to update device shadow for reported: '
            + str(reported) + ", or desired: " + str(desired))
        update = {'state': {'reported': {}, 'desired': {}}}

        if reported is not None:
            for change in reported:
                update['state']['reported'][change[0]] = change[1]

        if desired is not None:
            for change in desired:
                update['state']['desired'][change[0]] = change[1]

        doc = json.dumps(update)
        self.log.info(
            'iota.shadowUpdate(): calling shadow.shadowUpdate. srcJSONPayload: '
            + doc)
        self.shadow.shadowUpdate(doc, onResponse, 5)
        self.log.info(
            'iota.shadowUpdate(): finished request to update device shadow')

    def getShadow(self):
        logging.info("getShadow(): retrieving shadow doc from AWS")
        shadow = self.shadow.shadowGet(onResponse, 5)
        return (shadow)

    def getOutlet1(self):
        logging.info("getOutlet1: getting value of outlet1")
        return self.outlet1

    def setOutlet1(self, value):
        if value in ['on', 'off']:
            logging.info("setOutlet1: setting value of outlet1 to: " + value)
            self.outlet1 = value
            if value == 'on':
                self.d8.write(False)
            else:
                self.d8.write(True)
        else:
            logging.error(
                "setOutlet1: invalid value given for setting outlet1: " +
                value)

    def getOutlet2(self):
        logging.info("getOutlet2: getting value of outlet2")
        return self.outlet2

    def setOutlet2(self, value):
        if value in ['on', 'off']:
            logging.info("setOutlet2 setting value of outlet2 to: " + value)
            self.outlet2 = value
            if value == 'on':
                self.d9.write(False)
            else:
                self.d9.write(True)
        else:
            logging.error(
                "setOutlet2: invalid value given for setting outlet2: " +
                value)

    def getTemp(self):
        logging.info("getTemp(): getting temperature through Firmata")
        return (str(round(self.board.analog[1].read() * 500)))

    def getRH(self):
        logging.info("getTemp(): getting relative humidity through Firmata")
        return (str(round(100 * self.board.analog[0].read())))

    def getMotion(self):
        logging.info("getTemp(): getting motion through Firmata")
        mot = self.d7.read()
        if mot == None:
            return 'na'
        else:
            return str(mot)

    def setMotion(self, value):
        if value in ['true', 'false']:
            logging.info("setMotion setting value of motion to: " + value)
            self.motion = value
        else:
            logging.error(
                "setMotion: invalid value given for setting motion: " + value)

    def getSense(self):
        logging.info("getSense(): getting values of all sensors")
        return ((
            self.getTemp(),
            self.getRH(),
            self.getMotion(),
        ))

    def listen(self):
        while True:

            # sense = (temp, rh, motion)
            sense = self.getSense()
            if self.sense is None or sense != self.sense:
                changes = []
                '''
                if self.sense[0] != sense[0]:
                    changes.append( ("temp", sense[0],) )
                if self.sense[1] != sense[1]:
                    changes.append( ("rh", sense[1],) )
                if self.sense[2] != sense[2]:
                    changes.append( ("motion", sense[2],) )
                '''
                changes.append((
                    "temp",
                    sense[0],
                ))
                changes.append((
                    "rh",
                    sense[1],
                ))
                changes.append((
                    "motion",
                    sense[2],
                ))
                self.shadowUpdate(reported=changes)
            self.sense = sense

            time.sleep(1)
Example #9
0
class Shadow():
    def __init__(self, canvas):
        self.canvas = canvas
        self._logger = canvas._logger
        self._hub_id = canvas.hub_yaml["canvas-hub"]["id"]
        self._myShadowClient = None
        self._myDeviceShadow = None
        self._connectThread = None

        self._initialize()

    ##############
    # PRIVATE
    ##############

    def _initialize(self):
        mosaic_path = os.path.expanduser('~') + "/.mosaicdata/"
        root_ca_path = mosaic_path + "root-ca.crt"
        private_key_path = mosaic_path + "private.pem.key"
        certificate_path = mosaic_path + "certificate.pem.crt"

        # Initialization
        self._myShadowClient = AWSIoTMQTTShadowClient(self._hub_id)
        self._myShadowClient.configureEndpoint(constants.SHADOW_CLIENT_HOST,
                                               8883)
        self._myShadowClient.configureCredentials(root_ca_path,
                                                  private_key_path,
                                                  certificate_path)

        # Configuration
        self._myShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
        self._myShadowClient.configureConnectDisconnectTimeout(15)  # 15 sec
        self._myShadowClient.configureMQTTOperationTimeout(5)  # 5 sec
        self._myShadowClient.onOnline = self._onOnline
        self._myShadowClient.onOffline = self._onOffline
        self._logger.info("Shadow client initialized")

    def _connectShadowClient(self):
        # Connect to AWS IoT
        try:
            self._logger.info("Connecting shadow client...")
            self._myShadowClient.connect(30)
            self._subscribeShadowDeviceToTopic()
        except:
            self._logger.info("Could not connect shadow client")

    def _subscribeShadowDeviceToTopic(self):
        # Create device shadow with persistent subscription to the topic (i.e current hub)
        try:
            self._logger.info(
                "Device shadow subscribing to current hub topic...")
            shadow_topic = "canvas-hub-" + self._hub_id
            self._myDeviceShadow = self._myShadowClient.createShadowHandlerWithName(
                shadow_topic, True)
            self._myDeviceShadow.shadowRegisterDeltaCallback(
                self._onDelta)  # initialize listener for device shadow deltas
            self._logger.info("Device shadow successfully subscribed to topic")
            self.getData()
        except:
            self._logger.info(
                "Could not subscribe device shadow to the current hub topic")

    def _startConnectThread(self):
        if self._connectThread is not None:
            self._stopConnectThread()

        self._connectThreadStop = False
        self._connectThread = threading.Thread(target=self._connectToAWS)
        self._connectThread.daemon = True
        self._connectThread.start()

    def _connectToAWS(self):
        while not self._connectThreadStop:
            self._connectShadowClient()
            time.sleep(30)

    def _stopConnectThread(self):
        self._connectThreadStop = True
        if self._connectThread and threading.current_thread(
        ) != self._connectThread:
            self._connectThread.join()
        self._connectThread = None

    def _handlePrint(self, payload):
        self._logger.info("Handling print download")
        self.canvas.downloadPrintFiles(payload["queuedPrint"])
        state_to_send_back = {
            "state": {
                "reported": {
                    "queuedPrint": None
                },
                "desired": {
                    "queuedPrint": None
                }
            }
        }
        self._myDeviceShadow.shadowUpdate(json.dumps(state_to_send_back),
                                          self._onUpdate, 10)

    def _handleUserListChanges(self, payload):
        self._logger.info("Handling user list delta")
        current_yaml_users = list(
            self.canvas.hub_yaml["canvas-users"])  # for Python 2 & 3
        delta_users = payload["userIds"]

        # if contents are not the same, get new list of registered users
        if not set(current_yaml_users) == set(delta_users):
            self._logger.info(
                "Content not the same. Updating yaml user list first.")
            if len(delta_users) < len(current_yaml_users):
                removed_user = str(
                    set(current_yaml_users).difference(set(delta_users)).pop())
                self.canvas.removeUserFromYAML(removed_user)

        users_to_report = delta_users
        reportedState = {"state": {"reported": {"userIds": users_to_report}}}
        self._myDeviceShadow.shadowUpdate(json.dumps(reportedState),
                                          self._onUpdate, 10)
        # if there are no linked users, disconnect shadow client
        if not self.canvas.hub_yaml[
                "canvas-users"] and self.canvas.aws_connection:
            self._myShadowClient.disconnect()

    def _handleChanges(self, payload):
        if "userIds" in payload:
            self._handleUserListChanges(payload)
        if "queuedPrint" in payload:
            self._handlePrint(payload)

    # CALLBACKS

    def _onGetShadowObj(self, payload, responseStatus, token):
        self._logger.info("GOT SHADOW OBJECT")
        payload = json.loads(payload)
        if responseStatus == "accepted" and "delta" in payload["state"]:
            delta = payload["state"]["delta"]
            self._handleChanges(delta)
        else:
            self._logger.info("No delta found in object. No action needed.")

    def _onDelta(self, payload, responseStatus, token):
        self._logger.info("RECEIVED DELTA")
        payload = json.loads(payload)
        self._handleChanges(payload["state"])

    def _onUpdate(self, payload, responseStatus, token):
        self._logger.info("SHADOW UPDATE RESPONSE")

    def _onOnline(self):
        self._logger.info("Shadow client is online")
        self.canvas.aws_connection = True
        self.canvas.checkAWSConnection()
        self._connectThreadStop = True

    def _onOffline(self):
        self._logger.info("Shadow client is offline")
        self.canvas.aws_connection = False
        self.canvas.checkAWSConnection()

    ##############
    # PUBLIC
    ##############

    def connect(self):
        self._startConnectThread()

    def getData(self):
        self._myDeviceShadow.shadowGet(self._onGetShadowObj, 10)

    def disconnect(self):
        self._myShadowClient.disconnect()
Example #10
0
class IoTClient:
    _redis = None

    def __init__(self):
        path = os.path.abspath(os.path.dirname(__file__))

        self._shadowC = AWSIoTMQTTShadowClient("shadow")
        self._shadowC.configureEndpoint(
            "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883)
        self._shadowC.configureCredentials(
            os.path.join(path, "credentials/aws/aws-root.pem"),
            os.path.join(path, "credentials/device/private.pem.key"),
            os.path.join(path, "./credentials/device/certificate.pem.crt"))
        self._shadowC.configureConnectDisconnectTimeout(10)
        self._shadowC.configureMQTTOperationTimeout(5)

        # For certificate based connection
        self._mqttC = AWSIoTMQTTClient("regular")
        self._mqttC.configureEndpoint(
            "a1g1flllk3y7ps.iot.ap-northeast-1.amazonaws.com", 8883)
        self._mqttC.configureCredentials(
            os.path.join(path, "credentials/aws/aws-root.pem"),
            os.path.join(path, "credentials/device/private.pem.key"),
            os.path.join(path, "./credentials/device/certificate.pem.crt"))

        self._mqttC.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        self._mqttC.configureDrainingFrequency(2)  # Draining: 2 Hz
        self._mqttC.configureConnectDisconnectTimeout(10)  # 10 sec
        self._mqttC.configureMQTTOperationTimeout(5)  # 5 sec

    def __del__(self):
        try:
            self._shadowC.disconnect()
            self._mqttC.disconnect()
        except Exception:
            pass

    def connect(self):
        self._redis = redis.Redis(host='localhost', port=6379)

        try:
            self._redis.get(
                "test")  # getting None returns None or throws an exception
        except (redis.exceptions.ConnectionError,
                redis.exceptions.BusyLoadingError):
            print("Failed to connect to Redis server")
            return False

        connected = self._shadowC.connect() and self._mqttC.connect()

        if connected:
            self._shadowD = self._shadowC.createShadowHandlerWithName(
                "Air-RME-test", True)

            self._shadowD.shadowGet(self._setStateCallback, 5)

            self._shadowD.shadowRegisterDeltaCallback(self._echoCallback)
        return connected

    def _setStateCallback(self, payload, responseStatus, token):
        self._state = json.loads(payload)
        reported = '{"state":{"reported":' + json.dumps(
            self._state["state"]["desired"]) + '}}'
        self._redis.rpush("order", json.dumps(self._state["state"]["desired"]))
        print(self._redis.lpop("order").decode('utf-8'))
        self._shadowD.shadowUpdate(reported, None, 5)

    def _echoCallback(self, payload, responseStatus, token):
        print('--- Update Received ---')
        print("Status: " + responseStatus)
        p = json.loads(payload)
        self._state["state"]["desired"] = {
            **self._state["state"]["desired"],
            **p["state"]
        }
        print(json.dumps(json.loads(payload), indent=4, sort_keys=True))
        print('--- End of Update ---')
        reported = '{"state":{"reported":' + json.dumps(
            self._state["state"]["desired"]) + '}}'

        self._redis.rpush("order", json.dumps(self._state["state"]["desired"]))
        self._shadowD.shadowUpdate(reported, None, 5)

    def publish(self, topic, message):
        self._mqttC.publish(topic, json.dumps(message), 0)

    def run(self):
        print("Trying to connect to MQTT broker...")

        if self.connect():
            print("Connected")

            lastTemp = 0
            lastHum = 0

            while True:
                humidity, temperature = sensor_data.get_temperature_info()

                if lastTemp != temperature or lastHum != humidity:
                    data = {"temp": temperature, "hum": humidity}

                    self.publish("/Air-RME-test/sensor", data)
                    lastTemp = temperature
                    lastHum = humidity

                time.sleep(1)
        else:
            print("Connection failed.")

        return
Example #11
0
class ShadowClient(object):

    client = None
    bot = None

    def __init__(self, client_id, end_point, root_ca, private_key, certificate):
        """

        :param client_id:
        :param end_point:
        :param root_ca:
        :param private_key:
        :param certificate:
        """
        self.client = AWSIoTMQTTShadowClient(client_id)
        self.client.configureEndpoint(end_point, 8883)
        self.client.configureCredentials(root_ca, private_key, certificate)
        self.client.configureAutoReconnectBackoffTime(2, 32, 20)
        self.client.configureConnectDisconnectTimeout(10)  # 10 sec
        self.client.configureMQTTOperationTimeout(5)  # 5 sec

    def connect(self):
        """
        接続処理
        :return: 結果(True:成功、False:失敗)
        """
        return self.client.connect()

    def create_shadow_handler_with_name(self, shadow_name):
        """
        デバイスShadowハンドラ作成
        :return: デバイスShadowオブジェクト
        """
        self.bot = self.client.createShadowHandlerWithName(shadow_name, True)

    def shadow_get(self, call_back):
        """
        Thing Shadowデータの最新データ取得
        :param call_back: レスポンスを取得するコールバック関数
        :return: なし
        """
        self.bot.shadowGet(call_back, 5)

    def shadow_update(self, payload, call_back):
        """
        Thing Shadowデータの更新
        :param payload: 送信データ
        :param call_back: レスポンスを取得するコールバック関数
        :return: なし
        """
        self.bot.shadowUpdate(payload, call_back, 5)

    def shadow_register_delta_callback(self, callback):
        """
        Thing Shadow deltaデータ発生時の処理登録
        :param callback: deltaデータ発生時のコールバック関数
        :return:
        """
        if self.bot:
            self.bot.shadowRegisterDeltaCallback(callback)

    def disconnect(self):
        """
        切断処理
        :return: 結果(True:成功、False:失敗)
        """
        return self.client.disconnect()
Example #12
0
def updateDeviceState(device_seq, device_state):
    host = "a3mfkf3z93nqt8.iot.us-west-2.amazonaws.com"
    rootCAPath = "certs/root-CA.crt"
    certificatePath = "certs/team55device%s.cert.pem" % (device_seq+1)
    privateKeyPath = "certs/team55device%s.private.key" % (device_seq+1)
    clientId = "team55"

    thingName = "team55device%s" % (device_seq+1)

    # Custom Shadow callback
    def customShadowCallback_Update(payload, responseStatus, token):
        # payload is a JSON string ready to be parsed using json.loads(...)
        # in both Py2.x and Py3.x
        if responseStatus == "timeout":
            print("Update request " + token + " time out!")
        if responseStatus == "accepted":
            payloadDict = json.loads(payload)
            print("~~~~~~~~~~~~~~~~~~~~~~~")
            print("Update request with token: " + token + " accepted!")
            print("property: " + json.dumps(payloadDict["state"]["desired"]))
            print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
        if responseStatus == "rejected":
            print("Update request " + token + " rejected!")

    def customShadowCallback_Delete(payload, responseStatus, token):
        if responseStatus == "timeout":
            print("Delete request " + token + " time out!")
        if responseStatus == "accepted":
            print("~~~~~~~~~~~~~~~~~~~~~~~")
            print("Delete request with token: " + token + " accepted!")
            print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
        if responseStatus == "rejected":
            print("Delete request " + token + " rejected!")

    # logging
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)

    # Init AWSIoTMQTTShadowClient
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    # AWSIoTMQTTShadowClient configuration
    myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
    myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

    myAWSIoTMQTTShadowClient.connect()

    # Create a deviceShadow with persistent subscription
    deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)

    # Delete shadow JSON doc
    deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

    deviceShadowHandler.shadowUpdate(json.dumps({"state": {"desired": device_state}}), customShadowCallback_Update, 5)

    time.sleep(5)

    myAWSIoTMQTTShadowClient.disconnect()