Пример #1
0
def send_iot_hub_message(hub_manager, message_dict, schema):
    message = json.dumps(message_dict)
    message = IoTHubMessage(message)
    message.properties().add("iothub-creation-time-utc", make_time_string())
    message.properties().add("iothub-message-schema", schema)
    adjust_outstanding_sent_message_count(1)
    hub_manager.client.send_event_async("output2", message,
                                        send_confirmation_callback, 0)
    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))
            event.set_content_encoding_system_property('utf-8')
            event.set_content_type_system_property('application/json')

        event.properties().add('deviceId', 'RaspberryPi3')

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(event, send_confirmation_callback,
                                     send_context)
def read_and_send_measurements_from_sensehat(sense, hubManager):
    global SEND_SENSEHAT_CALLBACKS
    # sense.clear()
    temperature = sense.get_temperature()
    temperature_h = sense.get_temperature_from_humidity()
    temperature_p = sense.get_temperature_from_pressure()
    humidity = sense.get_humidity()
    pressure = sense.get_pressure()
    accelerometer = sense.get_accelerometer_raw()
    accel = "\"x\":{x:.5f},\"y\":{y:.5f},\"z\":{z:.5f}".format(**accelerometer)
    print("accelerometer - %s" % accel)

    timeCreated = datetime.datetime.utcnow().isoformat()
    MSG_TXT = "{\"temperature\": %.2f,\"temperature_h\": %.2f,\"temperature_p\": %.2f,\"humidity\": %.2f,\"pressure\": %.2f,\"accelerometer\":{%s},\"timeCreated\": \"%s\"}"
    msg_txt_formatted = MSG_TXT % (temperature, temperature_h, temperature_p,
                                   humidity, pressure, accel, timeCreated)
    print("Sending - :%s\n" % msg_txt_formatted)
    message = IoTHubMessage(msg_txt_formatted)
    prop_map = message.properties()
    prop_map.add("data-type", "sensing")
    prop_map.add("application",
                 "Custom-vision-service-iot-edge-raspberry-pi-ext")

    hubManager.send_event_to_output("output2", message, 0)
    SEND_SENSEHAT_CALLBACKS += 1
    print("    Total sensehat messages sent: %d" % SEND_SENSEHAT_CALLBACKS)
Пример #4
0
def iothub_client_sample_run():
    try:
        if (check_internet() == True):
            client = iothub_client_init()
            print("Connecting to IoT Hub")
            if client.protocol == IoTHubTransportProvider.MQTT:
                print("IoTHubClient is reporting state")
                reported_state = "{\"newState\":\"standBy\"}"
                #client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
            #telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")
            #while True:
            global MESSAGE_COUNT, MESSAGE_SWITCH
            if MESSAGE_SWITCH:
                # send a few messages every minute
                print("IoTHubClient sending %d messages" % MESSAGE_COUNT)
                #temperature = sensor.read_temperature()
                humidity_1 = get_humidity_1()
                temperature_1 = get_temperature_1()
                distance_1 = get_distance_1()
                distance_2 = get_distance_2()
                distance_3 = get_distance_3()
                distance_4 = get_distance_4()
                distance_5 = get_distance_5()
                distance_6 = get_distance_6()
                distance_7 = get_distance_7()
                distance_8 = get_distance_8()
                #distance_9 = get_distance_9()
                #distance_10 = get_distance_10()

                msg_txt_formatted = MSG_TXT % (
                    distance_1, distance_2, distance_3, distance_4, distance_5,
                    distance_6, distance_7, distance_8, distance_8, distance_8)
                print(msg_txt_formatted)
                message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % MESSAGE_COUNT
                message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add("temperatureAlert", "true")

                client.send_event_async(message, send_confirmation_callback,
                                        MESSAGE_COUNT)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % MESSAGE_COUNT)

                status = client.get_send_status()
                print("Send status: %s" % status)
                MESSAGE_COUNT += 1
            time.sleep(2)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        telemetry.send_telemetry_data(
            parse_iot_hub_name(), EVENT_FAILED,
            "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #5
0
def iothub_client_telemetry_sample_run():

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

        while True:
            # Build the message with simulated telemetry values.
            liveReading = LIVE_READING + random.randrange(0, 1000)
            msg_txt_formatted = MSG_TXT % (liveReading)
            message = IoTHubMessage(msg_txt_formatted)

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            prop_map = message.properties()
            if liveReading > 700:
              prop_map.add("highConsumptionAlert", "true")
            else:
              prop_map.add("highConsumptionAlert", "false")

            # Send the message.
            print( "Sending message: %s" % message.get_string() )
            client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(1)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Пример #6
0
def iothub_client_telemetry_sample_run():
    try:
        client = iothub_client_init()
        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")

        while True:
            humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
            curdate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            if humidity is not None and temperature is not None:
                msg_txt_formatted = MSG_TXT % (curdate, temperature, humidity)
                message = IoTHubMessage(msg_txt_formatted)

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

                # Send the message.
                print("Sending message: %s" % message.get_string())

                client.send_event_async(message, send_confirmation_callback,
                                        None)
            else:
                print('Failed to get reading. Try again!')
            time.sleep(2)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #7
0
def iothub_client_telemetry_sample_run():
    try:
        client = iothub_client_init()
        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")
        message_counter = 0

        while True:
            msg_txt_formatted = "Event!"
            # messages can be encoded as string or bytearray
            if (message_counter & 1) == 1:
                message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
            else:
                message = IoTHubMessage(msg_txt_formatted)
            # optional: assign ids
            message.message_id = "message_%d" % message_counter
            message.correlation_id = "correlation_%d" % message_counter
            # optional: assign properties
            prop_map = message.properties()
            generate_message(prop_map, generate_ticket_id(), datetime.now())
            client.send_event_async(message, send_confirmation_callback,
                                    message_counter)
            print(
                "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                % message_counter)
            message_counter += 1
            sleep(np.random.randint(10))

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return

    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #8
0
def data_loop(sensor, pin):
    try:
        client = iothub_client_init()
        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")
        count = 0
        while True:
            # Build the message with simulated telemetry values.
            humidity, temperature = get_sensor_data(sensor, pin)
            msg_txt_formatted = MSG_TXT % (temperature, humidity)
            message = IoTHubMessage(msg_txt_formatted)
            # Optional due to edgeHub error
            message.message_id = "message_%d" % count
            message.correlation_id = "correlation_%d" % count
            count += 1
            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            prop_map = message.properties()
            if temperature > 30:
                prop_map.add("temperatureAlert", "true")
            else:
                prop_map.add("temperatureAlert", "false")

            # Send the message.
            print("Sending message: %s" % message.get_string())
            client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
def filter_message(message):
    message_buffer = message.get_bytearray()
    size = len(message_buffer)
    message_str = message_buffer[:size].decode('utf-8')
    if not message_str:
        return None

    message_obj = json.loads(message_str)
    if message_obj["machine"]["temperature"] > TEMPERATURE_THRESHOLD:
        print(" Machine temperature : %d exceeds threshold %d" %
              (message_obj["machine"]["temperature"], TEMPERATURE_THRESHOLD))
        filtered_message = IoTHubMessage(message_str)

        filtered_message.set_content_type_system_property(
            message.get_content_type_system_property() or "application/json")
        filtered_message.set_content_encoding_system_property(
            message.get_content_encoding_system_property() or "utf-8")

        prop_map = filtered_message.properties()

        origin_prop_key_value_pair = message.properties().get_internals()
        for key in origin_prop_key_value_pair:
            prop_map.add(key, origin_prop_key_value_pair[key])

        prop_map.add("MessageType", "Alert")

        return filtered_message
    else:
        return None
Пример #10
0
def iothub_client_sample_run():
    try:
        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print("IoTHubClient is reporting state")
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state),
                                       send_reported_state_callback,
                                       SEND_REPORTED_STATE_CONTEXT)

        if not config.SIMULATED_DATA:
            sensor = SenseHat()
            print 'PI SenseHat Object Created'
        else:
            # sensor = BME280(address = config.I2C_ADDRESS)
            sensor = BME280SensorSimulator()

        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS,
                                      "IoT hub connection is established")
        while True:
            global MESSAGE_COUNT, MESSAGE_SWITCH
            if MESSAGE_SWITCH:
                # send a few messages every minute
                print("IoTHubClient sending %d messages" % MESSAGE_COUNT)
                temperature = sensor.get_temperature()
                humidity = sensor.get_humidity()
                msg_txt_formatted = MSG_TXT % (temperature, humidity)
                print(msg_txt_formatted)
                message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % MESSAGE_COUNT
                message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add(
                    "temperatureAlert",
                    "true" if temperature > TEMPERATURE_ALERT else "false")

                client.send_event_async(message, send_confirmation_callback,
                                        MESSAGE_COUNT)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % MESSAGE_COUNT)

                status = client.get_send_status()
                print("Send status: %s" % status)
                MESSAGE_COUNT += 1
            time.sleep(config.MESSAGE_TIMESPAN / 1000.0)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        telemetry.send_telemetry_data(
            parse_iot_hub_name(), EVENT_FAILED,
            "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")

    print_last_message_time(client)
Пример #11
0
def iothub_client_telemetry_sample_run():

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

        while True:
            # Build the message with simulated telemetry values.
            temperature = TEMPERATURE + (random.random() * 15)
            humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT % (temperature, humidity)
            message = IoTHubMessage(msg_txt_formatted)

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

            # Send the message.
            print("Sending message: %s" % message.get_string())
            client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #12
0
def iothub_client_telemetry_sample_run():
    try:
        client = iothub_client_init()
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )

        # Set up the callback method for direct method calls from the hub.
        client.set_device_method_callback(
            device_method_callback, None)

        client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)       

        while True:
            # Build the message with simulated telemetry values.
            temperature = TEMPERATURE + (random.random() * 15)
            humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT % (temperature, humidity)
            message = IoTHubMessage(msg_txt_formatted)

            prop_map = message.properties()
            if temperature > 30:
              prop_map.add("temperatureAlert", "true")
            else:
              prop_map.add("temperatureAlert", "false")
            # Send the message.
            print( "Sending message: %s" % message.get_string() )
            client.send_event_async(message, send_confirmation_callback, None)            
            time.sleep(INTERVAL)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Пример #13
0
def create_message(message_counter):
    AVG_WIND_SPEED = 10.0
    MIN_TEMPERATURE = 20.0
    MIN_HUMIDITY = 60.0

    temperature = MIN_TEMPERATURE + (random.random() * 10)
    humidity = MIN_HUMIDITY + (random.random() * 20)
    msg_txt_formatted = MSG_TXT % (
        AVG_WIND_SPEED + (random.random() * 4 + 2),
        temperature,
        humidity)

    # messages can be encoded as string or bytearray
    if (message_counter & 1) == 1:
        message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
    else:
        message = IoTHubMessage(msg_txt_formatted)

    # optional: assign ids
    message.message_id = "message_%d" % message_counter
    message.correlation_id = "correlation_%d" % message_counter
    # optional: assign properties
    prop_map = message.properties()
    prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false')

    return message
Пример #14
0
def iothub_client_telemetry_sample_run():

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

        while True:

            temperature = sense.get_temperature()
            humidity = sense.get_humidity()
            msg_txt_formatted = MSG_TXT % (temperature, humidity)
            message = IoTHubMessage(msg_txt_formatted)

            prop_map = message.properties()
            if temperature > 30:
                prop_map.add("temperatureAlert", "true")
            else:
                prop_map.add("temperatureAlert", "false")

            print("Sending message: %s" % message.get_string())
            client.send_event_async(message, send_confirmation_callback, None)
            sense.show_message(temperature + " C")
            time.sleep(1)
            sense.show_message(humidity + "%")
            time.sleep(2)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoT Hub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #15
0
def iothub_client_sample_run():

    try:

        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print("IoTHubClient is reporting state")
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state),
                                       send_reported_state_callback,
                                       SEND_REPORTED_STATE_CONTEXT)

        while True:
            # send a few messages every minute
            print("IoTHubClient sending %d messages" % MESSAGE_COUNT)

            for message_counter in range(0, MESSAGE_COUNT):
                temperature = MIN_TEMPERATURE + (random.random() * 10)
                humidity = MIN_HUMIDITY + (random.random() * 20)
                msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED +
                                               (random.random() * 4 + 2),
                                               temperature, humidity)
                # messages can be encoded as string or bytearray
                if (message_counter & 1) == 1:
                    message = IoTHubMessage(
                        bytearray(msg_txt_formatted, 'utf8'))
                else:
                    message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % message_counter
                message.correlation_id = "correlation_%d" % message_counter
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add("temperatureAlert",
                             'true' if temperature > 28 else 'false')

                client.send_event_async(message, send_confirmation_callback,
                                        message_counter)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % message_counter)

            # Wait for Commands or exit
            print("IoTHubClient waiting for commands, press Ctrl-C to exit")

            status_counter = 0
            while status_counter <= MESSAGE_COUNT:
                status = client.get_send_status()
                print("Send status: %s" % status)
                time.sleep(10)
                status_counter += 1

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")

    print_last_message_time(client)
Пример #16
0
def iothub_client_telemetry_sample_run():

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

        while True:
            # Build the message with simulated telemetry values.
            false = random.randrange(0, 30)
            true = random.randrange(0, 30)
            supplyOn = bool(TRUE_PROBALITY[true])
            fireAlert = bool(FALSE_PROBALITY[false])
            temperature = random.random() * TEMEPERATURE

            msg_txt_formatted = MSG_TXT % (supplyOn, fireAlert, temperature)
            message = IoTHubMessage(msg_txt_formatted)

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            prop_map = message.properties()
            if temperature > 70:
                prop_map.add("extremeHeatAlert", "true")
            else:
                prop_map.add("extremeHeatAlert", "false")

            # Send the message.
            print("Sending message: %s" % message.get_string())
            client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
Пример #17
0
    def iothub_client_telemetry_send(self):
        try:
            MSG_TXT = '{\"Timestamp\":%.0f,\"DeviceId\":\"%.10s\",\"location\":{\"lon\":%.5f,\"lat\":%.5f},\"Readings\":{\"Temperature\":{\"Internal\":%.2f,\"External\":%.2f}},\"Flow\":{\"In\":%.2f,\"Out\":%.2f},\"Pressure\":%.2f,\"Battery\":%.2f}'

            #print client.toString()

            # Build the message with simulated telemetry values.
            pressure = self.readPressure()
            flow = self.readFlow()
            temperature = self.readTemprature()
            battery = self.checkBattery()
            msg_txt_formatted = MSG_TXT % (calendar.timegm(
                time.gmtime()), self.deviceId, float(self.lat), float(
                    self.lon), temperature, temperature * 1.2, flow,
                                           flow * 1.354, pressure, battery)
            message = IoTHubMessage(msg_txt_formatted)

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

            # Send the message.
            print("Sending message: %s" % message.get_string())
            self.client.send_event_async(message,
                                         self.send_confirmation_callback, None)

        except IoTHubError as iothub_error:
            print("Unexpected error %s from IoTHub" % iothub_error)
            return
        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")
Пример #18
0
def iothub_client_telemetry_sample_run():
    # list of taps with starting keg weights
    taplist = [FULL_KEG_WEIGHT, FULL_KEG_WEIGHT, FULL_KEG_WEIGHT/2, FULL_KEG_WEIGHT/5];
    try:
        client = iothub_client_init()
        while True:
            for tap in range(len(taplist)):
                # 15% change of pouring a 200g-450g beer
                if (random.random() <= 0.15):
                    amount = random.randint(200, 450)
                    taplist[tap] -= amount
                if (taplist[tap] < 0):
                    taplist[tap] = FULL_KEG_WEIGHT; # keg magiclly refills when empty

                temperature = random.random() * 12  # 0-12 C
                msg_txt_formatted = MSG_TXT % \
                   (time.time(), DEVICE_ID, tap, temperature, taplist[tap])
                message = IoTHubMessage(msg_txt_formatted)

                prop_map = message.properties()
                if temperature > 10:
                  prop_map.add("temperatureAlert", "true")
                else:
                  prop_map.add("temperatureAlert", "false")

                # Send the message.
                print( "Sending message: %s" % message.get_string() )
                client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(REPORT_PERIOD_S)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Пример #19
0
def iothub_client_telemetry_sample_run():

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

        while True:
            # Build the message with simulated telemetry values.

            heartrate = ser.readline()
            heartrate = heartrate.decode("utf8").strip()
            msg_txt_formatted = MSG_TXT % (int(heartrate))
            message = IoTHubMessage(msg_txt_formatted)

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            prop_map = message.properties()
            if int(heartrate) > 140 and int(heartrate) < 50:
              prop_map.add("heartrateAlert", "false")
            else:
              prop_map.add("heartrateAlert", "true")

            # Send the message.
            print( "Sending message: %s" % message.get_string() )
            client.send_event_async(message, send_confirmation_callback, None)
            time.sleep(1)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Пример #20
0
def main(protocol):
    try:
        print ( "\nPython %s\n" % sys.version )
        print ( "IoT Hub Client for Python" )

        hub_manager = HubManager(protocol)
        device_client = iothub_client_init()
        print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )
        message = IoTHubMessage("mridu test message from module!!!!")
        message_counter = 0
        message.message_id = "message_%d" % message_counter
        message.correlation_id = "correlation_%d" % message_counter
        # optional: assign properties
        prop_map = message.properties()
        prop_map.add("temperatureAlert", 'false')
        device_client.send_event(message, properties=prop_map, send_context=message_counter)

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

        while True:
            time.sleep(1)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubModuleClient sample stopped" )
Пример #21
0
def send_to_Hub_callback(strMessage):
    if strMessage == []:
        return
    message = IoTHubMessage(bytearray(strMessage, 'utf8'))
    prop_map = message.properties()
    prop_map.add("appid", "scanner")
    hubManager.send_event_to_output("output1", message, 0)
    print('sent from send_to_Hub_callback')
Пример #22
0
def iothub_client():

    try:
        #Initialice Client
        client = iothub_client_init()

        print("IoT Device Simulator, press Ctrl-C to exit")
        #Specifies message format and values
        msg_txt_formatted = MSG_TXT % INTERFACE_PARAM_A
        message_counter = 0
        inp = 0
        while inp != 4:
            print("Press 1 to send a message to IOT Hub (Simulated message")
            print("Press 2 to send a picture to IOT Hub (Simulated message")
            print("Press 4 to EXIT")

            # messages can be encoded as string or bytearray

            if (message_counter & 1) == 1:
                message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
            else:
                message = IoTHubMessage(msg_txt_formatted)
            # optional: assign ids
            message.message_id = "message_%d" % message_counter
            message.correlation_id = "correlation_%d" % message_counter
            # optional: assign properties
            prop_map = message.properties()
            prop_text = "PropMsg_%d" % message_counter
            prop_map.add("Property", prop_text)
            inp = int(input())
            if inp == 1:
                #Sends a message to the Hub, reveives confirmation callback, adds counter
                client.send_event_async(message, send_confirmation_callback,
                                        message_counter)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % message_counter)
            if inp == 2:
                #Sends a file to Azure Storage Blob
                filename = "hello.jpg"
                content1 = open(filename, "rb")
                content = content1.read()
                #Send and shows confirmation
                client.upload_blob_async(filename, content, len(content),
                                         blob_upload_conf_callback, 1001)

            #status = client.get_send_status()
            #print ( "Send status: %s" % status )

            message_counter += 1
            if inp == 4:
                break

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
def iothub_client_sample_run():
    try:
        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print ( "IoTHubClient is reporting state" )
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)

        if not config.SIMULATED_DATA:
            sensor = BME280(address = config.I2C_ADDRESS)
        else:
            sensor = BME280SensorSimulator()

        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")
        while True:
            global MESSAGE_COUNT,MESSAGE_SWITCH
            if MESSAGE_SWITCH:
                # send a few messages every minute
                print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )
                temperature = sensor.read_temperature()
                humidity = sensor.read_humidity()
                timeStamp = time.time()
                dataValue = 0
                if DEVICE_TYPE=="T":
                    dataValue = temperature
                else : 
                    dataValue = humidity
                msg_txt_formatted = MSG_TXT % (
                    DEVICE_TYPE,
                    DEVICE_ID,
                    timeStamp,
                    dataValue)
                print (msg_txt_formatted)
                message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % MESSAGE_COUNT
                message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add("temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false")

                client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT)
                print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT )

                status = client.get_send_status()
                print ( "Send status: %s" % status )
                MESSAGE_COUNT += 1
            time.sleep(config.MESSAGE_TIMESPAN / 1000.0)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

    print_last_message_time(client)
def iothub_client_sample_run():
    try:
        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print("IoTHubClient is reporting state")
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state),
                                       send_reported_state_callback,
                                       SEND_REPORTED_STATE_CONTEXT)

        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS,
                                      "IoT hub connection is established")
        while True:
            #tripWire()
            global MESSAGE_COUNT, MESSAGE_SWITCH
            if MESSAGE_SWITCH:
                # send a few messages every minute
                print("IoTHubClient sending %d messages" % MESSAGE_COUNT)
                if tripWire() == 0:
                    lightState = "ON"
                    num = 0
                else:
                    lightState = "OFF"
                    num = 1
                #humidity = 1.23
                #temperature = 4.56
                #msg_txt_formatted = MSG_TXT % (temperature,humidity)
                msg_txt_formatted = MSG_TXT % num
                print(msg_txt_formatted)
                message = IoTHubMessage(msg_txt_formatted)
                message.message_id = "message_%d" % MESSAGE_COUNT
                message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                prop_map = message.properties()
                prop_map.add("Lightstate", lightState)
                client.send_event_async(message, send_confirmation_callback,
                                        MESSAGE_COUNT)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % MESSAGE_COUNT)

                status = client.get_send_status()
                print("Send status: %s" % status)
                MESSAGE_COUNT += 1
            time.sleep(1)  #Brandon

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        telemetry.send_telemetry_data(
            parse_iot_hub_name(), EVENT_FAILED,
            "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        GPIO.cleanup()
        print("IoTHubClient sample stopped")

    print_last_message_time(client)
Пример #25
0
    def send_event_to_output(self, message, properties, send_context):
        event = IoTHubMessage(bytearray(message, 'utf8'))
        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(event, send_confirmation_callback,
                                     send_context)
Пример #26
0
def ncd_send_message(msg, client):
    print(msg)
    message = IoTHubMessage(msg)
    message.type = "Telemetry"
    message.message_id = "message_0"
    message.correlation_id = "correlation_0"
    # # optional: assign properties
    prop_map = message.properties()
    client.send_event_async(message, send_confirmation_callback, 0)
    print ( "IoTHubClient.send_event_async accepted message for transmission to IoT Hub.")
Пример #27
0
def iothub_client_sample_run(msg):

    try:

        client = iothub_client_init()
        if client.protocol == IoTHubTransportProvider.MQTT:
            print("IoTHubClient is reporting state")
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state),
                                       send_reported_state_callback,
                                       SEND_REPORTED_STATE_CONTEXT)
        x = True
        while x == True:
            # send a few messages every minute
            print("IoTHubClient sending %d messages" % MESSAGE_COUNT)
            for message_counter in range(0, MESSAGE_COUNT):

                msg_txt_formatted = msg
                print "7777777777777777777777777777777777777777777777777777777"
                print msg_txt_formatted
                print "8888888888888888888888888888888888888888888888888888888"

                # messages can be encoded as string or bytearray
                if (message_counter & 1) == 1:
                    message = IoTHubMessage(
                        bytearray(msg_txt_formatted, 'utf8'))
                else:
                    message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % message_counter
                message.correlation_id = "correlation_%d" % message_counter
                # optional: assign properties
                prop_map = message.properties()
                # prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false')

                client.send_event_async(message, send_confirmation_callback, 1)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % message_counter)

            print("IoTHubClient waiting for commands, press Ctrl-C to exit")
            status = client.get_send_status()
            x = False
            status_counter = 0
            while status_counter <= 0:
                status = client.get_send_status()
                print("Send status: %s" % status)
                time.sleep(1)
                status_counter += 1

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
def iothub_client_sample_run():

    try:

        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print ( "IoTHubClient is reporting state" )
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)

        while True:
            # send a few messages every minute
            print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )

            for message_counter in range(0, MESSAGE_COUNT):
                temperature = MIN_TEMPERATURE + (random.random() * 10)
                humidity = MIN_HUMIDITY + (random.random() * 20)
                msg_txt_formatted = MSG_TXT % (
                    AVG_WIND_SPEED + (random.random() * 4 + 2),
                    temperature,
                    humidity)
                # messages can be encoded as string or bytearray
                if (message_counter & 1) == 1:
                    message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
                else:
                    message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % message_counter
                message.correlation_id = "correlation_%d" % message_counter
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false')

                client.send_event_async(message, send_confirmation_callback, message_counter)
                print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter )

            # Wait for Commands or exit
            print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" )

            status_counter = 0
            while status_counter <= MESSAGE_COUNT:
                status = client.get_send_status()
                print ( "Send status: %s" % status )
                time.sleep(10)
                status_counter += 1

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

    print_last_message_time(client)
    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(
            event, send_confirmation_callback, send_context)
Пример #30
0
def onHttpRequestSave():
    #request.form['rawData']
    # Data Sample {'temperature': 'nan', 'humidity': 'nan'}
    resp = request.get_json()
    resp['EventTime'] = datetime.datetime.now().strftime("%I:%M%p %B %d, %Y")
    payload = json.dumps(resp)
    data_t = strftime("%Y-%m-%dT%H:%M:%S+00:00", gmtime())
    #payload = '{ "data": '+payload+', "deviceId": "engine", "time": "'+data_t+'" }'
    #payload = payload
    print(payload, file=sys.stderr)
    print(type(payload),file=sys.stderr)
    
    headers = {
        'Content-Type': "application/json",
        'User-Agent': "PostmanRuntime/7.11.0",
        'Accept': "*/*",
        'Cache-Control': "no-cache",
        'Postman-Token': "0fa806d0-eee9-4960-8984-941eb1d8a340,0f174457-1072-4871-a853-2c2c8224f3f8",
        'Host': "us-central1-alwaystuned2019.cloudfunctions.net",
        'accept-encoding': "gzip, deflate",
        'content-length': "405",
        'Connection': "keep-alive",
        'cache-control': "no-cache"
        }
    
    
    response = requests.request("POST", url, data=payload, headers=headers)

    print(response.text, file=sys.stderr)
    
    try:
        client = iothub_client_init()
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit", file=sys.stderr)

        message = IoTHubMessage(payload)

        # Add a custom application property to the message.
        # An IoT hub can filter on these properties without access to the message body.
        prop_map = message.properties()
        

        # Send the message.
        print( "Sending message: %s" % message.get_string() , file=sys.stderr)
        client.send_event_async(message, send_confirmation_callback, None)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error , file=sys.stderr)
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" , file=sys.stderr)

    
    print(resp, file=sys.stderr)
    return saveData()
    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(
            event, send_confirmation_callback, send_context)
Пример #32
0
def composeStartMessage():
    msg_unformatted = {"startTime": time.asctime(time.localtime(time.time()))}
    msg_txt_formatted = json.dumps(msg_unformatted)
    message = IoTHubMessage(msg_txt_formatted)
    # optional: assign ids
    message.message_id = "message_%d" % MESSAGE_COUNT
    message.correlation_id = "correlation_%d" % MESSAGE_COUNT
    # optional: assign properties
    prop_map = message.properties()
    prop_map.add("startupMessage", "true")
    prop_map.add("telemetry", "false")
    return message
Пример #33
0
    def iothub_try(self, json, connection):
        try:
            print(json)
            client = self.iothub_client_init(connection)
            message_counter = 0

            msg_txt_formatted = json
            # messages can be encoded as string or bytearray
            #print ( msg_txt_formatted )

            if (message_counter & 1) == 1:
                message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            else:
                r = randint(0, 9)
                message = IoTHubMessage(msg_txt_formatted)

                if r > 7:
                    prop_map = message.properties()
                    prop_map.add("BatteryAlert", 'true')
                else:
                    prop_map = message.properties()
                    prop_map.add("BatteryAlert", 'false')
                # optional: assign ids
                message.message_id = "message_%d" % message_counter
                message.correlation_id = "correlation_%d" % message_counter

                client.send_event_async(message, send_confirmation_callback,
                                        message_counter)

            status = client.get_send_status()
            print("Send status: %s" % status)
            time.sleep(5)
            message_counter += 1

        except IoTHubError as iothub_error:
            print("Unexpected error %s from IoTHub" % iothub_error)
            return
        except KeyboardInterrupt:
            print("IoTHubClient sample stopped")
Пример #34
0
def iothub_client_sample_run():
    global gMQTTClient
    try:
        iotHubStopWatch = StopWatch(AZURE_REPORT_TIME)
        iotHubStopWatch.reset()
        client = iothub_client_init()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print ( "IoTHubClient is reporting state" )
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state), 
              send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)

        count = 1
        while True:
            if (True == iotHubStopWatch.isExpired()):
              global gSendMessage
              if gSendMessage:
                message = IoTHubMessage("JimsFridgeStatus")
              
                message.message_id = "message_%d" % count
                message.correlation_id = "correlation_%d" % count
              
                prop_map = message.properties()
                prop_map.add("FreezerDoor", str(gFreezerDoor))
                prop_map.add("FreezerTemp", str(gFreezerTemp))
                prop_map.add("FridgeDoor",  str(gFridgeDoor))
                prop_map.add("FridgeTemp",  str(gFridgeTemp))
                prop_map.add("BoredTime",   str(gBoredTime))
                prop_map.add("LockoutTime", str(gLockoutTime))
                prop_map.add("DoorTime",    str(gDoorTime))
                prop_map.add("LastTweet",   urllib.quote(gLastTweet))
                prop_map.add("WebTweet",    gWebTweet)

                client.send_event_async(message, send_confirmation_callback, count)
                count = count + 1

                status = client.get_send_status()
                iotHubStopWatch.reset()
            gMQTTClient.loop()
            time.sleep(0.01)
            pass

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

    print_last_message_time(client)
def iothub_client_shared_transport_sample_run():
    try:
        # create transport to share
        transport = IoTHubTransport(PROTOCOL, IOTHUBNAME, IOTHUBSUFFIX)

        client1 = iothub_client_init(transport, DEVICE_NAME1, DEVICE_KEY1)
        client1.set_message_callback(receive_message_callback1, RECEIVE_CONTEXT)

        client2 = iothub_client_init(transport, DEVICE_NAME2, DEVICE_KEY2)
        client2.set_message_callback(receive_message_callback2, RECEIVE_CONTEXT)

        print ( "IoTHubClient has been initialized" )

        while True:
            # send a few messages every minute
            print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )

            for message_counter in range(0, MESSAGE_COUNT):
                temperature = MIN_TEMPERATURE + (random.random() * 10)
                humidity = MIN_HUMIDITY + (random.random() * 20)
                msg_txt_formatted = MSG_TXT % (
                    AVG_WIND_SPEED + (random.random() * 4 + 2),
                    temperature,
                    humidity)
                # messages can be encoded as string or bytearray
                if (message_counter & 1) == 1:
                    message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
                else:
                    message = IoTHubMessage(msg_txt_formatted)
                # optional: assign ids
                message.message_id = "message_%d" % message_counter
                message.correlation_id = "correlation_%d" % message_counter
                # optional: assign properties
                prop_map = message.properties()
                prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false')

                if (message_counter % 2) == 0:
                    client1.send_event_async(message, send_confirmation_callback1, message_counter)
                else:
                    client2.send_event_async(message, send_confirmation_callback2, message_counter)
                print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter )

            # Wait for Commands or exit
            print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" )

            status_counter = 0
            while status_counter < MESSAGE_COUNT:
                status1 = client1.get_send_status()
                print ( "Send status client1: %s" % status1 )
                status2 = client2.get_send_status()
                print ( "Send status client2: %s" % status2 )
                time.sleep(10)
                status_counter += 1

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

    print_last_message_time(client1)
    print_last_message_time(client2)
Пример #36
0
def iothub_client_run():
    try:
        client = iothub_client_init()
        if client.protocol == IoTHubTransportProvider.MQTT:
            print ( "IoTHubClient is reporting state" )
            reported_state = "{\"newState\":\"standBy\"}"
            client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")
        while True:
            global MESSAGE_COUNT,MESSAGE_SWITCH
            if MESSAGE_SWITCH:
		        #-------------------------------------------------------------------------------------------
		        # This for loop reads the live data from the weather station and converts some of the data.
		        #     ptrraw is the WS pointer to circluar log buffer offset (16 bytes)
		        #     ptrhex ptr in Hex little endian
		        #     Convert to correct Relative Pressure HPA for location by adding 9.6
		        #     Convert MPS to KPH
                # Error Handling:
                #   Check for lost connection or null data. If found break from loop and do not send message
		        #-------------------------------------------------------------------------------------------
                for data, ptr, logged in ws.live_data():
                    record_time_local = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')
                    print("\n")
                    print(record_time_local)
                    ws_status = data['status']
                    ws_conn = data['status']['lost_connection']
		            # Check for lost connection
                    if ws_conn == True:
                        print("Lost Connection to Weather Station")
                        break
                    # Check for Null Data
                    if ws_conn == None:
                        print("No Data Returned From Weather Station")
                        break
                    # if connection OK process the data
                    ptrraw = ptr        
                    ptrhex = "%04x" % ptr       
                    record_time_utc = data['idx'].strftime('%Y-%m-%d %H:%M:%S')
                    hum_out = data['hum_out']
                    temp_out = data['temp_out']
                    hum_in = data['hum_in']
                    temp_in = data['temp_in']
                    abs_pres = data['abs_pressure']+9.6 
                    wind_gust = data['wind_gust']*3.6  
                    wind_avg = data['wind_ave']*3.6    
                    wind_dir = data['wind_dir']
                    wind_pos = wind_direction(wind_dir)
                    rain = data['rain']
                    msg_txt_formatted = MSG_TXT % (
                        DeviceID,
                        record_time_local,
                        hum_out,
                        temp_out,
                        hum_in,
                        temp_in,
                        abs_pres,
                        wind_gust,
                        wind_avg,
                        wind_dir,
                        wind_pos,
                        rain)
                    break
                if ws_conn == False:
                    print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )
                    message = IoTHubMessage(msg_txt_formatted)
                    # optional: assign ids
                    message.message_id = "message_%d" % MESSAGE_COUNT
                    message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                    # optional: assign properties
                    prop_map = message.properties()
                    prop_map.add("temperatureAlert", "true" if temp_out > TEMPERATURE_ALERT else "false")

                    client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT)
                    print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT )

                    status = client.get_send_status()
                    print ( "Send status: %s" % status )
                    MESSAGE_COUNT += 1
                time.sleep(config.MESSAGE_TIMESPAN / 1000.0)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient stopped" )
    print_last_message_time(client)