def callback(data): rospy.loginfo(rospy.get_caller_id() + '===CMD_VEL %s', data) #pub = rospy.Publisher('cmd_vel', Twist, queue_size=10) #cmd = Twist() iotc.sendTelemetry("{ \ \"linear-x\": " + str(data.linear.x) + " , \ \"linear-y\": " + str(data.linear.y) + " , \ \"linear-z\": " + str(data.linear.z) + " , \ \"angular-x\": " + str(data.angular.x) + " , \ \"angular-y\": " + str(data.angular.y) + " , \ \"angular-z\": " + str(data.angular.z) + " }")
iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) # Start by Connecting then Sending iotc.connect() (airtemp, airpressure, airhumidity) = readBME280All(addr=DEVICE) (r, g, b, c, lux, color_temp) = readTCSAll() iotc.sendTelemetry("{ \ \"airtemperature\": " + str(airtemp) + ", \ \"airpressure\": " + str(airpressure) + ", \ \"airhumidity\": " + str(airhumidity) + ", \ \"lux\": " + str(lux) + ", \ \"colortemp\": " + str(color_temp) + ", \ \"green\": " + str(g) + ", \ \"blue\": " + str(b) + ", \ \"clear\": " + str(c) + ", \ \"red\": " + str(r) + "}") starttime = time.time() while iotc.isConnected(): time.sleep(5) iotc.doNext() # do the async work needed to be done for MQTT elapsedtime = time.time() - starttime if elapsedtime > 66: print("Sending telemetry..") ## Collect Telemetry Data (airtemp, airpressure, airhumidity) = readBME280All(addr=DEVICE) (r, g, b, c, lux, color_temp) = readTCSAll() elapsedtime = 0
# Aaure IoT Central iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() # BME280 setup() get_calib_param() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT # read BME280 Data: data = [] for i in range(0xF7, 0xF7 + 8): data.append(bus.read_byte_data(i2c_address, i)) pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4) temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4) hum_raw = (data[6] << 8) | data[7] if gCanSend == True: iotc.sendTelemetry("{ \ \"temp\": " + str(compensate_T(temp_raw)) + ", \ \"pressure\": " + str(compensate_P(pres_raw)) + ", \ \"humidity\": " + str(compensate_H(hum_raw)) + "}") time.sleep(60)
def onmessagesent(info): print("\t- [onmessagesent] => " + str(info.getPayload())) def oncommand(info): print("- [oncommand] => " + info.getTag() + " => " + str(info.getPayload())) def onsettingsupdated(info): print("- [onsettingsupdated] => " + info.getTag() + " => " + info.getPayload()) iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: if gCounter % 20 == 0: gCounter = 0 print("Sending telemetry..") iotc.sendTelemetry("{ \ \"temp\": " + str(randint(20, 45)) + ", \ \"accelerometerX\": " + str(randint(2, 15)) + ", \ \"accelerometerY\": " + str(randint(3, 9)) + ", \ \"accelerometerZ\": " + str(randint(1, 4)) + "}") gCounter += 1
def onmessagesent(info): print("\t- [onmessagesent] => " + str(info.getPayload())) def oncommand(info): print("command name:", info.getTag()) print("command value: ", info.getPayload()) def onsettingsupdated(info): print("setting name:", info.getTag()) print("setting value: ", info.getPayload()) iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: if gCounter % 20 == 0: gCounter = 0 print("Sending telemetry..") iotc.sendTelemetry("{\"water_drunk\": " + str(random.randint(20, 45)) + "}") gCounter += 1
gas_data = gas.read_all() save_data(4, gas_data.oxidising / 1000) save_data(5, gas_data.reducing / 1000) save_data(6, gas_data.nh3 / 1000) pms_data = None try: pms_data = pms5003.read() except pmsReadTimeoutError: logging.warn("Failed to read PMS5003") else: save_data(7, float(pms_data.pm_ug_per_m3(1.0))) save_data(8, float(pms_data.pm_ug_per_m3(2.5))) save_data(9, float(pms_data.pm_ug_per_m3(10))) print("Sending telemetry..") iotc.sendTelemetry("{ \ \"temperature\": " + str(values[variables[0]][-1]) + ", \ \"pressure\": " + str(values[variables[1]][-1]) + ", \ \"humidity\": " + str(values[variables[2]][-1]) + ", \ \"light\": " + str(values[variables[3]][-1]) + ", \ \"oxidation\": " + str(values[variables[4]][-1]) + ", \ \"nh3\": " + str(values[variables[6]][-1]) + ", \ \"pm1\": " + str(values[variables[7]][-1]) + ", \ \"pm25\": " + str(values[variables[8]][-1]) + ", \ \"pm10\": " + str(values[variables[9]][-1]) + ", \ \"redu\": " + str(values[variables[5]][-1]) + "}") gCounter += 1
newState = "NOMINAL" if(newState != oldState): iotc.sendState("{ \"state\": \""+ newState + "\"}") #report status change only once print("Status changed to "+ newState) oldState ="NOMINAL" setRGB(0,128,64) # Set background color to light blue # read temperature and humidity from Grove lib temperature, humidity = grove_dht_pro_once.main() print("#" + str(gCounter) +" Sending telemetry...") iotc.sendTelemetry("{ \ \"test\": " + str(0) + ", \ \"temperature\": " + str(temperature) + ", \ \"humidity\": " + str(humidity) + ", \ \"vibration\": " + str(vibration) + "}") display_running_indicator("=") display_status("Connected=>Azure\n#"+str(gCounter)+" T:"+str(temperature)+"V:"+str(vibration)) gCounter += 1 time.sleep(5) # each 5 seconds (instead of gCounter % 20 == 0 as the original script was doing) except KeyboardInterrupt: #When interruptedd interactively exit and display default message print('Interrupted by keyboard') display_status("Terminating..") time.sleep(15) ipv4_addr = os.popen('ip addr show wlan0 | grep "\<inet\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip() display_status(ipv4_addr + '\npi:arrowiot ') setRGB(0,255,0) try:
def send(): global sent sent += 1 print("Sending telemetry.. sent:{}, confirmed: {}".format(sent, confirmed)) iotc.sendTelemetry("{\"index\": " + str(sent) + "}")
airQuality = values[1].split('=')[1] print(values) # If IoT Central is Connected, then send our Telemetry. if iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: if gCounter % 5 == 0: gCounter = 0 print("Sending telemetry..") iotc.sendTelemetry("{ \ \"temp\": " + str(randint(20, 45)) + ", \ \"airQuality\": " + str(airQuality) + ", \ \"zombieDetected\": " + str(zombieDetected) + ", \ \"accelerometerX\": " + str(randint(2, 15)) + ", \ \"accelerometerY\": " + str(randint(3, 9)) + ", \ \"accelerometerZ\": " + str(randint(1, 4)) + "}") gCounter += 1 # grab the frame from the threaded video stream frame = vs.read() # resize the frame to have a width of 600 pixels (while # maintaining the aspect ratio), and then grab the image # dimensions frame = imutils.resize(frame, width=600) (h, w) = frame.shape[:2]
#print("- [oncommand] => " + info.getTag() + " => " + str(info.getPayload())) mslog.info('[oncommand] => ' + info.getTag() + ' => ' + +str(info.getPayload())) def onsettingsupdated(info): #print("- [onsettingsupdated] => " + info.getTag() + " => " + info.getPayload()) mslog.info('[onsettingsupdated] => ' + info.getTag() + ' => ' + info.getPayload()) iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() while iotc.isConnected(): iotc.doNext() if gCanSend == True: if gCounter % 20 == 0: gCounter = 0 cur = time.time() now = datetime.utcfromtimestamp(cur).strftime('%Y-%m-%d %H:%M:%S') jsonStr = '{"temperature": ' + str(randint(20, 45)) + '}' print("[" + now + "] Sending telemetry...", gCounter) iotc.sendTelemetry(jsonStr) gCounter += 1
def postprocess(frame, outs): frameHeight = frame.shape[0] frameWidth = frame.shape[1] classIds = [] confidences = [] boxes = [] additionaltext = [] framecolor = [] # Scan through all the bounding boxes output from the network and keep only the # ones with high confidence scores. Assign the box's class label as the class with the highest score. classIds = [] confidences = [] boxes = [] additionaltext = [] framecolor = [] masktext = "" global resetcnt global alertcnt for out in outs: for detection in out: scores = detection[5:] classId = np.argmax(scores) confidence = scores[classId] if confidence > confThreshold: center_x = int(detection[0] * frameWidth) center_y = int(detection[1] * frameHeight) width = int(detection[2] * frameWidth) height = int(detection[3] * frameHeight) left = int(center_x - width / 2) top = int(center_y - height / 2) classIds.append(classId) confidences.append(float(confidence)) boxes.append([left, top, width, height]) #framecolor = (255, 0, 0) #additionaltext = '' #personIme = image[x1:x2, y1:y2] #print(personIme) try: encodedFrame = cv.imencode(".jpg", frame)[1].tostring() # Send over HTTP for processing response = sendFrameForProcessing(encodedFrame) print(response) if response != '': # if response['confidence'] > 0.50 and str( response['class'] ) == 'Facemas':#ConstructionHelmet # #framecolor = (0, 255, 0) # framecolor.append((0, 255, 0)) # masktext = str.format('[Mask, %.2f]' % response['confidence']) # additionaltext.append(masktext) # #resetcnt=11 # else: # #framecolor = (0, 0, 255) # masktext = str.format('[No Mask, %.2f]' % response['confidence']) # framecolor.append((0, 0, 255)) # additionaltext.append(masktext) # resetcnt = resetcnt + 1 if response['confidence'] > 0.50 and str( response['class'] ) == 'Facemask': #ConstructionHelmet #framecolor = (0, 255, 0) framecolor.append((0, 255, 0)) masktext = str.format('[Mask, %.2f]' % response['confidence']) additionaltext.append(masktext) #msg = Message('{"mask":"Yes","alertcnt":'+str(alertcnt)+',"level":' + str(response['confidence']*100)+'}') iotc.sendTelemetry('{"mask":"Yes","alertcnt":' + str(alertcnt) + ',"level":' + str(response['confidence'] * 100) + '}') #device_client.send_message(msg) #msg = Message("test wind speed " + str(i)) #resetcnt=11 elif response['confidence'] > 0.30 and str( response['class']) == 'Nomas': #framecolor = (0, 0, 255) masktext = str.format('[No Mask, %.2f]' % response['confidence']) framecolor.append((0, 0, 255)) additionaltext.append(masktext) msg = '{"mask":"No","alertcnt":' + str( alertcnt) + ',"level":' + str( response['confidence'] * 100) + '}' resetcnt = resetcnt + 1 else: print(resetcnt) framecolor.append((255, 0, 0)) additionaltext.append("") #print(resetcnt) print(resetcnt) iotc.sendProperty('{"masktext":"' + masktext + '"}') #message = IoTHubMessage(masktext) if (resetcnt > 3): #client.send_event_async(message, send_confirmation_callback, None) iotc.sendTelemetry(msg) iotc.sendState('{ "status": "WARNING"}') # iotc.sendTelemetry("{ \ # \"temp\": " + str(randint(20, 45)) + ", \ # \"accelerometerX\": " + str(randint(2, 15)) + ", \ # \"accelerometerY\": " + str(randint(3, 9)) + ", \ # \"accelerometerZ\": " + str(randint(1, 4)) + "}") print("Message transmitted to IoT Central") resetcnt = 0 alertcnt = alertcnt + 1 except Exception as e: print('Error frmae processing: ' + str(e)) # Perform non maximum suppression to eliminate redundant overlapping boxes with # lower confidences. indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold) for i in indices: i = i[0] box = boxes[i] left = box[0] top = box[1] width = box[2] height = box[3] drawPred(classIds[i], confidences[i], additionaltext[i], framecolor[i], left, top, left + width, top + height)
def main(): global gCounter global ledState global iotc ## Start Configuration ## Azure IoT Central #region # Set Callback functions iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) # Set logging iotc.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) #endregion ## Sensor #region try: # Use the BCM pin numbering GPIO.setmode(GPIO.BCM) # Set ledPin to be an output pin GPIO.setup(ledPin, GPIO.OUT) #endregion ## Start Post-Configuration iotc.connect() # Send the device property and ledstate once at the start of the program, so telemetry is shown in IoT Central. if iotc.isConnected() and gCanSend == True: sendDeviceProperty() sendLedState() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: # Do this when gCounter is 20. if gCounter % 20 == 0: gCounter = 0 print("Sending telemetry..") # The key in the json that will be sent to IoT Central must be equal to the Name in IoT Central!! # eg. "Temperature" in the json must equal (case sensitive) the Name field "Temperature" in IoT Central # if you want real temp data use function: readTempSensor() iotc.sendTelemetry("{ \ \"Temperature\": " + str(randint(0, 25)) + ", \ \"Pressure\": " + str(randint(850, 1150)) + ", \ \"Humidity\": " + str(randint(0, 100)) + ", \ \"CPUTemperature\": " + str(getCPUtemperature()) + ", \ }") gCounter += 1 except Exception as ex: print("Exception: " + str(ex)) finally: GPIO.cleanup()
def sendLedState(): global iotc iotc.sendTelemetry("{ \ \"LedState\": \"" + str(ledStateName[ledState]) + "\" \ }")
def oncommand(info): print("- [oncommand] => " + info.getTag() + " => " + str(info.getPayload())) if info.getTag() == "led_toggle": print("Toggling LED state") led.toggle() def onsettingsupdated(info): print("- [onsettingsupdated] => " + info.getTag() + " => " + info.getPayload()) iotc.on("ConnectionStatus", onconnect) iotc.on("MessageSent", onmessagesent) iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: if time.time() - lastSent > interval: print("Sending telemetry") payload = '{{"temp": {0},"du": {1}}}' iotc.sendTelemetry(payload.format(cpu.temperature, disk.usage)) lastSent = time.time()
iotc.on("Command", oncommand) iotc.on("SettingsUpdated", onsettingsupdated) iotc.connect() while iotc.isConnected(): iotc.doNext() # do the async work needed to be done for MQTT if gCanSend == True: if gCounter % 5 == 0: gCounter = 0 #get weather data from sense hat temp = sense.get_temperature() press = sense.get_pressure() hum = sense.get_humidity() print("Sending telemetry..") iotc.sendTelemetry("{ \ \"temp\": " + str(temp) + ", \ \"pressure\": " + str(press) + ", \ \"humidity\": " + str(hum) + " }") temp = round(temp, 2) press = round(press, 2) hum = round(hum, 2) #show weather sensor data on sense hat led matrix sense.show_message("Temp: " + str(temp) + " Pressure: " + str(press) + " Humidity: " + str(hum)) gCounter += 1