예제 #1
0
def send_aqburk_data_to_iothub():
    args = get_args()
    time_period = args.timelength
    msg_cnt = 0
    mac_pubid_map = {}
    mac_type_map = {}
    if os.path.isfile(args.devid):
        with open(args.devid, 'rt') as f:
            for line in f:
                apartment, inout, mac = line.strip().split()
                devid = sanitize_devid(mac)
                mac_pubid_map[devid] = f'{apartment}_{inout}'
                mac_type_map[devid] = 'indoor' if inout == 'in' else 'outdoor'
    else:
        print(f'File {args.devid} does not exist!')
        exit(1)
    try:
        client = iothub_client_init(args)
        start_time, end_time, next_send_time = get_next_send_time(time_period)
        while True:
            if get_now() < next_send_time:
                secs_left = (next_send_time - get_now()).total_seconds()
                logging.info(
                    'next send will be in {:.1f} seconds'.format(secs_left))
                logging.debug(
                    f'{get_now()}, {start_time}, {end_time}, {next_send_time}')
                if secs_left > 5:
                    sleeptime = secs_left / 2
                else:
                    sleeptime = 5
                time.sleep(sleeptime)
                continue
            start_time, end_time, next_send_time = get_next_send_time(
                time_period)
            devs = get_data(start_time, end_time, args)
            for devid in mac_pubid_map.keys():
                if devid not in devs:
                    continue
                message_data = create_message(start_time, mac_pubid_map[devid],
                                              mac_type_map[devid], devs[devid])
                message_json = json.dumps(message_data)
                message = IoTHubMessage(message_json)
                # Send the message.
                if args.dryrun is True:
                    logging.info("Dry-run, not sending: {}".format(
                        message.get_string()))
                else:
                    logging.info("Sending message: {}".format(
                        message.get_string()))
                    client.send_event_async(message,
                                            send_confirmation_callback, None)
                    time.sleep(.5)  # Sleep a bit between messages
                msg_cnt += 1
            time.sleep(5)  # sanity sleep

    except IoTHubError as iothub_error:
        logging.error(f"Unexpected error {iothub_error} from IoTHub")
        return
    except KeyboardInterrupt:
        print(f'\nIoTHubClient sample stopped. Sent total {msg_cnt} messages')
예제 #2
0
파일: Device.py 프로젝트: memodarr/simiot
    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")
예제 #3
0
def main(protocol):
    try:
        print("\nPython %s\n" % sys.version)
        print("IoT Edge Client for Python")

        hub_manager = HubManager(protocol)

        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:
            # 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)

            # Send the message.
            print("Steven demo sending message: %s" % message.get_string())
            hub_manager.forward_event_to_output("temperatureOutput", message,
                                                0)

            time.sleep(1)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubModuleClient sample stopped")
예제 #4
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" )
예제 #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")

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

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

            msg_txt_formatted = MSG_TXT % (humidity, temperature)
            message = IoTHubMessage(msg_txt_formatted)

            # 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")
예제 #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")

        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")
예제 #8
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" )
예제 #9
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")
예제 #10
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")
예제 #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" )

        # 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" )
예제 #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")
        temp = ''
        while True:
            # Build the message with simulated telemetry values.

            msg = open(
                "/home/pi/Desktop/project_master/cpp/output_files/data.json",
                'r')
            content = msg.read()
            msg.close()
            #or content=="[\n]" or content=="[]"
            if (temp == content or content == ""):
                continue
            else:
                message = IoTHubMessage(content)
                temp = content
                # Send the message.
                print("Sending message: %s" % message.get_string())
                client.send_event_async(message, send_confirmation_callback,
                                        None)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
예제 #13
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" )
예제 #14
0
def send_message(msg):
    global payload3, payload4
    #print("RAW message: %s" % msg)  
    
    # Case A: Em63 parameters
#    messageA = IoTHubMessage(msg)
#    print("Sending message: %s" % messageA.get_string() )
#    clientA.send_event_async(messageA, send_confirmation_callback, None)
    
    # Case B: dummy values
#    date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
#    sin=2
#    data = [{"Date": date, "Sinus": sin}]
#    messageA = IoTHubMessage(json.dumps(data))
#    print("Sending message: %s \n" % messageA.get_string() )
#    clientA.send_event_async(messageA, send_confirmation_callback, None)  
    
    # Case C: Em63 parameters
    # use a dictionary instead of a string
    #topicstr1 = "WIMMS/EM63/DATE"
    #topicstr2 = "WIMMS/EM63/@ActSimPara2"
    
    MSG_TXT = "{\"%s\": %.2f,\"%s\": %.2f}"
    #payload3=12
    #payload4=2*payload3
    msg_txt_formatted = MSG_TXT % (topicstr3, payload3, topicstr4, payload4)
    messageA = IoTHubMessage(msg_txt_formatted)
    if clientA:
        print("Sending message: %s \n" % messageA.get_string() )
        clientA.send_event_async(messageA, send_confirmation_callback, None)
    else:
        print("Skipping message to Azure. Not connected.")
예제 #15
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")
예제 #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")
        k = 0
        res = ''
        while True:
            inp = ser.read()
            if (inp.isdigit()):
                res = res + inp
                k = k + 1
                if (k == 3):
                    #print(res)

                    heart_point = float(res)
                    #print(heart_point)
                    msg_txt_formatted = MSG_TXT % (heart_point)
                    message = IoTHubMessage(msg_txt_formatted)
                    print("Sending message: %s" % message.get_string())
                    client.send_event_async(message,
                                            send_confirmation_callback, None)
                    time.sleep(1)

                    res = ''
                    k = 0
            else:
                if (res.isdigit()):
                    heart_point = float(res)
                    #print(heart_point)
                    msg_txt_formatted = MSG_TXT % (heart_point)
                    message = IoTHubMessage(msg_txt_formatted)
                    print("Sending message: %s" % message.get_string())
                    client.send_event_async(message,
                                            send_confirmation_callback, None)
                    time.sleep(1)
                #print(res)
                res = ''
                k = 0

    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_sample_run():
                client = iothub_client_init()
                print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )

                try:
                    temp = 0.01
                    hum = 0.01
                    [ temp,hum ] = dht(dht_sensor_port,0)       #Get the temperature and Humidity from the DHT sensor
                                                                #Change the second parameter to 0 when using DHT (instead of DHT Pro)
                                                                #You will get very large number values if you don't!
                    if (CtoF(temp) != lastTemp) and (hum != lastHum) and not math.isnan(temp) and not math.isnan(hum):
                    #print("lowC : ",FtoC(tooLow),"C\t\t","rightC  : ", FtoC(justRight),"C\t\t","highC : ",FtoC(tooHigh),"C") # comment these three lines
                    #print("lowF : ",tooLow,"F\t\tjustRight : ",justRight,"F\t\ttoHigh : ",tooHigh,"F")                       # if no monitor display
                        print("tempC : ", temp, "C\t\ttempF : ",CtoF(temp),"F\t\tHumidity =", hum,"%\r\n")
                
                        #lastHum = hum          # save temp & humidity values so that there is no update to the RGB LCD
                        ftemp = CtoF(temp)     # unless the value changes
                        ftemp = temp     # unless the value changes
                        #lastTemp = ftemp       # this reduces the flashing of the display
                        # print "ftemp = ",ftemp,"  temp = ",temp   # this was just for test and debug
                
                        bgList = calcBG(ftemp)           # Calculate background colors
                
                        t = str(ftemp)   # "stringify" the display values
                        h = str(hum)
                        # print "(",bgList[0],",",bgList[1],",",bgList[2],")"   # this was to test and debug color value list
                        setRGB(bgList[0],bgList[1],bgList[2])   # parse our list into the color settings
                        setText("Temp:" + t + "C      " + "Humidity :" + h + "%") # update the RGB LCD display
                
                    
                        # Build the message with real telemetry values.
                        temperature = temp
                        humidity = hum
                        msg_txt_formatted = MSG_TXT % (temperature, humidity)
                        message = IoTHubMessage(msg_txt_formatted)
                        # print("JSON payload = " + 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(5)
                except IoTHubError as iothub_error:
                    print ( "Unexpected error %s from IoTHub" % iothub_error )
                    return
                except KeyboardInterrupt:
                    print ( "IoTHubClient sample stopped" )
                except (IOError,TypeError) as e:
                    print("Error" + str(e))
예제 #18
0
파일: hubv2.py 프로젝트: mzkaramat/Rolling
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 iothub_client_telemetry_sample_run(events, bike_ids, rack_ids):

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

        #while True:
        for event in events:
            # 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)

            timestamp = event.time.strftime("%y-%m-%d %H:%M:%S")
            if event.type == Event.EventType.TAKE:
                rack_number = event.src
            else:
                rack_number = event.dest
            bike_number = event.bike
            msg_txt_formatted = MSG_TXT % (timestamp, rack_number, bike_number, event.type)
            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" )
예제 #20
0
def report_output(frame, res_json):
    json_string = json.dumps(res_json)
    print("Classification output: " + json_string)
    if enable_cloud_output:
        message = IoTHubMessage(json_string)
        print("Sending message: %s" % message.get_string())
        client.send_event_async(message, send_confirmation_callback, None)
    if enable_local_jpeg_output:
        now = datetime.datetime.now()
        date_prefix = str(now).replace(" ", "_")
        retval = cv2.imwrite(
            os.path.join(local_output_dir, date_prefix + ".jpeg"), frame)
예제 #21
0
def iothub_client_post_message(file_name):
    global ISSENDING
    ISSENDING = True
    while ISSENDING:
        message_client = iothub_client_init(MESSAGE_PROTOCOL)
        msg_txt_formatted = MSG_TXT % (DEVICEID, PROJECTNAME, file_name)
        message = IoTHubMessage(msg_txt_formatted)
        # Send the message.
        print("Sending message: %s" % message.get_string())
        message_client.send_event_async(message, send_confirmation_callback,
                                        None)
        time.sleep(7)
def iothub_client_telemetry_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.
            for root, dirs, files in os.walk(FTP_DIR):
                for file in files:
            
                    filePath = os.path.join(root, file)
                    print SENDING_FILES
                    
                    lock.acquire()
                    if filePath in SENDING_FILES:
                        continue
                    lock.release()
                    
                    try:
                        with open(filePath, "r") as json_file:  
                            data = json.load(json_file)
                            stringData = json.dumps(data)
    
                    except (ValueError, IOError) as e:
    
                        time.sleep(0.1)
                        continue
                    
                    
                    message = IoTHubMessage(stringData)
                    
                    # Send the message.
                    print( "Sending message: %s" % message.get_string() )
                    
                    lock.acquire()
                    SENDING_FILES.append(filePath)
                    lock.release()
                    
                    client.send_event_async(message, send_confirmation_callback, filePath)
                    
                    time.sleep(0.5)
                    
                    
                
    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
예제 #23
0
def iothub_client_telemetry_sample_run(direction, counter):
    try:
        client = iothub_client_init()
        # Build the message with simulated telemetry values.
        msg_txt_formatted = MSG_TXT % (direction, counter)
        message = IoTHubMessage(msg_txt_formatted)

        # 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
예제 #24
0
def iothub_client_post_message():
    global ISSENDING
    ISSENDING = True
    while ISSENDING:
        client = IoTHubClient(HUB_CONNECTION_STRING, MESSAGE_PROTOCOL)
        print("IoT Hub device sending periodic messages, press Ctrl-C to exit")

        msg_txt_formatted = MSG_TXT % (DEVICEID, PROJECTNAME, FILENAME)
        message = IoTHubMessage(msg_txt_formatted)

        # Send the message.
        print("Sending message: %s" % message.get_string())
        client.send_event_async(message, send_confirmation_callback, None)
        time.sleep(7)
예제 #25
0
def readValue():
    # Turn on LCD backlight
    mcp.output(3, 1)
    lcd.begin(16, 2)

    # Try to init client and send messages
    try:
        client = initHub()
        print("IoT device sending messages, press Ctrl+C to exit")

        while True:
            # Read and print value at channel zero
            value = analogRead(0)

            # Value to water or not
            toWater = False

            # Display the value and format moisture in JSON
            lcd.setCursor(0, 0)
            lcd.message('Moisture: %d' % (value) + '\n')
            if value > 200:
                lcd.message('Please water!' + '\n')
                msg_txt = MSG_TXT % (value)
                toWater = True
            elif value <= 200:
                lcd.message('Still good :D' + '\n')
                msg_txt = MSG_TXT % (value)
                toWater = False
            message = IoTHubMessage(msg_txt)

            # Create row to be stored
            rowToStore = [value, toWater]

            # Open file and write
            with open('waterLog.csv', 'a') as csvFile:
                writer = csv.writer(csvFile)
                writer.writerow(rowToStore)

            # Close file after writing
            csvFile.close()

            # Send 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
def iothub_client_telemetry_run():

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

        while True:

            (chip_id, chip_version) = readBME280ID()
            print "Chip ID     :", chip_id
            print "Version     :", chip_version

            temperature, pressure, humidity = readBME280All()

            print "Temperature : ", temperature, "F"
            print "Pressure : ", pressure, "hPa"
            print "Humidity : ", humidity, "%"

            # Build the message with simulated telemetry values.
            ##temperature = TEMPERATURE + (random.random() * 15)
            ##humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT % (temperature, pressure, 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 > 60:
                prop_map.add("temperatureAlert", "true")
            else:
                prop_map.add("temperatureAlert", "false")

            (chip_id, chip_version) = readBME280ID()
            print "Chip ID     :", chip_id
            print "Version     :", chip_version

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

            #sleep for 60 seconds so messages per day is under free IoT Hub max of 8000
            time.sleep(60)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient stopped")
예제 #27
0
def bag_event(client, eventtype, bagid, partnerid, employeeid, storeid):
    try:
        msg_txt_formatted = MSG_TXT % (eventtype, bagid, partnerid, employeeid,
                                       storeid, "", datetime.datetime.utcnow())
        message = IoTHubMessage(msg_txt_formatted)

        # Send the message.
        print("[%s] Bag %s is scaned wait for pipeline events" %
              (eventtype, bagid))
        print("%s" % message.get_string())
        client.send_event_async(message, send_confirmation_callback, None)
        interval = random.randrange(1, 5, 2)
        time.sleep(interval)
    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
예제 #28
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.
 
            result = instance.read()

            if result.is_valid():
                
                temperature = result.temperature
                
                humidity = result.humidity
                print("Last valid input: " + str(datetime.datetime.now()))
                print("Temperature: %-3.1f C" % result.temperature)
                print("Humidity: %-3.1f %%" % result.humidity)
                MSG_TXT = "The temperature is {0} and Humidity is {1}%".format(int(result.temperature) * 9/5+32 , result.humidity)
                print(MSG_TXT)
                
            msg_txt_formatted = {"temperature": temperature ,"humidity": humidity }
            message = IoTHubMessage(str(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(temperature) > 30:
              prop_map.add("temperatureAlert", "true")
              print("Temp alert sent, too hot.")
            elif int(temperature) < 30:
              prop_map.add("temperatureAlert", "false")
              print("Temp normal, no alert sent.")

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

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
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:

            GPIO.output(TRIG, True)  #Set TRIG as HIGH
            time.sleep(0.00001)  #Delay of 0.00001 seconds
            GPIO.output(TRIG, False)  #Set TRIG as LOW

            while GPIO.input(ECHO) == 0:  #Check whether the ECHO is LOW
                pulse_start = time.time(
                )  #Saves the last known time of LOW pulse

            while GPIO.input(ECHO) == 1:  #Check whether the ECHO is HIGH
                pulse_end = time.time(
                )  #Saves the last known time of HIGH pulse

            pulse_duration = pulse_end - pulse_start  #Get pulse duration to a variable

            distance = pulse_duration * 17150  #Multiply pulse duration by 17150 to get distance
            distance = round(distance, 2) - 0.5  #Round to two decimal points

            if distance > 2 and distance < 400:
                print("Distance:", distance, "cm")
            else:
                print("Out of range.")

            msg_txt_formatted = MSG_TXT % (distance)

            message = IoTHubMessage(msg_txt_formatted)

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

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")
예제 #30
0
def on_message(client, userdata, msg):
    my_payload = json.loads(msg.payload.decode("utf-8")[1:-1])
    print('Msg received from topic={topic}\n{content}'.format(topic=msg.topic, content=my_payload))
    
    if my_payload["name"] == "Tick":
        print("\n---- Tick motion detected. Transferring data to Azure IoT backend ----")  
        msg_txt = "{\"deviceId\": \"%s\", \"probability\": %.2f}" % (my_payload["deviceId"], my_payload["selfProbability"])
        # print( "Compiled message: %s" % msg_txt )

        try:                       
            # Send the message to Azure IoT Hub.            
            message = IoTHubMessage(msg_txt)
            message.set_content_type_system_property("application/json")    
            # print(message.get_content_type_system_property())         
            print( "Sending message: %s" % message.get_string() )                   
            azureclient.send_event_async(message, send_confirmation_callback, None)
        except IoTHubError as iothub_error:
            print ( "Unexpected error %s from IoTHub" % iothub_error )
            return