def initMQTT(self): self.mosquittoCommand = MQTT( server=settings['Command server address'], login=settings['Command server login'], password=settings['Command server password'], port=int(settings['Command server port'])) self.mosquittoCommand.sendTopic = settings['Robot name'] self.mosquittoCommand.client.on_connect = self.onCon self.mosquittoCommand.client.on_message = self.onMessage self.mosquittoCommand.isMain = True self.mosquittoCommand.connect() print(settings['UseTelemetry']) try: if settings['UseTelemetry']: print('Using Telem') self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon except KeyError: pass try: with open('keyboard.json', 'r+') as file: self.keyCommand = json.load(file) except (FileNotFoundError, json.decoder.JSONDecodeError): pass
def setup_mqtt_communication(self, client_id, host="192.168.0.120"): self.mqtt_comm = MQTT(client_id=client_id, host=host) self.mqtt_comm.client.loop_start() self.use_mqtt = True # invoke it just once self.read_messages_and_update_UI() pass
def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() response = BytesIO() response.write(b'This is POST request. ') response.write(b'Received: ') response.write(body) self.wfile.write(response.getvalue()) print("body: ", body) mqtt = MQTT(ip="51.83.42.157", port=1883, qos=2, mode=Message_mode.NON_BLOCKING) mqtt.connect() mes = body.decode("utf-8") print("decoded:", mes) if Message.is_str_message(mes): m = Message.from_string(mes) mqtt.publish_message("database/message", m) print("sent message to broker") else: mqtt.publish_string("basestation/startmeasurement", mes) print("sent measurement start command to broker") mqtt.disconnect()
def start(self): self.start_t_arg("Sound-Thread", self.ps, "female_system_start.wav") self.mqtt_handler = mq.Mqtt() self.mqtt_handler.connect_mqtt() self.initialize_processes() self.start_t("Alive-Service-1", self.keep_alive_service) self.start_t_arg("Sound-Thread", self.ps, "female_system_startet.wav") if self._console: self.console()
def main(): # Load configuration YAML path = os.path.dirname(os.path.realpath(__file__)) fp = open(path + '/config.yaml', 'r') cfg = yaml.safe_load(fp) # Start deamon # PID file location if platform.system() == 'Windows': pidfile = 'c:\\tmp\\IPCam_daemon.pid' recording_dir = 'S:\\WCAU45635050\\webcam' elif platform.system() == 'Linux': pidfile = '/tmp/IPCam_daemon.pid' recording_dir = '/home/pi/WCAU45635050/webcam' # Check if deamon already running if os.path.isfile(pidfile): with open(pidfile, 'r') as fp: pid = int(fp.read()) if psutil.pid_exists(pid): sys.exit() # Initialize logging init_log('Recording_checker') # Register current deamon with open(pidfile, 'w') as fp: pid = str(os.getpid()) talk_log('Registering recording checker with PID %s' % pid, 'info') fp.write(pid) # Set up MQTT client mqtt_client = MQTT.Client(**cfg['mqtt']) mqtt_client.subscribe('nodes/#') # Set up IPCam clients IPCam_motor = IPCam.Client(**cfg['ipcam']['motor']) IPCam_motor.set_base_path(recording_dir) # Local variables last_motion = 0 alarm_on = False while True: time.sleep(0.1) # Check for new motion at Motor IPCam, unless the alarm or the light is already on if IPCam_motor.new_recording(): talk_log('New motion detected!') mqtt_client.publish(cfg['mqtt']['nodes']['smarthouse'], 93, 1)
try: dataProxyHandler = DataProxy.dataProxy(SQLProxy=sqlHandler, syncEvents=dataProxySyncEvent, lock=dataProxyLock, proxy=lastData, loggingFile=loggingFile) except Exception as reason: logger.critical("Data Proxy initialization error. Reason = " + str(reason)) quit() try: mqttHandler = MQTT.MQTTclient(brokerAddress=brkAdr, username=brkUsername, password=brkPassword, syncEvents=mqttSyncEvent, dataProxy=dataProxyHandler, loggingFile=loggingFile) except Exception as reason: logger.critical("MQTT initialization error. Reason = " + str(reason)) quit() try: dataServerListener = DataServerAccepter( address='', port=2000, dataProxy=dataProxyHandler, dataProxyLock=dataProxyLock, dataProxySyncEvent=dataProxySyncEvent, logger=logger) except Exception as reason:
if led == 'red': led_number = 4 elif led == 'green': led_number = 1 elif led == 'yellow': led_number = 2 else: log ("Error: Unknown led.") # # Turn on or off the LED # if request['intent']['name'] == 'ledControlIntent': action = request['intent']['slots']['led_onoff']['value'] log (action) if action == 'on': MQTT.publish_event_to_client('s5d9', 'L'+ str(led_number) + ':1') elif action == 'off': MQTT.publish_event_to_client('s5d9', 'L'+ str(led_number) + ':0') else: log ("Error: Unknown action.") response_txt = "The " + led + " led is turned " + action + "." # # Blink the LED for a number of times. # elif request['intent']['name'] == 'ledBlinkIntent': blink_number = int(request['intent']['slots']['blink_num']['value']) log (blink_number) if blink_number == 0: MQTT.publish_event_to_client('s5d9', 'L'+ str(led_number) + ':0') response_txt = "The " + led + " led is turned off." elif blink_number <= 5:
class test(Frame): mosquittoCommand = None mosquittoTelemetry = None bindCommand = None useTelemetry = None fStart = False keyCommand = {} notification_manager = Notification_Manager(background="white") videoPanels = [] buttons = [] def __init__(self, parent): super().__init__(parent) self.pitchImage = PhotoImage(file="pitch.png") self.camImage = PhotoImage(file="cctv-camera.png") self.pitchMap = Label(image=self.pitchImage) self.gui = parent self.useTelemetry = BooleanVar() self.gui.bind('<KeyRelease>', self.keyRelease) self.gui.bind('<Escape>', self.showMap) self.gui.bind('<KeyPress>', self.keyPress) self.n1Flag = False try: self.initMQTT() except TypeError: self.fStart = True pass self.initUI() if not self.fStart: makeUI = threading.Thread(target=self.initButtons, args=(), daemon=False) makeUI.start() pingThread = threading.Thread(target=self.robotPing, args=(), daemon=True) pingThread.start() def initUI(self): self.gui.title(language['titleMainWindow']) self.gui.geometry('1280x720') self.gui.menubar = Menu() self.gui.config(menu=self.gui.menubar) self.gui.menubar.add_command(label=language['settings'], command=self.settings_clicked) def initButtons(self): global cams ml1 = int(round(time.time() * 1000)) while cams == json.loads( '{}') and int(round(time.time() * 1000)) - ml1 < 2000: print(int(round(time.time() * 1000)) - ml1 < 2000) time.sleep(0.1) print(cams) if int(round(time.time() * 1000)) - ml1 > 2000: self.notification_manager.alert(language['serverTimeError']) else: i = 0 for camera in cams: vp = Frame(self.gui) can = Canvas(vp) can.place(x=0, y=0) self.videoPanels.append(vp) print(camera['address']) vlcPlayer(self.videoPanels[i], camera['address']) btn = Button(self.pitchMap, command=lambda i=i: self.changeToCam(i), image=self.camImage) self.buttons.append(btn) btn.place(x=camera['x'], y=camera['y']) i += 1 self.pitchMap.place(relx=0.5, anchor=N) def initMQTT(self): self.mosquittoCommand = MQTT( server=settings['Command server address'], login=settings['Command server login'], password=settings['Command server password'], port=int(settings['Command server port'])) self.mosquittoCommand.sendTopic = settings['Robot name'] self.mosquittoCommand.client.on_connect = self.onCon self.mosquittoCommand.client.on_message = self.onMessage self.mosquittoCommand.isMain = True self.mosquittoCommand.connect() print(settings['UseTelemetry']) try: if settings['UseTelemetry']: print('Using Telem') self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon except KeyError: pass try: with open('keyboard.json', 'r+') as file: self.keyCommand = json.load(file) except (FileNotFoundError, json.decoder.JSONDecodeError): pass def changeToCam(self, cam): self.pitchMap.place_forget() for i in range(len(self.videoPanels)): self.videoPanels[i].place_forget() self.buttons[i].place_forget() self.videoPanels[cam].place(relx=.5, rely=0.1, anchor='n') self.videoPanels[cam].pack_propagate(False) self.videoPanels[cam].grid_propagate(False) self.videoPanels[cam].configure(height=self.gui.winfo_height() / 1.5, width=self.gui.winfo_width() / 1.5) def showMap(self, event): i = 0 for camera in cams: self.buttons[i].place(x=camera['x'], y=camera['y']) self.videoPanels[i].place_forget() i += 1 self.pitchMap.place(relx=0.5, anchor=N) def setCams(self, cameras): global cams cams = json.loads(cameras) def onMessage(self, client, userdata, msg): rec = str(msg.payload) rec = rec[2:len(rec) - 1] print(msg.topic) topic = str(msg.topic) global cams if topic.find('server') > -1: if not rec == 'cams': try: self.setCams(rec) except ValueError: pass elif topic.find('status') > -1: if rec == '200': self.notification_manager.success(codeNames[rec]) self.n1Flag = False print("yEP3") elif rec == '202' or rec == '203' or rec == '204': if not self.n1Flag: self.notification_manager.alert(codeNames[rec]) self.n1Flag = True elif rec == '201': global millis2 millis2 = int(round(time.time() * 1000)) # It`s a ping to a bluetooth car # Do what you need print(millis2 - millis1) if self.nFlag: self.notification_manager.success('Ping answer received') pass elif topic.find('/') > -1: pass else: print(rec) def robotPing(self): while True: self.mosquittoCommand.publish(self.mosquittoCommand.sendTopic, "w") global millis1, millis2 if millis2 - millis1 < -1000: if not self.nFlag: self.notification_manager.alert('Bluetooth ping error') self.nFlag = True else: self.nFlag = False millis1 = int(round(time.time() * 1000)) time.sleep(10) def onCon(self, client, userdata, flags, rc): print('Mqtt connected') client.subscribe(self.mosquittoCommand.sendTopic + '/status') client.publish(self.mosquittoCommand.sendTopic + '/server', 'cams') client.subscribe(self.mosquittoCommand.sendTopic + '/server') client.publish(self.mosquittoCommand.sendTopic + '/status', 'Connected') if not settings['UseTelemetry']: print('Using command telemetry') client.subscribe(self.mosquittoCommand.sendTopic + '/telemetry') def onTelemCon(self, client, userdata, flags, rc): print('Mqtt connected') client.publish(self.mosquittoTelemetry.sendTopic + '/telem/status', 'Connected') def settings_clicked(self): print('Settings clicked!') gui1 = Toplevel(self.gui) global setting_entry, settings gui1.title(language['titleSettingsWindow']) gui1.geometry("730x300") row = 0 setting_entry = [] with open('config.json', 'r+', encoding='utf-8') as f: settings = json.load(f) for name in setting_names: Label(gui1, text=language[name], font=('Arial', 8), width=40).grid(column=0, row=row) setting_entry.append(Entry(gui1, width=20)) setting_entry[row].grid(column=1, row=row) try: setting_entry[row].insert(0, settings[setting_names[row]]) except KeyError: settings[setting_names[row]] = None except TclError: pass row += 1 Button(gui1, text=language['SaveBtn'], command=self.saveBtn).grid(column=0, row=row) row = 0 Button(gui1, text=language['Bindkey'], command=self.bindBtn).grid(column=3, row=row) row += 1 Button(gui1, text=language['ClearBinds'], command=self.clearBind).grid(column=3, row=row) row += 1 Label(gui1, text=language['InputCommand'], font=('Arial', 8), width=20).grid(column=3, row=row) self.bindCommand = Entry(gui1, width=20) self.bindCommand.grid(column=4, row=row) row += 1 Checkbutton(gui1, text=language['UseTelemetryServer'], variable=self.useTelemetry).grid(column=3, row=row) gui1.grab_set() def bindBtn(self): key = keyboard.read_key() try: with open('keyboard.json', 'r+') as file: self.keyCommand = json.load(file) except (FileNotFoundError, json.decoder.JSONDecodeError): pass self.keyCommand[key] = self.bindCommand.get() with open('keyboard.json', 'w+') as file: file.write(json.dumps(self.keyCommand)) self.notification_manager.success( "Command {0} successfully bounded to key {1}".format( self.keyCommand[key], key)) def clearBind(self): self.keyCommand = """{}""" with open('keyboard.json', 'w+') as file: json.dump(self.keyCommand, file) def saveBtn(self): print("Save button clicked!") err = False global settings old = settings.copy() for i in range(len(setting_names)): data = setting_entry[i].get() if data == '': err = True else: settings[setting_names[i]] = data settings['UseTelemetry'] = self.useTelemetry.get() if self.fStart: try: self.initMQTT() self.fStart = False except TypeError: self.notification_manager.alert(language['incorrectData']) if self.useTelemetry.get(): if self.mosquittoTelemetry is None: print('Creating mt copy') self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon else: try: self.mosquittoTelemetry.reconnect( address=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) except AttributeError: self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon else: print('Subscribing') self.mosquittoCommand.subscribe(self.mosquittoCommand.sendTopic + '/telemetry') self.mosquittoCommand.publish( self.mosquittoCommand.sendTopic + '/telemetry', 'Saved') if not old['Robot name'] == settings['Robot name']: self.mosquittoCommand.updateTopic(topic=settings['Robot name'], old_topic=old['Robot name']) if old['Command server address'] is not settings['Command server address'] \ or old['Command server port'] is not settings['Command server port'] \ or old['Command server login'] is not settings['Command server login'] \ or old['Command server password'] is not settings['Command server password']: if not bool(match(DOMAINEXPRESSION, settings['Command server address'])) \ and not bool(match(IPEXPRESSIOM, settings['Command server address'])): err = True else: self.mosquittoCommand.reconnect( address=settings['Command server address'], login=settings['Command server login'], password=settings['Command server password'], port=int(settings['Command server port'])) if bool(match(MACEXPRESSION, settings['Bluetooth MAC-address'])): self.mosquittoCommand.publish( "{0}/{1}".format(settings['Robot name'], 'addMac'), settings['Bluetooth MAC-address']) else: self.notification_manager.warning( "Wrong MAC address format, file not saved") err = True if not err: print('Saved') with open('config.json', 'w+') as file: json.dump(settings, file) def keyRelease(self, event): global sendingKey try: command = self.keyCommand[event.char] if command in sendingKey: sendingKey.remove(command) self.mosquittoCommand.setKey(sendingKey) except KeyError: pass def keyPress(self, event): global sendingKey try: command = self.keyCommand[event.char] if not (command in sendingKey): sendingKey.append(command) self.mosquittoCommand.setKey(sendingKey) except KeyError: pass
if (secretcardkey == cardkey): verifyflag = True # Set Pass to indicate that they are matched. else: # not matched or secretcardkey is None or "" verifyflag = False # Set Pass to indicate that they are matched. else: sms_msg = "Error Invalid Mode" #unknown mode log('Invalid Mode') verifyflag = False # Show fail to indicate that there is a problem. # show the card ID sms_msg = sms_msg + ' (' + cardkey + '). ' #send the pass/fail flag to MCU, so the MCU can blink the green led or red led to indicate that the operation fails or pass respectively. if (verifyflag): sms_msg = sms_msg + " Pass!" MQTT.publish_event_to_client('esp32', 'V1') else: sms_msg = sms_msg + " Fail!" MQTT.publish_event_to_client('esp32', 'V0') # push (bool) to send this notification to push (iOS or Android) IONode.set_output('out1', { "message": sms_msg, "sms": False, "email": False, "push": True }) # For debug purpose log('mode =') log(verifyflag)
""" Sends a command to the device to set the x or y of the camera position. Command format is P{0}:{1} {0}: X or Y coordinate {1}: position value """ import MQTT if IONode.is_trigger('in2'): select = 0 #X position val = IONode.get_input('in2')['event_data']['value'] log('camera x position trigger') elif IONode.is_trigger('in3'): select = 1 #Y position val = IONode.get_input('in3')['event_data']['value'] log('camera y position trigger') MQTT.publish_event_to_client(IONode.get_input('in1')['event_data']['value'], 'P{}:{}'.format(select, str(val)))
''' This workflow will turn on or off the leds. Last Updated: June 19, 2018 Author: Medium One ''' import MQTT if IONode.is_trigger('in1'): redledlevel = IONode.get_input('in1')['event_data']['value'] if (redledlevel == "on"): MQTT.publish_event_to_client('esp32', 'G1:1') else: MQTT.publish_event_to_client('esp32', 'G1:0') log("red led level: " + str(redledlevel)) elif IONode.is_trigger('in2'): greenledlevel = IONode.get_input('in2')['event_data']['value'] if (greenledlevel == "on"): MQTT.publish_event_to_client('esp32', 'G2:1') else: MQTT.publish_event_to_client('esp32', 'G2:0') log("green led level: " + str(greenledlevel))
ads_ntc_reader.run() tank_level_sensor = UltraSonicSensor.HCSR04(13, 19) tank_level_sensor.run() def tank_level_func(): # return in cm with temperature compensation return 100. * tank_level_sensor.get_distance( ads_ntc_reader.get_channel_temperature(1)) ads.reset() # create publisher adapters for publishing tank_level = MQTT.PublisherAdapter("/sensors/tank_level", tank_level_func) temp_tank = MQTT.PublisherAdapter( "/sensors/temperature/tank", partial(ads_ntc_reader.get_channel_temperature, 0)) temp_ext = MQTT.PublisherAdapter( "/sensors/temperature/ext", partial(ads_ntc_reader.get_channel_temperature, 1)) dht11 = DHTSensors.DHT11(17) # dht11 on gpio 17 dht11.run() dht11_temperature = MQTT.PublisherAdapter("/sensors/dht11/01/temperature", dht11.get_temperature) dht11_humidity = MQTT.PublisherAdapter("/sensors/dht11/01/humidity", dht11.get_humidity) rpi_cpu_temp = RPiSensors.CPUTemperature("/sensors/temperature/cpu")
adduser = IONode.get_input('in1')['event_data']['value'] deluser = IONode.get_input('in2')['event_data']['value'] vfyuser = IONode.get_input('in3')['event_data']['value'] mode = Store.get("fingerprint_mode") # Get the stored fingerprint scan mode. if mode is None: Store.set_data("fingerprint_mode", "idle", -1) mode = "idle" if (mode == "idle"): if (adduser == 'on'): new_value = "add" msg = "Add mode: Please place your finger on reader." MQTT.publish_event_to_client('esp32', 'C1') elif (deluser == 'on'): new_value = "delete" msg = "Delete mode: Delete now." MQTT.publish_event_to_client('esp32', 'C2') elif (vfyuser == 'on'): new_value = "verify" msg = "Verify mode: Please place your finger on reader." MQTT.publish_event_to_client('esp32', 'C3') elif (mode == "add"): if (adduser == 'off'): new_value = "idle" msg = "Back to Idle Mode." elif (mode == "delete"): if (deluser == 'off'): new_value = "idle"
# This workflow publishes data requests to the RPi according to the custom scheduler. # It starts only after the 'Initialized':'True' message has been published by the client. import MQTT import Store in1_triggered = IONode.is_trigger('in1') # raw:Initialized tag published by client RPi if (in1_triggered): Store.set_global_data("initialized", "True") is_initialized = Store.get_global("initialized") is_initialized_string = is_initialized.encode("latin-1") if (is_initialized_string == "True"): MQTT.publish_event_to_client('Rasp_Pi', '{"Data Request":"True"}', encoding='utf-8')
def run(self): MQTT.mqtt_start(token=self.token)
import MQTT led_value = IONode.get_input('in1')['event_data']['value'] send_value = "0" if led_value == "on": send_value = "1" MQTT.publish_event_to_client('esp8266', send_value)
errorflag = True response_txt = "Problem. The external yellow l e d does not exist." log("Error: no external yellow led.") else: errorflag = True response_txt = "Problem. The external l e d does not exist." log("Error: Unknown led.") # # Turn on or off the LED # if request['intent'][ 'name'] == 'ledControlIntent' and errorflag == False: action = request['intent']['slots']['led_onoff']['value'] log(action) if action == 'on': MQTT.publish_event_to_client('s5d9', ledpin + ':0') elif action == 'off': MQTT.publish_event_to_client('s5d9', ledpin + ':1') else: errorflag = True response_txt = "Problem. The request action for l e d does not exist." log("Error: Unknown action.") if (errorflag == False): response_txt = "The external " + led + " l e d is turned " + action + "." # # Blink the LED for a number of times. # elif request['intent'][ 'name'] == 'ledBlinkIntent' and errorflag == False: blink_number = int( request['intent']['slots']['blink_num']['value'])
# Raspberry Pi Weather Station Data Request Scheduling # Created: June 28, 2017 # By: Dan Kane # This workflow publishes weather data requests (temperature, humidity, pressure) to the RPi according # to the custom scheduler. It starts only after the 'Initialized':'True' message has been published # by the client. import MQTT import Store in1_triggered = IONode.is_trigger( 'in1') # raw:Initialized tag published by client RPi if (in1_triggered): Store.set_global_data("initialized", "True") is_initialized = Store.get_global("initialized") is_initialized_string = is_initialized.encode("latin-1") if (is_initialized_string == "True"): MQTT.publish_event_to_client('Rasp_Pi', '{"Temp_Request":"True"}', encoding='utf-8') MQTT.publish_event_to_client('Rasp_Pi', '{"Pressure_Request":"True"}', encoding='utf-8') MQTT.publish_event_to_client('Rasp_Pi', '{"Humidity_Request":"True"}', encoding='utf-8')
"MESSAGE_FROM_BASE_STATION": "database/message", "MEASUREMENT_FROM_BASE_STATION": "database/measurement", "NURSE_CONFIRMED_MESSAGE": "watch/confirm", "MESSAGE_FOR_WATCH": "watch/message", "NEW_WATCH_CONNECTED": "watch/connected", } ALARM_BOUNDARIES = { "SYSTOLIC_UPPER": 145, "SYSTOLIC_LOWER": 90, "HEARTRATE_LOWER": 50, "HEARTRATE_UPPER": 110, "OXYGEN_LOWER": 80 } mqtt = MQTT(ip="51.83.42.157", port=1883, qos=2, mode=Message_mode.BLOCKING) DB = DbConnector() def database_message_callback(message): patient_info = DB.getPatientInfo(message.patient_id) if patient_info is None: print("Couldn't find patient with id " + message.patient_id) patient_name = "unknown" else: patient_name = patient_info[0] print("Received message on topic message with id %d" % message.id) print("For patient with id %d and name %s" %
class SSN_Server_UI(): def __init__(self, window_theme="aquativo", window_title="Hello World!", window_geometry="400x400+100+100"): self.root_window = ThemedTk() self.root_window.set_theme(theme_name=window_theme) self.root_window.title(window_title) self.root_window.geometry(window_geometry) self.window_width = self.root_window.winfo_screenwidth() self.window_height = self.root_window.winfo_screenheight() # essential communicators self.udp_comm = None self.mqtt_comm = None self.serial_comm = None self.use_udp = False self.use_mqtt = False self.csv_data_recording = None ############# if we have more than one node self.NodeCountInGUI = 0 self.message_type_text = list() self.node_select_radio_button = SSN_Radio_Button_Common_Option_Widget( self.root_window) self.nodeid_text = list() self.temperature_text = list() self.humidity_text = list() self.nodeuptime_text = list() self.abnormalactivity_text = list() ######## Machine Incoming data to be displayed self.machine_loadcurrents, self.machine_percentageloads, self.machine_status = [ [] for _ in range(4) ], [[] for _ in range(4)], [[] for _ in range(4)] self.machine_timeinstate, self.machine_sincewheninstate = [ [] for _ in range(4) ], [[] for _ in range(4)] self.no_connection = 0 pass def start(self): self.root_window.mainloop() # threading.Thread.__init__(self) # self.start() def setup_input_interface(self, current_sensor_ratings, mac_addresses_filename, default_configs): # enter the SSN new MAC full_mac_list = get_MAC_addresses_from_file(mac_addresses_filename) self.ssn_mac_dropdown = SSN_DropDown_Widget( window=self.root_window, label_text="SSN MAC", label_pos=(0, vertical_spacing * 0 + 2), dropdown_list=full_mac_list, dropdown_pos=(horizontal_spacing - 10, vertical_spacing * 0 + 2), dropdown_block_width=17) ######## Machine Config Inputs self.machine_ratings, self.machine_maxloads, self.machine_thresholds = list( ), list(), list() for i in range(4): # generate machine label rating_label_text = "M{} Sensor Rating (A)".format(i + 1) maxload_label_text = "M{} Max Load (A)".format(i + 1) thres_label_text = "M{} Threshold (A)".format(i + 1) # enter machine sensor rating rating_dropdown = SSN_DropDown_Widget( window=self.root_window, label_text=rating_label_text, label_pos=(horizontal_spacing * 2 * i, vertical_spacing * 1 + 5), dropdown_list=current_sensor_ratings, dropdown_pos=(horizontal_spacing * (2 * i + 1), vertical_spacing * 1 + 5), dropdown_block_width=12, default_selected_item=default_configs[0 + 3 * i]) # enter machine max load maxload_text_entry = SSN_Text_Entry_Widget( window=self.root_window, label_text=maxload_label_text, label_pos=(horizontal_spacing * 2 * i, vertical_spacing * 2 + 5), text_entry_width=15, text_pos=(horizontal_spacing * (2 * i + 1), vertical_spacing * 2 + 5), default_value=default_configs[1 + 3 * i]) # enter machine threshold current thresh_text_entry = SSN_Text_Entry_Widget( window=self.root_window, label_text=thres_label_text, label_pos=(horizontal_spacing * 2 * i, vertical_spacing * 3 + 5), text_entry_width=15, text_pos=(horizontal_spacing * (2 * i + 1), vertical_spacing * 3 + 5), default_value=default_configs[2 + 3 * i]) self.machine_ratings.append(rating_dropdown) self.machine_maxloads.append(maxload_text_entry) self.machine_thresholds.append(thresh_text_entry) pass # reporting interval text input self.reportinterval_text_entry = SSN_Text_Entry_Widget( window=self.root_window, label_text="Report Interval (sec)", label_pos=(horizontal_spacing * 2, vertical_spacing * 4 + 5), text_entry_width=15, text_pos=(horizontal_spacing * (2 + 1), vertical_spacing * 4 + 5), default_value=default_configs[12]) pass def clear_status_panel(self): # clear node status for this_node in range(self.NodeCountInGUI): self.message_type_text[this_node].clear() self.nodeid_text[this_node].clear() # clear existing texts for node specific information self.temperature_text[this_node].clear() self.humidity_text[this_node].clear() self.nodeuptime_text[this_node].clear() self.abnormalactivity_text[this_node].clear() # clear existing texts for machine specific information for i in range(4): self.machine_loadcurrents[this_node][i].clear() self.machine_percentageloads[this_node][i].clear() self.machine_status[this_node][i].clear() self.machine_timeinstate[this_node][i].clear() self.machine_sincewheninstate[this_node][i].clear() pass pass pass def send_mac_btn_clicked(self): # clear node status panel self.clear_status_panel() if self.use_udp: # construct and send set_mac message try: self.udp_comm.send_set_mac_message( node_index=self.node_select_radio_button.getSelectedNode() - 1, mac_address=self.ssn_mac_dropdown.get()) print('\033[34m' + "Sent MAC to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except IndexError: print( '\033[31m' + "SSN Network Node Count: {}. Can't Send to SSN Indexed: {}" .format( self.udp_comm.getNodeCountinNetwork(), self.node_select_radio_button.getSelectedNode() - 1)) pass elif self.use_mqtt: # construct and send set_mac message try: self.mqtt_comm.send_set_mac_message( mac_address=self.ssn_mac_dropdown.get()) print('\033[34m' + "Sent MAC to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except error: print('\033[31m' + f"{error}") pass pass pass def send_config_btn_clicked(self): # clear node status panel self.clear_status_panel() # get the configs from the GUI self.configs = list() for i in range(4): this_sensor_rating = self.machine_ratings[i].get() this_sensor_rating = int( this_sensor_rating) if this_sensor_rating != 'NONE' else 0 self.configs.append(this_sensor_rating) self.configs.append( int(10 * float(self.machine_thresholds[i].get()))) self.configs.append(int(self.machine_maxloads[i].get())) pass self.configs.append(int(self.reportinterval_text_entry.get())) if self.use_udp: try: self.udp_comm.send_set_config_message( node_index=self.node_select_radio_button.getSelectedNode() - 1, config=self.configs) print('\033[34m' + "Sent CONFIG to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except IndexError: print( '\033[31m' + "SSN Network Node Count: {}. Can't Send to SSN Indexed: {}" .format( self.udp_comm.getNodeCountinNetwork(), self.node_select_radio_button.getSelectedNode() - 1)) # change button color # self.config_button.config(bg='white') elif self.use_mqtt: # construct and send set_mac message try: self.mqtt_comm.send_set_config_message(config=self.configs) print('\033[34m' + "Sent CONFIG to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except error: print('\033[31m' + f"{error}") pass pass pass def send_timeofday_btn_clicked(self): if self.use_udp: try: # self.udp_comm.send_set_timeofday_message(node_index=self.node_select_radio_button.getSelectedNode() - 1, current_time=self.server_time_now) self.udp_comm.send_set_timeofday_Tick_message( node_index=self.node_select_radio_button.getSelectedNode() - 1, current_tick=utils.get_bytes_from_int( self.servertimeofday_Tick)) print('\033[34m' + "Sent Time of Day to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except IndexError: print( '\033[31m' + "SSN Network Node Count: {}. Can't Send to SSN Indexed: {}" .format( self.udp_comm.getNodeCountinNetwork(), self.node_select_radio_button.getSelectedNode() - 1)) elif self.use_mqtt: # construct and send set_mac message try: self.mqtt_comm.send_set_timeofday_Tick_message( current_tick=utils.get_bytes_from_int( self.servertimeofday_Tick)) print('\033[34m' + "Sent Time of Day to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except error: print('\033[31m' + f"{error}") pass pass pass def debug_reset_eeprom_btn_clicked(self): # clear node status panel self.clear_status_panel() if self.use_udp: # send message and clear the status texts try: self.udp_comm.send_debug_reset_eeprom_message( node_index=self.node_select_radio_button.getSelectedNode() - 1) print('\033[34m' + "Sent CLEAR EEPROM to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except IndexError: print( '\033[31m' + "SSN Network Node Count: {}. Can't Send to SSN Indexed: {}" .format( self.udp_comm.getNodeCountinNetwork(), self.node_select_radio_button.getSelectedNode() - 1)) elif self.use_mqtt: # construct and send set_mac message try: self.mqtt_comm.send_debug_reset_eeprom_message() print('\033[34m' + "Sent CLEAR EEPROM to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except error: print('\033[31m' + f"{error}") pass pass pass def debug_reset_ssn_btn_clicked(self): # clear node status panel self.clear_status_panel() if self.use_udp: # send message and clear statuss try: self.udp_comm.send_debug_reset_ssn_message( node_index=self.node_select_radio_button.getSelectedNode() - 1) print('\033[34m' + "Sent RESET to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except IndexError: print( '\033[31m' + "SSN Network Node Count: {}. Can't Send to SSN Indexed: {}" .format( self.udp_comm.getNodeCountinNetwork(), self.node_select_radio_button.getSelectedNode() - 1)) elif self.use_mqtt: # construct and send set_mac message try: self.mqtt_comm.send_debug_reset_ssn_message() print('\033[34m' + "Sent RESET to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) except error: print('\033[31m' + f"{error}") pass pass pass def setup_buttons(self): # update mac button self.mac_button = SSN_Button_Widget( window=self.root_window, button_text="Send MAC Address", button_command=self.send_mac_btn_clicked, button_pos=(2 * horizontal_spacing, vertical_spacing * 0 + 0)) # send sensor configuration button self.config_button = SSN_Button_Widget( window=self.root_window, button_text="Send Configuration", button_command=self.send_config_btn_clicked, button_pos=(horizontal_spacing * 4, vertical_spacing * 4 + 5)) # send time of day button; we will also give a display of current time of day with this self.servertimeofday_text = SSN_Text_Display_Widget( window=self.root_window, label_text="Server Time of Day", label_pos=(3 * horizontal_spacing + 52, vertical_spacing * 7), text_size=(150, vertical_spacing), text_pos=(3 * horizontal_spacing + 30, vertical_spacing * 8)) self.servertimeofday_button = SSN_Button_Widget( window=self.root_window, button_text="Send Time of Day", button_command=self.send_timeofday_btn_clicked, button_pos=(3 * horizontal_spacing + 54, vertical_spacing * 9 + 5)) self.debug_reset_eeprom_button = SSN_Button_Widget( window=self.root_window, button_text="(DEBUG) CLEAR EEPROM", button_command=self.debug_reset_eeprom_btn_clicked, button_pos=(5 * horizontal_spacing + 50, vertical_spacing * 8 - 10)) self.debug_reset_ssn_button = SSN_Button_Widget( window=self.root_window, button_text="(DEBUG) RESET SSN", button_command=self.debug_reset_ssn_btn_clicked, button_pos=(5 * horizontal_spacing + 64, vertical_spacing * 9 + 5)) self.clear_status_panel_button = SSN_Button_Widget( window=self.root_window, button_text="Clear Status Panel", button_command=self.clear_status_panel, button_pos=(5 * horizontal_spacing + 69, vertical_spacing * 10 + 22)) pass def GUI_Block(self): return (self.NodeCountInGUI - 1) * vertical_spacing * 14 + 40 def setup_incoming_data_interface(self, NumOfNodes): for k in range(NumOfNodes): self.NodeCountInGUI += 1 # received message/status to be displayed self.message_type_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Incoming Message Type", label_pos=(0, self.GUI_Block() + vertical_spacing * 6), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 6))) # add a radio-button to chose this one when we have to send the message self.node_select_radio_button.add_radio( radio_text="SSN-{}".format(self.NodeCountInGUI), radio_value=self.NodeCountInGUI, radio_pos=(2 * horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 6)) # SSN Node ID to be displayed self.nodeid_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Node ID", label_pos=(0, self.GUI_Block() + vertical_spacing * 7), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 7))) # temperature to be displayed self.temperature_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Temperature ({}C)".format(chr(176)), label_pos=(0, self.GUI_Block() + vertical_spacing * 8), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 8))) # humidity to be displayed self.humidity_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Relative Humidity (%)", label_pos=(0, self.GUI_Block() + vertical_spacing * 9), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 9))) # node uptime to be displayed self.nodeuptime_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Node Up Time in (sec)", label_pos=(0, self.GUI_Block() + vertical_spacing * 10), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 10))) # abnormal activity to be displayed self.abnormalactivity_text.append( SSN_Text_Display_Widget( window=self.root_window, label_text="Abnormal Activity", label_pos=(0, self.GUI_Block() + vertical_spacing * 11), text_size=(110, vertical_spacing), text_pos=(horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 11), color='green')) for i in range(4): # generate machine labels loadcurrent_label_text = "M{} Load Current (A)".format(i + 1) percentload_label_text = "M{} Percentage Load (%)".format(i + 1) state_label_text = "M{} State (OFF/IDLE/ON)".format(i + 1) duration_label_text = "M{} Time In State (sec)".format(i + 1) timestamp_label_text = "M{} State Time Stamp".format(i + 1) # machine load current loadcurrent_text = SSN_Text_Display_Widget( window=self.root_window, label_text=loadcurrent_label_text, label_pos=(horizontal_spacing * 2 * i, self.GUI_Block() + vertical_spacing * 12 + 20), text_size=(80, vertical_spacing), text_pos=((2 * i + 1) * horizontal_spacing + 20, self.GUI_Block() + vertical_spacing * 12 + 20)) percentload_text_entry = SSN_Text_Display_Widget( window=self.root_window, label_text=percentload_label_text, label_pos=(horizontal_spacing * 2 * i, self.GUI_Block() + vertical_spacing * 13 + 20), text_size=(80, vertical_spacing), text_pos=(horizontal_spacing * (2 * i + 1) + 20, self.GUI_Block() + vertical_spacing * 13 + 20)) # machine state state_text_entry = SSN_Text_Display_Widget( window=self.root_window, label_text=state_label_text, label_pos=(horizontal_spacing * 2 * i, self.GUI_Block() + vertical_spacing * 14 + 20), text_size=(80, vertical_spacing), text_pos=(horizontal_spacing * (2 * i + 1) + 20, self.GUI_Block() + vertical_spacing * 14 + 20)) # machine state duration duration_text_entry = SSN_Text_Display_Widget( window=self.root_window, label_text=duration_label_text, label_pos=(horizontal_spacing * 2 * i, self.GUI_Block() + vertical_spacing * 15 + 20), text_size=(80, vertical_spacing), text_pos=(horizontal_spacing * (2 * i + 1) + 20, self.GUI_Block() + vertical_spacing * 15 + 20)) # machine state timestamp timestamp_dual_text_entry = SSN_Dual_Text_Display_Widget( window=self.root_window, label_text=timestamp_label_text, label_pos=(horizontal_spacing * 2 * i, self.GUI_Block() + vertical_spacing * 16 + 20), text_size=(80, vertical_spacing), text_pos1=(horizontal_spacing * (2 * i + 1) + 20, self.GUI_Block() + vertical_spacing * 16 + 20), text_pos2=(horizontal_spacing * (2 * i + 1) + 20, self.GUI_Block() + vertical_spacing * 17 + 20)) self.machine_loadcurrents[self.NodeCountInGUI - 1].append(loadcurrent_text) self.machine_percentageloads[self.NodeCountInGUI - 1].append(percentload_text_entry) self.machine_status[self.NodeCountInGUI - 1].append(state_text_entry) self.machine_timeinstate[self.NodeCountInGUI - 1].append(duration_text_entry) self.machine_sincewheninstate[self.NodeCountInGUI - 1].append( timestamp_dual_text_entry) pass pass # set default node for sending messages self.node_select_radio_button.radio_buttons[0].invoke() pass def setup_serial_communication(self, serial_port='COM5', baudrate=19200, log_file='../serial_log-110920-130920.txt'): self.serial_comm = SERIAL_COMM(serial_port, baudrate, log_file) pass def setup_udp_communication(self, server_end): # essential UDP communicator self.udp_comm = UDP_COMM() connection_status = self.udp_comm.udp_setup_connection( server_address=server_end[0], server_port=server_end[1]) if connection_status is None: print("Cannot Connect to Network!!!") return self.use_udp = True # invoke it just once self.read_messages_and_update_UI() pass def setup_mqtt_communication(self, client_id, host="192.168.0.120"): self.mqtt_comm = MQTT(client_id=client_id, host=host) self.mqtt_comm.client.loop_start() self.use_mqtt = True # invoke it just once self.read_messages_and_update_UI() pass def setup_csv_data_recording(self, csv_file): this_date = datetime.datetime.fromtimestamp(int(round(time.time()))) file_name, extension = os.path.splitext(csv_file) self.csv_data_file = file_name self.csv_data_recording = True pass def read_messages_and_update_UI(self): # check serial comm for messages if self.serial_comm: self.serial_comm.log() self.servertimeofday_Tick = int(round(time.time())) self.servertimeofday_text.update( new_text_string=self.servertimeofday_Tick) # receive the incoming message if self.use_udp: node_index, message_id, params = self.udp_comm.read_udp_message() # check if a valid message was received or not if node_index == -1 and message_id == -1: self.no_connection += 1 if self.no_connection > 10: self.no_connection = 0 print('\033[30m' + "XXX Nothing Received XXX") # recall this method after another second self.root_window.after(200, self.read_messages_and_update_UI) return elif self.use_mqtt: if not self.mqtt_comm.message_queue.qsize(): self.no_connection += 1 if self.no_connection > 10: self.no_connection = 0 print('\033[30m' + "XXX Nothing Received XXX") # recall this method after another second self.root_window.after(200, self.read_messages_and_update_UI) return node_index, message_id, params = self.mqtt_comm.message_queue.get() # proceed only if a genuine message is found self.no_connection = 0 # message type and node id will always be displayed self.message_type_text[node_index].update( new_text_string=SSN_MessageID_to_Type[message_id], justification='left') self.nodeid_text[node_index].update(new_text_string=params[0]) # basic get messages received? if message_id == SSN_MessageType_to_ID['GET_MAC']: print('\033[34m' + "Received GET_MAC from SSN-{}".format(node_index + 1)) elif message_id == SSN_MessageType_to_ID['GET_TIMEOFDAY']: print('\033[34m' + "Received GET_TIMEOFDAY from SSN-{}".format(node_index + 1)) # automate set time of day print('\033[34m' + "Sending SET_TIMEOFDAY to SSN-{}".format(node_index + 1)) if self.use_udp: self.udp_comm.send_set_timeofday_Tick_message( node_index=self.node_select_radio_button.getSelectedNode() - 1, current_tick=utils.get_bytes_from_int( self.servertimeofday_Tick)) print('\033[34m' + "Sent Time of Day to SSN-{}".format( self.node_select_radio_button.getSelectedNode())) elif self.use_mqtt: self.mqtt_comm.send_set_timeofday_Tick_message( current_tick=utils.get_bytes_from_int( self.servertimeofday_Tick)) elif message_id == SSN_MessageType_to_ID['GET_CONFIG']: print('\033[34m' + "Received GET_CONFIG from SSN-{}".format(node_index + 1)) # configs have been acknowledged? elif message_id == SSN_MessageType_to_ID['ACK_CONFIG']: configs_acknowledged = params[1] # it is a list if configs_acknowledged == self.configs: print('\033[34m' + "Received CONFIG ACK from SSN-{}".format(node_index + 1)) # self.config_button.config(bg='light green') pass pass # status update message brings the ssn heartbeat status elif message_id == SSN_MessageType_to_ID['STATUS_UPDATE']: print('\033[34m' + "Received Status Update from SSN-{}".format(node_index + 1)) self.temperature_text[node_index].update(new_text_string=params[1]) self.humidity_text[node_index].update(new_text_string=params[2]) self.nodeuptime_text[node_index].update( new_text_string=self.servertimeofday_Tick - params[3] ) # get the difference of static tick and current tick activity_level = SSN_ActivityLevelID_to_Type[params[4]] # get activity level of the SSN and display properly self.abnormalactivity_text[node_index].update( new_text_string=activity_level) if activity_level == 'NORMAL': self.abnormalactivity_text[node_index].change_text_color( new_color='green') else: self.abnormalactivity_text[node_index].change_text_color( new_color='red') fault_count = params[-1] if fault_count is not None: print('\033[34m' + "Fault Count from SSN-{}: {}".format( node_index + 1, fault_count)) machine_state_timestamps = [] for i in range(4): self.machine_loadcurrents[node_index][i].update( new_text_string=params[5 + i]) self.machine_percentageloads[node_index][i].update( new_text_string=params[9 + i]) self.machine_status[node_index][i].update( new_text_string=Machine_State_ID_to_State[params[13 + i]]) state_timestamp_tick = params[17 + i] if state_timestamp_tick != 0: # elapsed_time_in_state = self.servertimeofday_Tick - state_timestamp_tick good_time = datetime.datetime.fromtimestamp( state_timestamp_tick) exact_time_strings = [ "{}:{}:{}".format(good_time.hour, good_time.minute, good_time.second), "{}/{}/{}".format(good_time.day, good_time.month, good_time.year) ] else: # elapsed_time_in_state = state_timestamp_tick exact_time_strings = ["0:0:0", "0/0/0"] machine_state_timestamps.append(exact_time_strings) self.machine_timeinstate[node_index][i].update( new_text_string=params[21 + i]) self.machine_sincewheninstate[node_index][i].update( new_text_strings=machine_state_timestamps[i]) pass # append this data to our CSV file if self.csv_data_recording: # insertiontimestamp, node_id, node_uptime, activitylevel, # temperature, humidity, # M1_load, M1_load%, M1_state, M1_statetimestamp, M1_stateduration, # M2_*... server_time_of_the_day = datetime.datetime.fromtimestamp( self.servertimeofday_Tick) data_packet = [ server_time_of_the_day, params[0], datetime.datetime.fromtimestamp(params[3]), activity_level, params[1], params[2], params[5], params[9], params[13], datetime.datetime.fromtimestamp(params[17]), params[21], params[6], params[10], params[14], datetime.datetime.fromtimestamp(params[18]), params[22], fault_count ] with open(self.csv_data_file + "-{}-{}-{}".format(server_time_of_the_day.day, server_time_of_the_day.month, server_time_of_the_day.year) + ".csv", 'a', newline="") as f: writer = csv.writer(f) writer.writerow(data_packet) pass pass pass # recall this method after another second self.root_window.after(200, self.read_messages_and_update_UI) pass pass
if (secretcardkey == cardkey): verifyflag = True # Set Pass to indicate that they are matched. else: # not matched or secretcardkey is None or "" verifyflag = False # Set Pass to indicate that they are matched. else: sms_msg = "Error Invalid Mode" #unknown mode log('Invalid Mode') verifyflag = False # Show fail to indicate that there is a problem. # show the card ID sms_msg = sms_msg + ' (' + cardkey + '). ' #send the pass/fail flag to MCU, so the MCU can blink the green led or red led to indicate that the operation fails or pass respectively. if (verifyflag): sms_msg = sms_msg + " Pass!" MQTT.publish_event_to_client('s5d9', 'V1') else: sms_msg = sms_msg + " Fail!" MQTT.publish_event_to_client('s5d9', 'V0') # push (bool) to send this notification to push (iOS or Android) IONode.set_output('out1', { "message": sms_msg, "sms": False, "email": False, "push": True }) # For debug purpose log('mode =') log(verifyflag)
import MQTT # Send a command to the device to take a picture. Expect to recieve a base64 format string back from the device. if (IONode.get_input('in2')['event_data']['value']): MQTT.publish_event_to_client(IONode.get_input('in1')['event_data']['value'], 'C') log ('Sent the command.')
def connect(self): self.c = MQTT.MQTTClient(self.client, self.server) self.c.connect()
def main(): client = MQTT.MQTT(host, port).connect() data_dth22(client, "city/street", 1) google_mini(client, "city/street", 1)
# Public packages import sys import yaml import os # Personal packages import P1 import MQTT # Load configuration YAML path = os.path.dirname(os.path.realpath(__file__)) fp = open(path + '/config.yaml', 'r') cfg = yaml.safe_load(fp) # Set up MQTT client mqtt_client = MQTT.Client(**cfg['mqtt']) mqtt_client.subscribe(cfg['mqtt']['topic']) # Set up P1 client p1_client = P1.Client(cfg['P1']['port']) def main(): # Get P1 data if not p1_client.read_telegram(): sys.exit() mqtt_client.publish('B827EBF288F8', 22, p1_client.energy) mqtt_client.publish('B827EBF288F8', 94, p1_client.power)
def receiveData(): global R0, robotCode, data1, data2, data3, data4, data5 global thread_die global encoX, encoY, angleZ, ball global cond, distB, degB, KrdX, KrdY global count, b_1, b_2, b_3, b_4,b_5 FPrint1=0 FPrint2=0 while True: # print("ditrima") if not queue.empty(): packet = queue.get() # time.sleep(0.01) # print(packet) if packet[0] == 'A': # terima data dari Arduino encoX = round(int(packet[1])/10) encoY = round(int(packet[2])/10) angleZ = int(packet[3]) c_ball = int(packet[4]) if count > 5: count = 1 else: count += 1 if count == 1: b_1 = c_ball elif count == 2: b_2 = c_ball elif count == 3: b_3 = c_ball elif count == 4: b_4 = c_ball elif count == 5: b_5 = c_ball ball_filter = ((b_1 + b_2 + b_3 + b_4 + b_5)/5) # print(ball_filter) if ball_filter >0: ball = 1 else: ball = 0 # print('packet = ',packet) # mqtt.send(0,encoX, encoY, angleZ, ball) elif packet[0] == 'O': # terima data dari Odroid cond = int(packet[1]) distB= int(packet[2]) degB= int(packet[3]) c_KrdX= int(packet[4]) KrdY= int(packet[5]) KrdX = (c_KrdX-160) # print(degB) # if KrdX == -160: # KrdX = 0 # print(KrdX) # mqtt.send(1,distB, degB, enemyDistance, enemyDegree) R0 = mqtt.read("Base") # terima data dari Base Station if R0: # print(R0) robotCode = R0[0] data1 = (R0[1]) data2 = (R0[2]) data3 = (R0[3]) data4 = (R0[4]) data5 = (R0[5]) # print(robotCode,'\t', xRobot,'\t', yRobot,'\t', zRobot,'\t', speed) if thread_die is True: print('thread diee..') break # Jrk = (encoX,encoY) if FPrint1!=encoX and FPrint2!=encoY: # print(robotCode,' ', data1, ' ', data2,' ', data3,' ', data4) print(encoX, ' ', encoY,' ', angleZ,' ', ball) (FPrint1,FPrint2)=(encoX,encoY)
def saveBtn(self): print("Save button clicked!") err = False global settings old = settings.copy() for i in range(len(setting_names)): data = setting_entry[i].get() if data == '': err = True else: settings[setting_names[i]] = data settings['UseTelemetry'] = self.useTelemetry.get() if self.fStart: try: self.initMQTT() self.fStart = False except TypeError: self.notification_manager.alert(language['incorrectData']) if self.useTelemetry.get(): if self.mosquittoTelemetry is None: print('Creating mt copy') self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon else: try: self.mosquittoTelemetry.reconnect( address=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) except AttributeError: self.mosquittoTelemetry = MQTT( server=settings['Telemetry server address'], login=settings['Telemetry server login'], password=settings['Telemetry server password'], port=int(settings['Telemetry server port'])) self.mosquittoTelemetry.sendTopic = settings['Robot name'] self.mosquittoTelemetry.on_connect = self.onTelemCon else: print('Subscribing') self.mosquittoCommand.subscribe(self.mosquittoCommand.sendTopic + '/telemetry') self.mosquittoCommand.publish( self.mosquittoCommand.sendTopic + '/telemetry', 'Saved') if not old['Robot name'] == settings['Robot name']: self.mosquittoCommand.updateTopic(topic=settings['Robot name'], old_topic=old['Robot name']) if old['Command server address'] is not settings['Command server address'] \ or old['Command server port'] is not settings['Command server port'] \ or old['Command server login'] is not settings['Command server login'] \ or old['Command server password'] is not settings['Command server password']: if not bool(match(DOMAINEXPRESSION, settings['Command server address'])) \ and not bool(match(IPEXPRESSIOM, settings['Command server address'])): err = True else: self.mosquittoCommand.reconnect( address=settings['Command server address'], login=settings['Command server login'], password=settings['Command server password'], port=int(settings['Command server port'])) if bool(match(MACEXPRESSION, settings['Bluetooth MAC-address'])): self.mosquittoCommand.publish( "{0}/{1}".format(settings['Robot name'], 'addMac'), settings['Bluetooth MAC-address']) else: self.notification_manager.warning( "Wrong MAC address format, file not saved") err = True if not err: print('Saved') with open('config.json', 'w+') as file: json.dump(settings, file)
def main(): global robotCode, data1, data2, data3, data4, data5 global thread_die, stepP global find1, find2, point1, point2, point3 global encoX, encoY, angleZ, ball global cond, distB, degB, KrdX, KrdY robotCode = 'A' if degB == 0: degB = -36 fprint=0 while True: try: # if robotCode == 'A': # # print(encoX, ' ', encoY) # if point1 != 'done': # point1 = pointToPoint(520, 50) # if point1 == 'done' and find1 != 'done': # # print('sipp sipp sipp') # find1 = findingObject('friend', 300, 20) # time.sleep(0.05) # robot.chargeKicker() # if find1 == 'done' and point2 != 'done' and ball == 1: # # print('hehe') # point2 = pointToPoint(520, 370) # if point2 == 'done' and point3 != 'done': # point3 = pointToPoint(365, 350) # if point3 == 'done' and ball == 1: # find2 = findingObject('friend', 220, 350) # print('nyari temen') # if find2 == 'done' and ball == 1: # robot.tendang() while True: try: if robotCode == '3': if data1 == 'step': if data2 == '1': if point1 != 'done': point1 = pointToPoint(520, 50) if point1 == 'done': mqtt.send('recvPos', 1) elif data2 == '2': if find1 != 'done': find1 = findingObject('friend', data3, data4) elif find1 == 'done': mqtt.send('friend', 1) elif data2 == '3': ball_follow() if ball == 1: mqtt.send('recvBall', 1) elif data2 == '4': if point2 != 'done': point2 = pointToPoint(520, 370) elif point2 == 'done' and point3 != 'done': point3 = pointToPoint(365, 370) if point3 == 'done': mqtt.send('passPos', 1) elif data2 == '5': find2 = findObject('friend', data2, data3) if find2 == 'done': mqtt.send('friend', 1) elif data2 == '6': robot.tendang() mqtt.send('passBall', 1) elif data2 == '7': robot.berhenti() if robotCode == '3M': # (0, xSpeed, ySpeed, zSpeed, dribble, kick) dribble = 0 if data1 > 0 and data2==0 : dribble = 1 elif data1 < 0 and data2==0: dribble = 2 elif data2 > 0 and data1==0: dribble = 3 elif data2 < 0 and data1==0: dribble = 4 else: dribble = 0 serArduino.write(0, data1, data2, data3, dribble, data4) except KeyboardInterrupt: time.sleep(1) mqtt.send(2, 0) thread_die = True p1.join() # p2.setDaemon(True) print("Exit nih gua") p2.terminate() p3.terminate() # p2.terminate() sys.exit(0)
import math import re # astar = A_Star.AStar(500) # start = (0, 0) # end = (2, 3) # path = astar.solve(start, end) n = dirX = dirY = 0 grid = 500 trig = 0 serArduino = Arduino.Serial('raspi', 'usb') serOdroid = Arduino.Serial('raspi', 'gpio') robot = move() mqtt.set("192.168.0.112", "Jasmine") queue = Queue() # Receive Data from Base Station R0 = robotCode = 0 data1 = data2 = data3 = data4 = data5 = 0 # Variable Process find1=find2=point1=point2=point3=0 # Receive Data from Arduino encoX = encoY = angleZ = ball = 0 # Receive Data from Odroid cond = distB = degB = KrdX = KrdY = 0
from random import shuffle import pygame import sys import MQTT import datetime, json from Cell import Cell width = 50 height = 50 cell_width = 10 mqttclient = MQTT.mqtt() grid = [[Cell() for j in range(height)] for i in range(width)] # starts mqtt listener def start_mqtt_listener(): mqttclient.connect() mqttclient.add_listener_func(message_callback) # gets called when a mqtt message arrives def message_callback(msg): #strip the b'' msg = msg[2:-1] for row in grid: for cell in row: res = { "timestamp": datetime.datetime.now().isoformat(), "value": -1, "username": "******" }