Ejemplo n.º 1
0
def iothub_client_telemetry_sample_run():
    global count
    try:
        client = iothub_client_init()
        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")

        while count < NBR_MESSAGE:
            # Build the message with simulated telemetry values.
            temperature = TEMPERATURE + (random.random() * 15)
            humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT.format(
                temperature=temperature, humidity=humidity, count=count)
            message = Message(msg_txt_formatted)
            message.content_encoding = "utf-8"
            message.content_type = "application/json"

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            if temperature > 30:
                message.custom_properties["temperatureAlert"] = "true"
            else:
                message.custom_properties["temperatureAlert"] = "false"

            message.custom_properties["SendingTime"] = datetime.datetime.now()

            # Send the message.
            print("Sending message: {}".format(message))
            client.send_message(message)
            time.sleep(1)
            print("Message successfully sent")
            count += 1

    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
def build_message(payload):
    msg = Message(payload)
    msg.message_id = uuid.uuid4()
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"

    return msg
 async def send_telemetry(self, Telemetry, InterfacelId, InterfaceInstanceName):
   msg = Message(json.dumps(Telemetry))
   msg.content_encoding = "utf-8"
   msg.content_type = "application/json"
   msg.custom_properties["$.ifname"] = InterfaceInstanceName
   msg.custom_properties["$.ifid"] = InterfacelId
   await self.device_client.send_message(msg)
   self.logger.info("[MESSAGE] %s" % msg)
Ejemplo n.º 5
0
async def send_test_message(i):
    i["timestamp"] = str(datetime.utcnow())
    msg = Message(json.dumps(i))
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    msg.message_id = uuid.uuid4()
    await device_client.send_message(msg)
    print("done sending message #" + str(i))
Ejemplo n.º 6
0
 async def send_test_message(i):
     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"
     msg.content_encoding = "utf-8"
     msg.content_type = "application/json"
     await device_client.send_message(msg)
     print("done sending message #" + str(i))
Ejemplo n.º 7
0
def send_to_Hub_callback(strMessage):
    if strMessage == []:
        return

    message = Message(strMessage)
    message.content_encoding = "utf-8"
    message.custom_properties["appid"] = "scanner"

    # hubManager.send_event_to_output("output1", message, 0)
    print('sent from send_to_Hub_callback')
Ejemplo n.º 8
0
def test_script_object_to_outgoing_message(payload):
    """
    Convert an object that we received from a test script into something that we
    can pass into the iothub sdk.
    """

    msg = Message(bytearray(json.dumps(payload.body), "utf-8"))
    msg.content_type = "application/JSON"
    msg.content_encoding = "utf-8"
    return msg
Ejemplo n.º 9
0
async def send_telemetry(device_client, send_frequency):
    while not terminate:
        payload = '{"temp": %f, "humidity": %f}' % (random.randrange(
            60.0, 95.0), random.randrange(10.0, 100.0))
        print("sending message: %s" % (payload))
        msg = Message(payload)
        msg.content_type = "application/json"
        msg.content_encoding = "utf-8"
        await device_client.send_message(msg)
        print("completed sending message")
        await asyncio.sleep(send_frequency)
Ejemplo n.º 10
0
def iothub_client_telemetry_sample_run():
    try:
        aux_validate_connection_string()
        client = aux_iothub_client_init()

        print("IoT Hub Simulated body sensor")
        print("Press Ctrl-C to exit")

        #ENABLE THE RECEPTION THREAD, DEFINING THE TARGET METHOD
        message_listener_thread = threading.Thread(target=message_listener,
                                                   args=(client, ))
        message_listener_thread.daemon = True
        message_listener_thread.start()

        #IT WILL RUN FOREVER UNLESS YOU STOP IT
        while True:
            #COLLECTING SENSOR VALUES
            #NEW METRIC COLLECTION SHOULD ADD CODE HERE
            temperature_measure = get_sensor_temperature()
            heart_rate_measure = get_sensor_heart_rate()

            sensor_data['device_name'] = DEVICE_NAME
            #STORING SENSOR VALUES IN DATA STRUCTURE
            #NEW METRIC COLLECTION SHOULD ADD CODE HERE
            sensor_data['temperature'] = temperature_measure
            sensor_data['heart_rate'] = heart_rate_measure

            #TRANFORMING IT TO JSON
            json_sensor_data = json.dumps(sensor_data)

            #CREATING AN AZURE IOT MESSAGE OBJECT
            azure_iot_message = Message(json_sensor_data)

            #ADDING A CUSTOM PROPERTY OF OUR CHOICE TO THE MESSAGE CALLED temperature_alert
            if temperature_measure > AUX_MAXIMUM_BODY_TEMPERATURE:
                azure_iot_message.custom_properties[
                    "temperature_alert"] = "true"
            else:
                azure_iot_message.custom_properties[
                    "temperature_alert"] = "false"

        #SETTING PROPER MESSAGE ENCODING
            azure_iot_message.content_encoding = 'utf-8'
            azure_iot_message.content_type = 'application/json'

            #SENDING THE MESSAGE
            print("Sending azure_iot_message: {}".format(azure_iot_message))
            client.send_message(azure_iot_message)
            print("Message successfully sent")
            #SLEEPING FOR A SECOND BEFORE RESTARTING
            time.sleep(1)

    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
async def send_telemetry(send_frequency):
    while not terminate:
        payload = f'{{"cpu_temp": {get_current_cpu_temp()}, "cpu_freq": {get_cpu_frequency_statistics()["current"]}, "cpu_usage": {get_cpu_usage()}, "ram_usage": {get_memory_statistics()["used"]}}}'
        print(f'sending message:{payload}')
        msg = Message(payload)
        # these message properties are important if you intend to export data from IoT Central
        msg.content_type = 'application/json'
        msg.content_encoding = 'utf-8'
        await client.send_message(msg)
        print('completed sending telemetry message')
        await asyncio.sleep(send_frequency)
Ejemplo n.º 12
0
    async def _send(self, client, payload):
        """ Send the payload, using provided client """
       
        message = Message(json.dumps(payload, separators = (',', ':')).encode('utf-8'))
        message.content_encoding = "utf-8"
        message.content_type = "application/json"
        size = str(message.get_size())

        _LOGGER.info("Sending message: {}".format(message))
        _LOGGER.info("Message Size: {}".format(size))
        await client.send_message(message)
        _LOGGER.info('Message successfully sent')
def create_telemetry(telemetry_msg, component_name=None):
    """
    Function to create telemetry for a plug and play device. This function will take the raw telemetry message
    in the form of a dictionary from the user and then create a plug and play specific message.
    :param telemetry_msg: A dictionary of items to be sent as telemetry.
    :param component_name: The name of the device like "sensor"
    :return: The message.
    """
    msg = Message(json.dumps(telemetry_msg))
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    if component_name:
        msg.custom_properties["$.sub"] = component_name
    return msg
Ejemplo n.º 14
0
    async def send_test_message(i):
        print("sending message #" + str(i))
        message_id = uuid.uuid4()
        csv_text = str(i) + "," + str(message_id) + ",test wind speed " + str(
            i) + "," + datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")

        msg = Message(csv_text)
        msg.message_id = message_id
        msg.correlation_id = "correlation-1234"
        msg.custom_properties["tornado-warning"] = "yes"
        msg.content_encoding = "utf-8"
        msg.content_type = "application/csv"
        await device_client.send_message(msg)
        print("done sending message #" + str(i))
def create_telemetry(telemetry_msg, component_name=None):
    """
    Coroutine to send telemetry from a PNP device. This method will take the raw telemetry message
    in the form of a dictionary from the user and then send message after creating a message object.
    :param device_client: The device client
    :param component_name: The name of the device like "sensor"
    :param telemetry_msg: A dictionary of items to be sent as telemetry.
    """
    msg = Message(json.dumps(telemetry_msg))
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    if component_name:
        msg.custom_properties["$.sub"] = component_name
    return msg
Ejemplo n.º 16
0
    async def send_telemetry():
        print("Sending telemetry for temperature")

        while True:
            current_temp = random.randrange(
                10, 50)  # Current temperature in Celsius (randomly generated)
            # Send a single temperature report message
            temperature_msg = {"temperature": current_temp}

            msg = Message(json.dumps(temperature_msg))
            msg.content_encoding = "utf-8"
            msg.content_type = "application/json"
            print("Sent message")
            await device_client.send_message(msg)
            await asyncio.sleep(8)
Ejemplo n.º 17
0
async def send_recurring_telemetry(device_client):
    # Connect the client.
    await 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))
        await device_client.send_message(msg)
        time.sleep(2)
Ejemplo n.º 18
0
def iothub_client_telemetry_sample_run():
    try:
        aux_validate_connection_string()
        client = aux_iothub_client_init()

        print ( "IoT Hub Simulated body sensor" )
        print ( "Press Ctrl-C to exit" )

	#IT WILL RUN FOREVER UNLESS YOU STOP IT BY PRESSING CTRL + C
        while True:
        #COLLECTING SENSOR VALUES
		#NEW METRIC COLLECTION SHOULD ADD CODE HERE
		temperature_measure = get_sensor_temperature()
		heart_rate_measure  = get_sensor_heart_rate()
		blood_sugar_measure = get_blood_sugar_rate()
		sensor_data['Gas_Consumption_KWh'] = heart_rate_measure
		sensor_data['Connection_Strength'] = blood_sugar_measure
		sensor_data['Elec_Consumption_KWh'] = temperature_measure
		#STORING SENSOR VALUES IN DATA STRUCTURE
		#NEW METRIC COLLECTION SHOULD ADD CODE HERE sensor_data['Elec_Consumption_KWh'] = temperature_measure

		#TRANFORMING IT TO JSON			
		json_sensor_data = json.dumps(sensor_data)
		#CREATING AN AZURE IOT MESSAGE OBJECT		
		azure_iot_message = Message(json_sensor_data)

        #ADDING A CUSTOM PROPERTY OF OUR CHOICE TO THE MESSAGE CALLED temperature_alert
		if temperature_measure > AUX_MAXIMUM_BODY_TEMPERATURE:
		  azure_iot_message.custom_properties["power_outage_alert"] = "true"
		else:
		  azure_iot_message.custom_properties["power_outage_alert"] = "false"

        #SETTING PROPER MESSAGE ENCODING
		azure_iot_message.content_encoding='utf-8'
		azure_iot_message.content_type='application/json'

        #SENDING THE MESSAGE
		print( "Sending azure_iot_message: {}".format(azure_iot_message) )
		client.send_message(azure_iot_message)
		print ( "Message successfully sent" )
		#SLEEPING FOR A SECOND BEFORE RESTARTING
		time.sleep(1)

    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Ejemplo n.º 19
0
def device_telemetry_sender(device_client):
    global message_interval
    try:
        while True:
            # Genarate the value.
            temperature = temperature_base + (random.random() * 15)
            humidity = humidity_base + (random.random() * 20)
            # Build the message.
            message_dic = {'temperature': temperature,'humidity': humidity}
            message = Message(json.dumps(message_dic), content_encoding='utf-8')
            message.content_encoding = 'utf-8'
            message.content_type = 'application/json'
            # Add a custom application property to the message.
            message.custom_properties["temperatureAlert"] = "true" if temperature > 30 else "false"
            device_client.send_message(message)
            print("Message sent: {}".format(message))
            # Sleep.
            time.sleep(message_interval)
    except KeyboardInterrupt:
        pass
Ejemplo n.º 20
0
async def send_telemetry_from_smart_valve(device_client, telemetry_msg):
    msg = Message(json.dumps(telemetry_msg))
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    print("Sending message {0}".format(msg))
    await device_client.send_message(msg)
Ejemplo n.º 21
0
from azure.iot.device import IoTHubModuleClient, Message

# 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
module_client = IoTHubModuleClient.create_from_edge_environment()

# Connect the client.
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"
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    module_client.send_message_to_output(msg, "twister")
    time.sleep(1)

# send only string messages
for i in range(6, 11):
    print("sending message #" + str(i))
    module_client.send_message_to_output("test payload message " + str(i), "tracking")
    time.sleep(1)


# finally, shut down the client
module_client.shutdown()
Ejemplo n.º 22
0
async def send_telemetry_from_thermostat(device_client, telemetry_msg):
    msg = Message(json.dumps(telemetry_msg))
    msg.content_encoding = "utf-8"
    msg.content_type = "application/json"
    print("Sent message")
    await device_client.send_message(msg)
Ejemplo n.º 23
0
def iothub_message(condition):
    try:
        client = iothub_client_init()

        if condition == 'normal':
            starttime = params.normalduration
            while starttime > 0:
                starttime -= 1
                temperature = random.uniform(params.normal_temp_min, params.normal_temp_max)
                heartbeat = random.uniform(params.normal_heartbeat_min, params.normal_heartbeat_max)
                oxygen = random.uniform(params.normal_oxygen_min, params.normal_oxygen_max)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

        elif condition == 'hightemp':
            starttime = params.intervalduration
            while starttime > 0:
                starttime -= 1
                temperature = random.uniform(params.normal_temp_min, params.normal_temp_max)
                heartbeat = random.uniform(params.normal_heartbeat_min, params.normal_heartbeat_max)
                oxygen = random.uniform(params.normal_oxygen_min, params.normal_oxygen_max)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

            firstevent = params.intervalduration
            while firstevent > 0:
                firstevent -= 1
                temperature = random.uniform(params.high_temp_firstevent_min, params.high_temp_firstevent_max)
                heartbeat = random.uniform(params.high_heartbeat_firstevent_min, params.high_heartbeat_firstevent_max)
                oxygen = random.uniform(params.high_oxygen_firstevent_min, params.high_oxygen_firstevent_max)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

            secondevent = params.intervalduration
            while secondevent > 0:
                secondevent -= 1
                temperature = random.uniform(params.high_temp_secondevent_min, params.high_temp_secondevent_max)
                heartbeat = random.uniform(params.high_heartbeat_secondevent_min, params.high_heartbeat_secondevent_max)
                oxygen = random.uniform(params.high_oxygen_secondevent_min, params.high_oxygen_secondevent_max)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

            thirdevent = params.intervalduration
            while thirdevent > 0:
                thirdevent -= 1
                temperature = random.uniform(params.high_temp_thirdevent_min, params.high_temp_thirdevent_max)
                heartbeat = random.uniform(params.high_heartbeat_thirdevent_min, params.high_heartbeat_thirdevent_max)
                oxygen = random.uniform(params.high_oxygen_thirdevent_min, params.high_oxygen_thirdevent_max)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

            finalevent = params.intervalduration
            while finalevent > 0:
                finalevent -= 1
                temperature = random.uniform(0, 0)
                heartbeat = random.uniform(0, 0)
                oxygen = random.uniform(0, 0)

                msg_txt_formatted = params.MSG_TXT.format(temperature=temperature, heartbeat=heartbeat, oxygen=oxygen)
                message = Message(msg_txt_formatted)
                message.content_encoding = "utf-8"
                message.content_type = "application/json"

                if temperature > 40:
                    message.custom_properties["temperatureAlert"] = "true"
                else:
                    message.custom_properties["temperatureAlert"] = "false"

                print(f"Sending {condition} message: {message}")
                client.send_message(message)
                time.sleep(params.sleepduration)

    except KeyboardInterrupt:
        pass