Beispiel #1
0
def publish_message():
    """
    It publishes messages to the IoT hub every 4 seconds.
    """
    con0 = "HostName=TalkingChalkz.azure-devices.net;DeviceId=dev_00;SharedAccessKey=UJ/C3PxH8S/dx/+uY6BuBEuBzyfKoPhk/btkGgG1y2c="
    client0 = IoTHubDeviceClient.create_from_connection_string(con0,
                                                               websockets=True)

    con1 = "HostName=TalkingChalkz.azure-devices.net;DeviceId=dev_01;SharedAccessKey=3lE82lIMlEoJg1zvN9J8FFUxBxEeKNi+kJ1ZUad3igQ="
    client1 = IoTHubDeviceClient.create_from_connection_string(con1,
                                                               websockets=True)

    con2 = "HostName=TalkingChalkz.azure-devices.net;DeviceId=dev_02;SharedAccessKey=5mbx9W1uxKd/aK6pDEKQuHaOcMkMkKwBqPRj/Ri051w="
    client2 = IoTHubDeviceClient.create_from_connection_string(con2,
                                                               websockets=True)

    # Connect the device client
    client0.connect()
    client1.connect()
    client2.connect()

    while (True):
        try:
            dev = random.choice(devs)
            profile = random.choice(profiles)
            #Generating the message to send
            msg = {
                'dev_id': dev,
                'profile_id': profile,
                'hrate': '72',
                'timestamp': '123'
            }
            message = json.dumps(msg)

            # Send the message
            print("Sending message...")
            if (dev == "dev_00"):
                client0.send_message(message)
            elif (dev == "dev_01"):
                client1.send_message(message)
            elif (dev == "dev_02"):
                client2.send_message(message)
            print("Message successfully sent!")
            print(message)
            time.sleep(4)

        except KeyboardInterrupt:
            print("IoTHubClient stopped")
            return

        except:
            print("Unexpected error")
            time.sleep(4)

    # finally, disconnect
    client0.disconnect()
    client1.disconnect()
    client2.disconnect()
    def __init__(self, msg_stack: deque):
        self.conn = db_access.create_connection()
        self.msg_stack = msg_stack
        conn_str = "REMOVED"

        self.device_client: IoTHubDeviceClient = IoTHubDeviceClient.create_from_connection_string(conn_str)
        threading.Thread.__init__(self)
def iothub_client_telemetry_sample_run():
    lat = LATITUDE
    long = LONGITUDE
    distance = DISTANCE
    try:
        client = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING)
        while True:
            # simulate telemetry values to be transmitted
            speed = SPEED + random.random() * 50
            # make engine tempertaure a function of speed
            engine_temperature = ENGINE_TEMP + random.random() * speed
            # simulate movement by changing location
            lat = lat + random.random() * 0.00001
            long = long + random.random() * 0.00001
            # calculate distance travelled
            distance = distance + haversine_distance(LATITUDE, LONGITUDE, lat,
                                                     long)

            # format the message
            message = Message(
                MESSAGE.format(speed=speed,
                               engine_temperature=engine_temperature,
                               lat=lat,
                               long=long,
                               distance=distance))
            # send message every 5 seconds
            print("Sending message: {}".format(message))
            client.send_message(message)
            print("Message successfully sent")
            time.sleep(5)

    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Beispiel #4
0
def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    print("IoTHub Device Client Recurring Telemetry Sample")
    print("Press Ctrl+C to exit")
    try:
        # Connect the client.
        device_client.connect()

        # Send recurring telemetry
        i = 0
        while True:
            i += 1
            msg = Message("test wind speed " + str(i))
            msg.message_id = uuid.uuid4()
            msg.correlation_id = "correlation-1234"
            msg.custom_properties["tornado-warning"] = "yes"
            msg.content_encoding = "utf-8"
            msg.content_type = "application/json"
            print("sending message #" + str(i))
            device_client.send_message(msg)
            time.sleep(2)
    except KeyboardInterrupt:
        print("User initiated exit")
    except Exception:
        print("Unexpected exception!")
        raise
    finally:
        device_client.shutdown()
def connect_client():
    try:
        client = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING)
        return client
    except KeyboardInterrupt:
        print("Stopped!")
    def __init__(
            self,
            telemetry_interval: int = 3,
            fan_session_duration: int = 10,
            connection_string: str = os.getenv("CONNECTION_STRING_IOT_DEVICE"),
    ):
        """Abstract Raspberry Pi interface definition that is inherited by both simulated and real Raspberry Pi implementations.

        Args:
            telemetry_interval (int, optional): Interval in seconds at which the Raspberry pi should send telemetry to the cloud. Defaults to 3.
            fan_session_duration (int, optional): Time in seconds that the fan should turn on if the temperature is above a certain level. Defaults to 10.
            connection_string (str, optional): Connection string for the device to connect with Azure IoThub. Defaults to os.getenv("CONNECTION_STRING_IOT_DEVICE").
        """

        # Connection string for the device to connect with Azure IoThub.
        self.connection_string = connection_string
        # Interval in seconds at which the Raspberry pi should send telemetry to the cloud.
        self.telemetry_interval = telemetry_interval
        # Time in seconds that the fan should stay on if it is too warm.
        self.fan_session_duration = fan_session_duration
        # Inidicator for if the fan is currently turned on
        self.fan_active = False
        # Time that the fan should turn off again, if on.
        self.fan_stoptime = datetime.datetime(1970, 1, 1)

        # create a IoTHub client for the device to interact with.
        self.client = IoTHubDeviceClient.create_from_connection_string(
            self.connection_string)
    def start(self):
        try:
            self.registry_manager = IoTHubRegistryManager(CONNECTION_server)
            os.system(
                'az iot hub device-identity create --device-id %s --hub-name pathak'
                % (self.id))
            print("ID of the client created = %s" % (self.id))
            print("Connecting the Python IoT Hub")
            self.CONNECTION_STRING = os.popen(
                "az iot hub device-identity show-connection-string --device-id %s --hub-name pathak -o table"
                % (self.id)).read()
            self.CONNECTION_STRING = self.CONNECTION_STRING.split()[-1]
            client = IoTHubDeviceClient.create_from_connection_string(
                self.CONNECTION_STRING)
        except Exception as e:
            print("Problems with IOT HUB")
            os._exit(0)
        print("Connected")
        self.uploader = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.uploader.bind(('', 0))
        self.UPLOAD_PORT = self.uploader.getsockname()[1]
        self.uploader.listen(5)
        print('Listening on the upload port %s' % self.UPLOAD_PORT)

        message_listener_thread = threading.Thread(
            target=self.message_listener, args=(client, ))
        message_listener_thread.daemon = True
        message_listener_thread.start()
        self.cli()
Beispiel #8
0
def envia_iothub(dados):
    flag = 2
    #CONNECTION_STRING = "HostName=mdwcopel.azure-devices.net;DeviceId=pythondevice;SharedAccessKey=PzCUFs423r12S9qGKOu74hqwRYR+2LlOCGAssUYv9Fo="
    #CONNECTION_STRING = "HostName=HemsHub.azure-devices.net;DeviceId=Hemsd;SharedAccessKey=L3YBChE5GvupNPT2ILsQbpU58Du71yEeEmohUFeiBWE="

    try:
        with open('/etc/iotedge/config.yaml', 'r') as searchfile:
            for line in searchfile:
                if 'device_connection_string' in line:
                    string_teste = line.partition(
                        "device_connection_string: ")[2]
                    #print (string_teste)
        string_teste = string_teste.replace("\"", "")
        CONNECTION_STRING = string_teste
        client = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING)
        client.connect()
        #print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
        # Send the message.
        print("Enviando mensagem para IoTHub: " + str(dados))
        client.send_message(str(dados))
        print("Enviada com sucesso!")
        time.sleep(1)
        client.disconnect()
        flag = 2

    except Exception as e:

        print("IoTHubClient sample stopped")
        reenviar(dados)
        return flag

    return flag
Beispiel #9
0
def iothub_client_init():
    # Create an IoT Hub client
    print("Connecting to " + "'" + CONNECTION_STRING + "'")
    global client
    client = IoTHubDeviceClient.create_from_connection_string(
        CONNECTION_STRING)
    return client
Beispiel #10
0
def iothub_client_init():
    # Create an IoT Hub client
    global _client
    _client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING, auto_connect=True)
    try:

        def device_method_handler(method_request):
            _led.blink(on_time=0.1, off_time=0.1)
            print (
                "\nMethod callback called with:\nmethodName = {method_name}\npayload = {payload}".format(
                    method_name=method_request.name,
                    payload=method_request.payload
                ) , flush=True
            )

            cb = _callbackSelector.get(method_request.name, lambda _: ({"Response" : "Not Defined"}, 404))

            response_payload, response_status = cb(method_request.payload)

            method_response = MethodResponse.create_from_method_request(method_request, response_status, payload=response_payload)
            print("\nResponse:\nPayload: {pl}\nStatus: {st}".format(pl=response_payload, st=response_status), flush=True)
            _client.send_method_response(method_response)
            _led.on()

        _client.on_method_request_received = device_method_handler

        _client.connect()
        _led.on()
    except:
        _client.shutdown()
        _client = None
        _led.off()
Beispiel #11
0
 def __init__(self, connection_string):
     self._client = IoTHubDeviceClient.create_from_connection_string(
         connection_string)
     self._client.connect()
     self._q = queue.Queue()
     self._thread = threading.Thread(target=self._loop, daemon=True)
     self._thread.start()
Beispiel #12
0
 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 = IoTHubDeviceClient.from_authentication_provider(
         auth_provider, transport_type)
     self.client.connect()
Beispiel #13
0
def sendToAzure(topic, message):
    try:
        client1 = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING_1)
        client2 = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING_2)
        print("Sending message: {}".format(message))
        message = message.encode('utf8')
        if topic == "sensors/s1":
            print("Sending to S1")
            client1.send_message(message)
        if topic == "sensors/s2":
            print("Sending to S2")
            client2.send_message(message)
        print("Message successfully sent")
    except KeyboardInterrupt:
        print("IoTHubBridge sample stopped")
def sendToAzure(device, message):
    try:
        client = IoTHubDeviceClient.create_from_connection_string(device)
        print("Sending message: {}".format(message))
        message = message.encode('utf8')
        client.send_message(message)
        print("Message successfully sent")
    except KeyboardInterrupt:
        print("IoTHubBridge sample stopped")
Beispiel #15
0
    def __init__(self, port, baudrate, name, reconnect_period, update_period,
                 connection_string):
        self.name = name
        try:
            # modbus client
            self.mb_client = modbus_rtu.RtuMaster(
                serial.Serial(port=port,
                              baudrate=baudrate,
                              bytesize=8,
                              parity='N',
                              stopbits=1,
                              xonxoff=0))
            self.mb_client.set_timeout(5.0)
            self.mb_client.set_verbose(True)
        except Exception as e:
            logging.error(str(e))

        try:
            # azure iothub client
            self.iothub_client = IoTHubDeviceClient.create_from_connection_string(
                connection_string)
        except Exception as e:
            logging.error(str(e))

        self.reconnect_period = reconnect_period
        self.update_period = update_period
        # number of float elements
        self.float_ele_number = 12
        # number of uint8_t elements
        self.char_ele_number = 8
        # number of short(uint16_t) elements
        self.short_ele_number = 1

        # analog input values  (in Volt)
        self.vin = [0] * self.float_ele_number
        # digital io inout status (0 -> off 1 -> flash 2-> on)
        self.din = [0] * self.char_ele_number
        # board card address
        self.address = 0
        # data length (in word) to be read
        self.word2read = self.float_ele_number * 2 + self.char_ele_number / 2 + self.short_ele_number
        # original data from modbus
        self.original_list = [0] * int(self.word2read)
        # machine status
        self.status = 0
        self.status_old = 0
        # weld status
        self.weld_status = 0
        self.weld_status_old = 0
        # weld values
        self.weld_voltage = [0] * 4
        self.weld_current = [0] * 4
Beispiel #16
0
 def __init__(self, connection):
     self.guid = str(uuid.uuid4())
     self.client = IoTHubDeviceClient.create_from_connection_string(
         connection)
     self.vid = cv2.VideoCapture(0)
     # maximum number of frames between saving images
     self.frame_cap = 1000
     # maximum number of images to save before recycling
     self.image_cap = 10
     # for iteration, should be set to 0
     self.frame_no = 0
     self.image_no = 0
     self.images_path = os.path.join('assets','images')
def send_message(message): 
    '''
    Sends a message to the Azure Iot Hub. The function requires
    that the message has an attribute 'hub_endpoint' which contains the
    corresponding device url of the Azure Iot Hub.
    '''
    # Definitly not the most performant way of communicating with the hub but
    # should work for device simulation and keeps the code very simple
    device_hub_url = message.get('hub_endpoint')
    msgjson = json.dumps(message)
    msg = Message(msgjson)
    client = IoTHubDeviceClient.create_from_connection_string(device_hub_url)
    client.send_message(msg)
    client.disconnect()
Beispiel #18
0
    def iothub_client_init(self):
        global logger
        # Create an IoT Hub client
        device_client = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING)

        while True:
            try:
                device_client.connect()  #connect client
                break
            except:
                logger.error("Azure Connection failed connecting.....")
                time.sleep(5)  #retry

        return device_client
Beispiel #19
0
def iothub_client_sample_run():
    try:
        client = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING_DEVICE)

        message_listener_thread = threading.Thread(target=message_listener,
                                                   args=(client, ))
        message_listener_thread.daemon = True
        message_listener_thread.start()

        while True:
            time.sleep(1000)

    except KeyboardInterrupt:
        print("IoT Hub C2D Messaging device sample stopped")
Beispiel #20
0
    def __init__(self):
        # The device connection string to authenticate the device with your IoT hub.
        # Using the Azure CLI:
        # az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyNodeDevice --output table
        self.CONNECTION_STRING = "HostName=su-MSA.azure-devices.net;DeviceId=MyPythonDevice;SharedAccessKey=ZqigHWDCQ696rya1jI24fA9X3/RAtgbIqkN6WEo0ROc="

        # Define the JSON message to send to IoT Hub.
        self.DISTANCE = 250.0
        self.INTENSITY = 255
        self.MSG_TXT = '{{"Distance": {distance}, "Intensity": {intensity}}}'  #, "Intruder image": {intruder_img}}}'

        self.INTERVAL = 1

        # Create an IoT Hub client
        self.client = IoTHubDeviceClient.create_from_connection_string(
            self.CONNECTION_STRING)
def main():
    print("IoT Hub Quickstart #1 - Simulated device")
    print("Press Ctrl-C to exit")

    # Instantiate the client. Use the same instance of the client for the duration of
    # your application
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

    # Run Sample
    try:
        run_telemetry_sample(client)
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped by user")
    finally:
        # Upon application exit, shut down the client
        print("Shutting down IoTHubClient")
        client.shutdown()
def iothub_client_telemetry_run():

    try:
        client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )

        while True:
            message = getReadings()

            # Send the message.
            print( "Sending message: {}".format(message) )
            client.send_message(message)
            print( "Message sent" )
            time.sleep(INTERVAL)

    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Beispiel #23
0
def init(connection_string, methods):
    if connection_string is "":
        print("Missing connection string!")
        return 0

    client = IoTHubDeviceClient.create_from_connection_string(
        connection_string, websockets=True)
    # connect the client.
    while connect(client) == False:
        time.sleep(10)

    print("Starting listening for direct methods of type [{}]...".format(
        ', '.join(methods.keys())))

    # Run method listener threads in the background
    device_method_thread = threading.Thread(target=device_method_listener,
                                            args=(client, methods))
    device_method_thread.daemon = True
    device_method_thread.start()
Beispiel #24
0
def iothub_client_init():
    derived_device_key = devicekey.derive_device_key(device_id,
                                                     group_symmetric_key)
    registration_result = registerdevice.register_device(
        device_id, derived_device_key)
    print(registration_result)
    print("The status was :-")
    print(registration_result.status)
    print("The etag is :-")
    print(registration_result.registration_state.etag)
    print("\n")
    if registration_result.status == "assigned":
        print("Will send telemetry from the provisioned device with id {id}".
              format(id=device_id))
        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=derived_device_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )
    return device_client
def create_client():
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(
        CONNECTION_STRING)

    # Define a method request handler
    def method_request_handler(method_request):
        if method_request.name == "SetTelemetryInterval":
            try:
                global INTERVAL
                INTERVAL = int(method_request.payload)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {
                    "Response":
                    "Executed direct method {}".format(method_request.name)
                }
                response_status = 200
        else:
            response_payload = {
                "Response":
                "Direct method {} not defined".format(method_request.name)
            }
            response_status = 404

        method_response = MethodResponse.create_from_method_request(
            method_request, response_status, response_payload)
        client.send_method_response(method_response)

    try:
        # Attach the method request handler
        client.on_method_request_received = method_request_handler
    except:
        # Clean up in the event of failure
        client.shutdown()
        raise

    return client
Beispiel #26
0
    def __init__(self, base_dir, config_path):
        with open(os.path.join(base_dir, config_path), "r") as f:
            self.forza_config = json.load(f)

        self._init_logger()

        self._setup_udp_socket()
        self.telemetry_manager = TelemetryManager(
            self.forza_config["device"]["output_fname"],
            self.forza_config["device"]["telemetry_format_fname"]
        )
        self.send_ip = self.forza_config["device"]["send_ip"]
        self.send_port = self.forza_config["device"]["send_port"]

        # Get the connection string
        # TODO(): Risk: the file is saved on the disk in plain text
        conn_str_fname = os.path.join(base_dir, self.forza_config["iothub"]["conn_str_fname"])
        self.conn_str = open(conn_str_fname, 'r').read()
        
        # Create instance of the device client using the authentication provider
        self.device_client = IoTHubDeviceClient.create_from_connection_string(self.conn_str)
        self.device_client.connect()
Beispiel #27
0
def run():
    try:
        speed: float = 0.0
        #initialises direction to a random number since _generate_direction needs something to start with
        direction: float = random.uniform(0, 360)
        #establish connection
        client: IoTHubDeviceClient = IoTHubDeviceClient.create_from_connection_string(
            CONNECTION_STRING)
        print("Sending messages, press Ctrl-c to exit")
        while True:
            #update wind speed and direction
            speed = _generate_speed()
            direction = _generate_direction(direction, speed)
            #create and send message
            message: str = '{"wind_speed":' + str(
                speed) + ',"wind_direction":' + str(direction) + '}'
            print("sending: " + message)
            client.send_message(message)  #message is actually sent here
            print("sent")
            time.sleep(1)
    except KeyboardInterrupt:
        #when Ctrl-c is pressed allow the function to finish so the program can stop running
        print("Stopped")
Beispiel #28
0
def aux_iothub_client_init():
    client = IoTHubDeviceClient.create_from_connection_string(
        AUX_CONNECTION_STRING)
    return client
Beispiel #29
0
def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(
        CONNECTION_STRING)
    return client
Beispiel #30
0
        'wind_direction': pld[2],
        'wind_intensity': pld[3],
        'rain': pld[4]
    }
    messaggio = json.dumps(mess)
    print(dev + " sent " + messaggio)
    if (dev == "foggia_2"):
        hubClient1.send_message(messaggio)
    elif (dev == "rome_2"):
        hubClient2.send_message(messaggio)
    print("Message forwarded to the hub")


if __name__ == "__main__":
    #initialize the gateway and connect to the hub from 2 possible devices (fogia_2 and rome_2)
    hubClient1 = IoTHubDeviceClient.create_from_connection_string(
        connection_string1, websockets=True)
    hubClient1.connect()
    hubClient2 = IoTHubDeviceClient.create_from_connection_string(
        connection_string2, websockets=True)
    hubClient2.connect()

    #initialize the gateway and connect to the broker via MQTT
    brokerClient = mqtt.Client("PythonGateway", mqtt.MQTTv311)
    brokerClient.on_connect = on_connect
    brokerClient.on_disconnect = on_disconnect
    brokerClient.on_message = on_message
    brokerClient.connect(brokerAddress, brokerPort)

    brokerClient.loop_forever()

    #finally disconnect