def is_edge():
    """Determine is edge or not. Return bool"""
    try:
        IoTHubModuleClient.create_from_edge_environment()
        return True
    except:
        return False
Exemple #2
0
def is_edge():
    """is edge: bool"""
    try:
        IoTHubModuleClient.create_from_edge_environment()
        return True
    except:
        return False
Exemple #3
0
def is_edge():
    """is_edge.
    """
    try:
        IoTHubModuleClient.create_from_edge_environment()
        return True
    except Exception:
        return False
def is_edge() -> bool:
    """is_edge.

    Returns:
        bool: is_edge
    """
    try:
        IoTHubModuleClient.create_from_edge_environment()
        return True
    except:
        return False
def is_edge():
    """is_edge.
    """
    try:
        IoTHubModuleClient.create_from_edge_environment()
        return True
    except Exception:
        IS_K8S = os.environ.get("IS_K8S", "false")
        if IS_K8S == "true":
            return True
        else:
            return False
Exemple #6
0
def main(imageProcessingEndpoint):
    try:
        print(
            "Simulated camera module for Azure IoT Edge. Press Ctrl-C to exit."
        )

        try:
            global CLIENT
            CLIENT = IoTHubModuleClient.create_from_edge_environment()
        except Exception as iothub_error:
            print("Unexpected error {} from IoTHub".format(iothub_error))
            return

        print(
            "The sample is now sending images for processing and will indefinitely."
        )

        while True:
            imagePath = get_image_from_blob()
            classification = sendFrameForProcessing(imagePath,
                                                    imageProcessingEndpoint)
            if classification:
                send_to_hub(classification)
            time.sleep(10)
            os.remove(imagePath)

    except KeyboardInterrupt:
        print("IoT Edge module sample stopped")
def create_client():
    # Inputs/Outputs are only supported in the context of Azure IoT Edge and module client
    # The module client object acts as an Azure IoT Edge module and interacts with an Azure IoT Edge hub
    client = IoTHubModuleClient.create_from_edge_environment()

    # define behavior for receiving a message on inputs 1 and 2
    def message_handler(message):
        if message.input_name == "input1":
            print("Message received on INPUT 1")
            print("the data in the message received was ")
            print(message.data)
            print("custom properties are")
            print(message.custom_properties)
        elif message.input_name == "input2":
            print("Message received on INPUT 2")
            print("the data in the message received was ")
            print(message.data)
            print("custom properties are")
            print(message.custom_properties)
        else:
            print("message received on unknown input")

    # set the message handler on the client
    client.on_message_received = message_handler

    return client
    def __init__(self, rtsp, part_id=None, inference=False):
        if rtsp == '0': self.rtsp = 0
        elif rtsp == '1': self.rtsp = 1
        else: self.rtsp = rtsp
        self.part_id = part_id

        self.last_active = time.time()
        self.status = 'init'
        self.last_img = None
        self.cur_img_index = 0
        self.last_get_img_index = 0
        self.id = id(self)

        self.mutex = threading.Lock()
        self.predictions = []
        self.inference = inference

        try:
            self.iot = IoTHubModuleClient.create_from_edge_environment()
        except:
            self.iot = None

        print('inference', self.inference)
        print('iot', self.iot)

        def _listener(self):
            if not self.inference: return
            while True:
                if self.last_active + 10 < time.time():
                    print('[INFO] stream finished')
                    break
                sys.stdout.flush()
                res = requests.get('http://' + inference_module_url() +
                                   '/prediction')

                self.mutex.acquire()
                self.predictions = res.json()
                self.mutex.release()
                time.sleep(0.02)
                #print('received p', self.predictions)

                #inference = self.iot.receive_message_on_input('inference', timeout=1)
                #if not inference:
                #    self.mutex.acquire()
                #    self.bboxes = []
                #    self.mutex.release()
                #else:
                #    data = json.loads(inference.data)
                #    print('receive inference', data)
                #    self.mutex.acquire()
                #    self.bboxes = [{
                #        'label': data['Label'],
                #        'confidence': data['Confidence'] + '%',
                #        'p1': (data['Position'][0], data['Position'][1]),
                #        'p2': (data['Position'][2], data['Position'][3])
                #    }]
                #    self.mutex.release()

        #if self.iot:
        threading.Thread(target=_listener, args=(self, )).start()
def create_client():
    client = IoTHubModuleClient.create_from_edge_environment()

    # define function for handling received messages
    def receive_message_handler(message):
        # NOTE: This function only handles messages sent to "input1".
        # Messages sent to other inputs or to the default will be discarded.
        global RECEIVED_MESSAGES
        if message.input_name == "input1":
            RECEIVED_MESSAGES += 1
            print("Message received on input1")
            print("    Data: <<{}>>".format(message.data))
            print("    Properties: {}".format(message.custom_properties))
            print("    Total calls received: {}".format(RECEIVED_MESSAGES))
            print("Forwarding message to output1")
            client.send_message_to_output(message, "output1")
            print("Message successfully forwarded")
        else:
            print("Message received on unknown input: {}".format(
                message.input_name))

    try:
        # Set handler
        client.on_message_received = receive_message_handler
    except:
        # Cleanup
        client.shutdown()

    return client
Exemple #10
0
def main():
    try:
        print("\nPython {}\n".format(sys.version))
        print("IoT Hub Client for Python")

        client = IoTHubModuleClient.create_from_edge_environment()

        # Begin listening for messages
        message_listener_thread = threading.Thread(
            target=receive_message_listener, args=(client, ))
        message_listener_thread.daemon = True
        message_listener_thread.start()

        print("Starting the IoT Hub Python sample...")
        print(
            "The sample is now waiting for messages and will indefinitely.  Press Ctrl-C to exit. "
        )

        while True:
            time.sleep(1000)

    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
    except:
        print("Unexpected error from IoTHub")
        return
 def connect(self, transport_type, connection_string, cert):
     print("connecting using " + transport_type)
     auth_provider = auth.from_connection_string(connection_string)
     if "GatewayHostName" in connection_string:
         auth_provider.ca_cert = cert
     self.client = IoTHubModuleClient.from_authentication_provider(
         auth_provider, transport_type)
     self.client.connect()
def init():
    # Inputs/Ouputs are only supported in the context of Azure IoT Edge and module client
    # The module client object acts as an Azure IoT Edge module and interacts with an Azure IoT Edge hub
    module_client = IoTHubModuleClient.create_from_edge_environment()

    # connect the client.
    module_client.connect()

    return module_client
Exemple #13
0
def iothub_client_run():
    try:
        module_client = IoTHubModuleClient.create_from_edge_environment()

        twin_update_listener_thread = threading.Thread(
            target=twin_update_listener, args=(module_client, ))
        twin_update_listener_thread.daemon = True
        twin_update_listener_thread.start()
    except:
        print("[WARNING] Unexpected error:", sys.exc_info()[0], flush=True)
        print('[WARNING] No IoT Edge Environment', flush=True)
def get_iothub_module_client(raise_exception=False):
    try:
        iot = IoTHubModuleClient.create_from_edge_environment()
        return iot
    except KeyError as key_error:
        logger.error(key_error)
    except OSError as os_error:
        logger.error(os_error)
    except Exception:
        logger.exception("Unexpected error")
    return None
Exemple #15
0
def iothub_client_sample_run():
    try:
        module_client = IoTHubModuleClient.create_from_connection_string(CONNECTION_STRING)

        twin_update_listener_thread = threading.Thread(target=twin_update_listener, args=(module_client,))
        twin_update_listener_thread.daemon = True
        twin_update_listener_thread.start()

        while True:
            time.sleep(1000000)

    except KeyboardInterrupt:
        print("IoTHubModuleClient sample stopped")
    def __init__(
            self,
            messageTimeout,
            verbose):
        '''
        Communicate with the Edge Hub

        :param int messageTimeout: the maximum time in milliseconds until a message times out. The timeout period starts at IoTHubClient.send_event_async. By default, messages do not expire.
        :param IoTHubTransportProvider protocol: Choose HTTP, AMQP or MQTT as transport protocol.  Currently only MQTT is supported.
        :param bool verbose: set to true to get detailed logs on messages
        '''
        self.messageTimeout = messageTimeout
        self.client = IoTHubModuleClient.create_from_edge_environment()
def main(imagePath, imageProcessingEndpoint):
    try:
        print(
            "Simulated camera module for Azure IoT Edge. Press Ctrl-C to exit."
        )

        try:
            global CLIENT
            CLIENT = IoTHubModuleClient.create_from_edge_environment()
        except Exception as iothub_error:
            print("Unexpected error {} from IoTHub".format(iothub_error))
            return

        print(
            "The sample is now sending images for processing and will indefinitely."
        )

        while True:
            # Get image from HomeAssistant
            url = CAMERA_CAPTURE_URL
            response = requests.get(url, stream=True)
            with open(imagePath, 'wb') as out_file:
                shutil.copyfileobj(response.raw, out_file)
            del response

            # Process Image
            classification = sendFrameForProcessing(imagePath,
                                                    imageProcessingEndpoint)

            # find Active Probablity
            probability = findprobablity("active", json.loads(classification))

            # update MQTT sensor
            client = mqtt.Client()
            client.username_pw_set(MQTTUSER, MQTTPASSWORD)
            client.connect(MQTTBROKER, 1883, 60)
            if float(probability) > float(PROBABILITY_THRESHOLD):
                client.publish("home/alfresco/image_processing_sensor/state",
                               "on")
            else:
                client.publish("home/alfresco/image_processing_sensor/state",
                               "off")
            client.disconnect()

            # send to IoT Hub
            send_to_hub(classification)
            time.sleep(15)

    except KeyboardInterrupt:
        print("IoT Edge module sample stopped")
Exemple #18
0
async def main():
    global module_client
    try:
        VIDEO_PATH = os.getenv('Video', '0')
        PREDICT_THRESHOLD = os.getenv('Threshold', .75)
        IMAGE_PROCESSING_ENDPOINT = os.getenv('AiEndpoint',
                                              'http://localhost:80/image')
        AZURE_SPEECH_SERVICES_KEY = os.getenv(
            'azureSpeechServicesKey', '2f57f2d9f1074faaa0e9484e1f1c08c1')
        SPEECH_MAP_FILENAME = os.getenv('SpeechMapFilename',
                                        'speech_map_australian.json')

        # The client object is used to interact with your Azure IoT hub.
        module_client = IoTHubModuleClient.create_from_edge_environment()

        module_client.connect()

    except ValueError as error:
        print(error)
        sys.exit(1)

    initialise(VIDEO_PATH, AZURE_SPEECH_SERVICES_KEY, PREDICT_THRESHOLD,
               IMAGE_PROCESSING_ENDPOINT, SPEECH_MAP_FILENAME)
Exemple #19
0
#from tracker import Tracker
from scenarios import PartCounter, DefeatDetection, DangerZone, Detection
from utility import draw_label

import logging

DETECTION_TYPE_NOTHING = 'nothing'
DETECTION_TYPE_SUCCESS = 'success'
DETECTION_TYPE_UNIDENTIFIED = 'unidentified'
DETECTION_BUFFER_SIZE = 10000

# for Retraining
UPLOAD_INTERVAL = 5

try:
    iot = IoTHubModuleClient.create_from_edge_environment()
except:
    iot = None

is_edge = False
try:
    IoTHubModuleClient.create_from_edge_environment()
    is_edge = True
except:
    pass


class Stream():
    def __init__(self, cam_id, model, sender, cam_type="video_file", cam_source='./sample_video/video.mp4'):
        self.cam_id = cam_id
        self.model = model
 def connect_from_environment(self, transport_type):
     print("connecting from environment")
     auth_provider = auth.from_environment()
     self.client = IoTHubModuleClient.from_authentication_provider(
         auth_provider, transport_type)
     self.client.connect()
Exemple #21
0
 async def __init__(self):
     # The client object is used to interact with your Azure IoT hub.
     module_client = IoTHubModuleClient.create_from_edge_environment()
     await self.client.connect()
Exemple #22
0
def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubModuleClient.create_from_edge_environment()
    return client
def main():
    try:
        if not sys.version >= "3.5.3":
            raise Exception(
                "The sample requires python 3.5.3+. Current version of Python: %s"
                % sys.version)
        print("IoT Hub Client for Python")

        # The client object is used to interact with your Azure IoT hub.
        module_client = IoTHubModuleClient.create_from_edge_environment()

        # connect the client.
        module_client.connect()

        # define behavior for receiving an input message on input1
        def input1_listener(module_client, param_lock):
            count = 0
            while True:
                print("Waiting for message")
                input_message = module_client.receive_message_on_input(
                    "input1")  # blocking call
                print("the data in the message received on input1 was ")
                print(input_message.data)
                print("custom properties are")
                print(input_message.custom_properties)
                content = json.loads(input_message.data.decode('utf8'))
                if 'command' in content:
                    if content['command'] == "ShowText":
                        stShowText(content['payload'], param_lock)
                    elif content['command'] == "ShowImage":
                        stShowImage(content['payload'], param_lock)
                    elif content['command'] == "SetOptions":
                        stSetOptions(content['payload'], param_lock)
                    elif content['command'] == "Clear":
                        stClear(content['payload'], param_lock)
                elif 'timeCreated' in content:
                    if (count % 10) == 0:
                        temp = content['temperature']
                        humi = content['humidity']
                        pres = content['pressure']
                        adjustColor(temp, humi, pres, param_lock)

        def direct_method_listener(module_client, param_lock):
            while True:
                try:
                    print("waiting for method invocation...")
                    methodRequest = module_client.receive_method_request()
                    print("received method invocation - '{}'({})".format(
                        methodRequest.name, methodRequest.payload))
                    response = {}
                    response_status = 200
                    if methodRequest.name == "ShowText":
                        stShowText(methodRequest.payload, param_lock)
                    elif methodRequest.name == "ShowImage":
                        stShowImage(methodRequest.payload, param_lock)
                    elif methodRequest.name == "SetOptions":
                        stSetOptions(methodRequest.payload, param_lock)
                    elif methodRequest.name == "Clear":
                        stClear(methodRequest.payload, param_lock)
                    else:
                        response['message'] = "bad method name"
                        response_status = 404
                    response = MethodResponse(methodRequest.request_id,
                                              response_status,
                                              payload=response)
                    module_client.send_method_response(response)
                except Exception as error:
                    print("exception happens - {}".format(error))

        print("The sample is now waiting for messages. ")

        param_lock = threading.Lock()
        message_thread = threading.Thread(target=input1_listener,
                                          args=(module_client, param_lock))
        message_thread.daemon = True
        message_thread.start()
        method_thread = threading.Thread(target=direct_method_listener,
                                         args=(module_client, param_lock))
        method_thread.daemon = True
        method_thread.start()

        reported = {'application': 'sensehat-led'}
        module_client.patch_twin_reported_properties(reported)

        while True:
            time.sleep(1)

        # Finally, disconnect
        module_client.disconnect()

    except Exception as e:
        print("Unexpected error %s " % e)
        raise
async def main(data_folder_path):
    try:
        if not sys.version >= "3.5.3":
            raise Exception(
                "The sample requires python 3.5.3+. Current version of Python: %s"
                % sys.version)
        print("IoT Hub Client for Python")

        if sys.version < "3.6.0":
            from classify_csv import SoundClassifier
        else:
            from classify_wav import SoundClassifier

        # The client object is used to interact with your Azure IoT hub.
        module_client = IoTHubModuleClient.create_from_edge_environment()

        # connect the client.
        module_client.connect()
        print("Connected to Edge Runtime.")

        currentTwin = module_client.get_twin()
        print('Resolve current spec...')
        predictSpec = currentTwin['desired']
        sound_classifer = SoundClassifier()
        parse_desired_property_request(predictSpec, module_client,
                                       sound_classifer)

        # initialize sound classifier

        for file in os.listdir('model'):
            if file.rfind('.h5') > 0:
                model_file_path = os.path.join('model', file)
                sound_classifer.load_model(model_file_path)

        async def desired_twin_update_listener(module_client, soundclassifier):
            print('Get current desired properties...')
            currentTwin = module_client.get_twin()
            print('Resolve current spec...')
            predictSpec = currentTwin['desired']
            parse_desired_property_request(predictSpec, module_client,
                                           sound_classifer)

        # define behavior for receiving an input message on input_sound_data
        async def input_sound_data_listener(module_client, soundclassifier):
            while True:
                print("waiting message from 'input_sound_data'")
                input_message = module_client.receive_message_on_input(
                    "input_sound_data")  # blocking call
                try:
                    print("custom properties are")
                    print(input_message.custom_properties)
                    if 'message-source' in input_message.custom_properties:
                        if input_message.custom_properties[
                                'message-source'] == 'sound-capturing':
                            print(
                                "the data in the message received on input_sound_data was "
                            )
                            tmpFileName = 'data' + soundclassifier.get_fileformat(
                            )
                            targetDataFile = input_message.custom_properties[
                                'data-file']
                            if targetDataFile.endswith(
                                    soundclassifier.get_fileformat()):
                                with open(tmpFileName, 'wb') as tf:
                                    tf.write(input_message.data)
                                    print('Saved content in {} as {}'.format(
                                        targetDataFile, tmpFileName))
                                predictedResult = soundclassifier.predict(
                                    tmpFileName)
                                print('Classification Succeeded')
                                os.remove(tmpFileName)

                                outputMessageJson = {
                                    'timestamp':
                                    '{0:%Y/%m/%dT%H:%M:%S.%f}'.format(
                                        datetime.datetime.now()),
                                    'channels': []
                                }
                                for p in predictedResult.keys():
                                    #                                    print('channel:{},predicted:{} as type:{}'.format(p,predictedResult[p],type(predictedResult[p])))
                                    channelPredicted = {}
                                    channelPredicted['channel'] = p
                                    if soundclassifier.get_fileformat(
                                    ) == 'csv':
                                        channelPredicted['predicted'] = []
                                        cindex = 1
                                        for cdata in predictedResult[p]:
                                            channelPredicted[
                                                'predicted'].append({
                                                    'chunk':
                                                    cindex,
                                                    'result':
                                                    cdata
                                                })
                                        outputMessageJson['channels'].append(
                                            channelPredicted)
                                    else:  # wav
                                        channelPredicted[
                                            'predicted'] = predictedResult[p]
                                content = json.dumps(outputMessageJson)
                                message = Message(content)
                                message.custom_properties[
                                    'message-source'] = 'sound-classifier'
                                module_client.send_message_to_output(
                                    content, "output_classified")
                                print('sent result:{} to {}'.format(content),
                                      'output_classified')
                except Exception as e:
                    print('Failed to classify - {0}'.format(e))

        # define behavior for halting the application
        def stdin_listener():
            while True:
                try:
                    selection = input("Press Q to quit\n")
                    if selection == "Q" or selection == "q":
                        print("Quitting...")
                        break
                except:
                    time.sleep(10)

        # Schedule task for C2D Listener
        listeners = asyncio.gather(
            input_sound_data_listener(module_client, sound_classifer),
            desired_twin_update_listener(module_client, sound_classifer))

        print("The sample is now waiting for messages. ")

        # Run the stdin listener in the event loop
        loop = asyncio.get_event_loop()
        user_finished = loop.run_in_executor(None, listeners)

        # Wait for user to indicate they are done listening for messages
        await user_finished

        # Cancel listening
        listeners.cancel()

        # Finally, disconnect
        module_client.disconnect()

    except Exception as e:
        print("Unexpected error %s " % e)
        raise
  def __init__(self):
    self.client = IoTHubModuleClient.create_from_edge_environment()

    # set the time until a message times out
    self.output_queue = "iotHub"
    def __init__(self, rtsp, part_id=None, inference=False):
        if rtsp == "0":
            self.rtsp = 0
        elif rtsp == "1":
            self.rtsp = 1
        else:
            self.rtsp = rtsp
        self.part_id = part_id

        self.last_active = time.time()
        self.status = "init"
        self.last_img = None
        self.cur_img_index = 0
        self.last_get_img_index = 0
        self.id = id(self)

        self.mutex = threading.Lock()
        self.predictions = []
        self.inference = inference
        self.iot = None
        self.keep_alive = time.time()
        self.cap = None
        try:
            self.iot = IoTHubModuleClient.create_from_edge_environment()
        except KeyError as key_error:
            logger.error(key_error)
        except OSError as os_error:
            logger.error(os_error)
        except Exception:
            logger.exception("Unexpected error")

        logger.info("inference %s", self.inference)
        logger.info("iot %s", self.iot)

        def _listener(self):
            if not self.inference:
                return
            while True:
                if self.last_active + 10 < time.time():
                    logger.info("stream finished")
                    break
                sys.stdout.flush()
                res = requests.get("http://" + inference_module_url() +
                                   "/prediction")

                self.mutex.acquire()
                self.predictions = res.json()
                self.mutex.release()
                time.sleep(0.02)
                # print('received p', self.predictions)

                # inference = self.iot.receive_message_on_input('inference',
                #                                               timeout=1)
                # if not inference:
                #    self.mutex.acquire()
                #    self.bboxes = []
                #    self.mutex.release()
                # else:
                #    data = json.loads(inference.data)
                #    print('receive inference', data)
                #    self.mutex.acquire()
                #    self.bboxes = [{
                #        'label': data['Label'],
                #        'confidence': data['Confidence'] + '%',
                #        'p1': (data['Position'][0], data['Position'][1]),
                #        'p2': (data['Position'][2], data['Position'][3])
                #    }]
                #    self.mutex.release()

        # if self.iot:
        threading.Thread(target=_listener, args=(self,)).start()
async def main(micCapture):
    try:
        if not sys.version >= "3.5.3":
            raise Exception(
                "The sample requires python 3.5.3+. Current version of Python: %s"
                % sys.version)
        print("IoT Hub Client for Python version - {}".format(sys.version))

        fileUpdater = BlobFileUpdater(BLOB_ON_EDGE_MODULE,
                                      BLOB_ON_EDGE_ACCOUNT_NAME,
                                      BLOB_ON_EDGE_ACCOUNT_KEY,
                                      SOUND_CONTAINER_NAME, IOTEDGE_DEVICEID)
        try:
            await fileUpdater.initialize()
            print('fileUpdater initialize completed.')
        except Exception as e:
            print(
                'Exception happens during fileUpdater initialize - {}'.format(
                    e))

        # The client object is used to interact with your Azure IoT hub.
        module_client = IoTHubModuleClient.create_from_edge_environment()

        # connect the client.
        module_client.connect()
        print('Connected to edge runtime.')

        if micCapture.getCurrentMicSpec():
            module_client.patch_twin_reported_properties(
                micCapture.getCurrentMicSpec())

        statusChangeListener = CaptureStateChangeListener(
            module_client, IOTEDGE_DEVICEID)

        async def desired_twin_update_listener(module_client, capture):
            print('Get current desired properties...')
            currentTwin = module_client.get_twin()
            print('Resolve current spec...')
            captureSpec = resolveCaptureSetting(currentTwin['desired'])
            capturingFileUpdater = None
            if captureSpec.CLASSIFY_ON_EDGE:
                print("AI on Edge mode: ON")
                capturingFileUpdater = AIonEdgeFileUpdater(
                    module_client, IOTEDGE_DEVICEID, captureSpec)
                if captureSpec.CLASSIFY_ON_EDGE_UPLOAD:
                    print(" with Blob on Edge uploader")
                    capturingFileUpdater.Forwarder = BlobFileUpdater(
                        BLOB_ON_EDGE_MODULE, BLOB_ON_EDGE_ACCOUNT_NAME,
                        BLOB_ON_EDGE_ACCOUNT_KEY, SOUND_CONTAINER_NAME,
                        IOTEDGE_DEVICEID)
            else:
                print("AI on Edge mode: OFF")
                capturingFileUpdater = BlobFileUpdater(
                    BLOB_ON_EDGE_MODULE, BLOB_ON_EDGE_ACCOUNT_NAME,
                    BLOB_ON_EDGE_ACCOUNT_KEY, SOUND_CONTAINER_NAME,
                    IOTEDGE_DEVICEID)
            while True:
                try:
                    soundCaptureExecuter = SoundCaptureExecuter(capture)
                    if (captureSpec.CAPTURE_ORDER):
                        print('Capturing on - capture thread starting...')
                        soundCaptureExecuter.start(captureSpec,
                                                   SOUND_DATA_FOLDER,
                                                   capturingFileUpdater,
                                                   statusChangeListener)
                    else:
                        print("Capturing off...")
                    print(
                        'Waiting for module twin desired properties updated...'
                    )
                    patch = module_client.receive_twin_desired_properties_patch(
                    )  # blocking call
                    print("Twin patch received: - {}".format(patch))
                    captureSpec = resolveCaptureSetting(patch)
                    await soundCaptureExecuter.stop()

                    print('Current capture order is {}'.format(
                        captureSpec.CAPTURE_ORDER))
                except Exception as e:
                    print('desired_twin_update_listener exception - {}'.format(
                        e))

        # define behavior for halting the application
        async def stdin_listener():
            while True:
                try:
                    selection = input("Press Q to quit\n")
                    if selection == "Q" or selection == "q":
                        await micCapture.stopCapture()
                        print("Quitting...")
                        break
                except:
                    time.sleep(10)

        # Schedule task for C2D Listener
        print('try to get device twin')
        dtwin = module_client.get_twin()
        print('current twin - {}'.format(dtwin['desired']))

        listeners = asyncio.gather(
            desired_twin_update_listener(module_client, micCapture))

        print(
            "The sample is now waiting for messages and module twin update. ")

        # Run the stdin listener in the event loop
        loop = asyncio.get_event_loop()
        user_finished = loop.run_in_executor(None, stdin_listener)

        # Wait for user to indicate they are done listening for messages
        await user_finished

        print('executing loop exited')

        # Cancel listening
        listeners.cancel()

        # Finally, disconnect
        module_client.disconnect()
        print('IoT Hub connection is disconnected')

    except Exception as e:
        print("Unexpected error %s " % e)
        raise
async def main(videoPath, fileUploader):
    global uploadCycleSecKey, uploadCycleSec, quitFlag
    try:
        if not sys.version >= "3.5.3":
            raise Exception(
                "The sample requires python 3.5.3+. Current version of Python: %s"
                % sys.version)
        print("IoT Hub Client for Python")

        # The client object is used to interact with your Azure IoT hub.
        module_client = IoTHubModuleClient.create_from_edge_environment()

        # connect the client.
        module_client.connect()

        currentTwin = module_client.get_twin()
        dtwin = currentTwin['desired']
        if uploadCycleSecKey in dtwin:
            uploadCycleSec = dtwin[uploadCycleSecKey]
            updateReportedTwin(module_client)

        # define behavior for receiving an input message on input1
        def twin_patch_listener(module_client, param_lock):
            global uploadCycleSec
            print("twin patch listener started.")
            while True:
                data = module_client.receive_twin_desired_properties_patch(
                )  # blocking call
                print("Received desired properties updated.")
                if uploadCycleSecKey in data:
                    param_lock.acquire()
                    uploadCycleSec = data[uploadCycleSecKey]
                    param_lock.release()
                    print("Updated {}={}".format(uploadCycleSecKey,
                                                 uploadCycleSec))
                    updateReportedTwin(module_client)
                param_lock.acquire()
                isBreak = quitFlag
                param_lock.release()
                if isBreak:
                    print("twin patch listener will be finished")
                    break

        async def upload_photo_handler(videoPath, uploader, module_client,
                                       param_lock):
            global PHOTO_DATA_FOLDER, uploadCycleSec, uploadStared, uploadNotifyOutputName, uploadNotifyStatus
            await uploader.initialize()
            print("upload photo handler started.")
            try:
                print("creating VideoStream")
                #                cap = cv2.VideoStream(int(videoPath))
                cap = cv2.VideoCapture(int(videoPath))
                print("...Created")
                time.sleep(1)
                if cap.isOpened():
                    print("VideoCapture has been opened")
                else:
                    print("VideoCapture has not been opened")
                while True:
                    param_lock.acquire()
                    sleepTime = uploadCycleSec
                    isUpload = uploadStared
                    isNotify = uploadNotifyStatus
                    param_lock.release()

                    time.sleep(sleepTime)
                    if isUpload:
                        now = datetime.datetime.now()
                        photoFileName = 'photo-{0:%Y%m%d%H%M%S%f}'.format(
                            now) + '.jpg'
                        filename = os.path.join(PHOTO_DATA_FOLDER,
                                                photoFileName)
                        print("Try to take photo - name={}".format(filename))
                        ret, frame = cap.read()
                        cv2.imwrite(filename, frame)
                        print("Saved photo file")
                        await uploader.uploadFile(filename)
                        os.remove(filename)
                        if isNotify:
                            notifyMsg = "{\"timestamp\":\"%s\",\"filename\":\"%s\"}"
                            msg = notifyMsg % (datetime.datetime.utcnow().
                                               isoformat(), photoFileName)
                            sendMsg = Message(msg)
                            module_client.send_message_to_output(
                                sendMsg, uploadNotifyOutputName)
                    else:
                        print("Waiting for start")
                    param_lock.acquire()
                    isBreak = quitFlag
                    param_lock.release()
                    if isBreak:
                        print("upload photo handler will be finished")
                        break

            except Exception as error:
                print('upload photo handler exception - {}'.format(error))

        def direct_method_listener(module_client, param_lock):
            global uploadStared, uploadNotifyStatus
            while True:
                try:
                    print("waiting for method invocation...")
                    methodRequest = module_client.receive_method_request()
                    print("received method invocation - '{}'({})".format(
                        methodRequest.name, methodRequest.payload))
                    response = {}
                    response_status = 200
                    if methodRequest.name == "Start":
                        response['message'] = "Upload started."
                        param_lock.acquire()
                        uploadStared = True
                        if (methodRequest.payload is None) == False:
                            if uploadNotifyStatusKey in methodRequest.payload:
                                uploadNotifyStatus = methodRequest.payload[
                                    uploadNotifyStatusKey]
                            else:
                                response[
                                    'message'] = "payload should be '{\"" + uploadCycleSecKey + "\": true|false}"
                        param_lock.release()
                        print("Received - Start order")
                        if uploadNotifyStatus:
                            print("  with notofication")
                        updateReportedTwin(module_client)
                    elif methodRequest.name == "Stop":
                        param_lock.acquire()
                        uploadStared = False
                        param_lock.release()
                        response['message'] = "Upload stopped."
                        print("Received - Stop order")
                        updateReportedTwin(module_client)
                    else:
                        response['message'] = "bad method name"
                        response_status = 404
                        print("Bad Method Request!")
                except Exception as error:
                    print("exception happens - {}".format(error))
                    response['message'] = "Exception - {}".format(error)
                methodResponse = MethodResponse(methodRequest.request_id,
                                                response_status,
                                                payload=response)
                module_client.send_method_response(methodResponse)

        param_lock = threading.Lock()

        twinThread = threading.Thread(target=twin_patch_listener,
                                      args=(module_client, param_lock))
        twinThread.daemon = True
        twinThread.start()

        methodThread = threading.Thread(target=direct_method_listener,
                                        args=(module_client, param_lock))
        methodThread.daemon = True
        methodThread.start()

        #        uploadPhotoThread = threading.Thread(target=upload_photo_handler, args=(videoPath, fileUploader, param_lock))
        #        uploadPhotoThread.daemon = True
        #        uploadPhotoThread.start()

        # Schedule task for Photo Uploader
        listeners = asyncio.gather(
            upload_photo_handler(videoPath, fileUploader, module_client,
                                 param_lock))

        print(
            "The sample is now waiting for direct method and desired twin update. "
        )

        def stdin_listener():
            while True:
                try:
                    selection = input("Press Q to quit\n")
                    if selection == "Q" or selection == "q":
                        print("Quitting...")
                        param_lock.acquire()
                        quitFlag = True
                        param_lock.release()
                        break
                except:
                    time.sleep(10)

        # Run the stdin listener in the event loop
        loop = asyncio.get_event_loop()
        user_finished = loop.run_in_executor(None, stdin_listener)

        # Wait for user to indicate they are done listening for messages
        await user_finished

        # Cancel listening
        listeners.cancel()

        # uploadPhotoThread.join()
        methodThread.join()
        twinThread.join()

        # Finally, disconnect
        module_client.disconnect()

    except Exception as e:
        print("Unexpected error %s " % e)
        raise
Exemple #29
0
hostname = os.getenv("HOSTNAME")

# The device having a certain module that has been created on the portal
# using X509 CA signing or Self signing capabilities
# The <device_id>\<module_id> should be the common name of the certificate

device_id = os.getenv("DEVICE_ID")
module_id = os.getenv("MODULE_ID")

x509 = X509(
    cert_file=os.getenv("X509_CERT_FILE"),
    key_file=os.getenv("X509_KEY_FILE"),
    pass_phrase=os.getenv("PASS_PHRASE"),
)

module_client = IoTHubModuleClient.create_from_x509_certificate(
    hostname=hostname, x509=x509, device_id=device_id, module_id=module_id)

module_client.connect()

# send 5 messages with a 1 second pause between each message
for i in range(1, 6):
    print("sending message #" + str(i))
    msg = Message("test wind speed " + str(i))
    msg.message_id = uuid.uuid4()
    msg.correlation_id = "correlation-1234"
    msg.custom_properties["tornado-warning"] = "yes"
    module_client.send_d2c_message(msg)
    time.sleep(1)

# send only string messages
for i in range(6, 11):
Exemple #30
0
import logging
import threading
from azure.iot.device import IoTHubModuleClient
from azure.iot.device import auth

logging.basicConfig(level=logging.ERROR)

# The "Authentication Provider" is the object in charge of creating authentication "tokens" for the module client.
auth_provider = auth.from_environment()
# For now, the SDK only supports MQTT as a protocol.
# Inputs/Ouputs are only supported in the context of Azure IoT Edge and module client
# The module client object acts as an Azure IoT Edge module and interacts with an Azure IoT Edge hub
# It needs an Authentication Provider to secure the communication with the Edge hub.
# This authentication provider is created from environment & delegates token generation to iotedged.

module_client = IoTHubModuleClient.from_authentication_provider(
    auth_provider, "mqtt")

# connect the client.
module_client.connect()


# define behavior for receiving an input message on input1
def input1_listener(module_client):
    while True:
        input_message = module_client.receive_input_message(
            "input1")  # blocking call
        print("the data in the message received on input1 was ")
        print(input_message.data)
        print("custom properties are")
        print(input_message.custom_properties)