def activateModal(self, title, message, modalType, resume="false", progress="false"): ''' Sends socket message to UI client to activate a modal :param title: Title to be used for the modal :param message: The message that should appear in the modal body :param modalType: The type of modal (content, notification, alarm).. I don't think content modals come via this fucntion because modalSize is hardcoded to small. :param resume: Whether to have a resume button on the modal.. used while gcode is running :param progress: Whether to show the progress bar/spinner :return: ''' data = json.dumps({ "title": title, "message": message, "resume": resume, "progress": progress, "modalSize": "small", "modalType": modalType }) socketio.emit( "message", { "command": "activateModal", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC", )
def performHealthCheck(self): ''' This function sends a message to the UI clients every 5 seconds. It contains cpuUsage, current bufferSize as reported by the controller, and indication if the uploadFlag is enabled or disabled. The client prevents the user from performing certain functions when the gcode is being sent (i.e., uploadFlag enabled). :return: ''' currentTime = time.time() if currentTime - self.lastHealthCheck > 5: self.lastHealthCheck = currentTime load = max(psutil.cpu_percent(interval=None, percpu=True)) weAreBufferingLines = bool( int( self.app.data.config.getValue("Maslow Settings", "bufferOn"))) if weAreBufferingLines: bufferSize = self.app.data.bufferSize else: bufferSize = -1 healthData = { "cpuUsage": load, "bufferSize": bufferSize, } socketio.emit("message", { "command": "healthMessage", "data": json.dumps(healthData), "dataFormat": "json" }, namespace="/MaslowCNC") self.performStatusCheck(True)
def off_led(): global motor_status global pin_num global pin_mode # 判斷伺服馬達是否已經打開 if motor_status: # TODO: 檢查元件已經正確被關閉 motor_status = False data = { 'pin': pin_num, 'mode': pin_mode, 'code': 200, 'accessory': 'motor', 'status': motor_status, 'type': 'MotorCloseSuccess', 'msg': '伺服馬達已經關閉!' } socketio.emit('motor_off_publish_server', data, json=True, namespace='/pi', broadcast=True) return jsonify(data), 200 else: return jsonify({ 'pin': pin_num, 'mode': pin_mode, 'accessory': 'motor', 'status': motor_status, 'error_code': 400, 'error_type': 'MotorUnopen', 'error_msg': '請勿在未開啟狀態關閉伺服馬達!!' }), 400 return jsonify(data), 400
def performStatusCheck(self, healthCheckCalled=False): ''' This function sends a message to the client if it detects a change in the following parameters: uploadFlag, positioningMode, currentTool Also sends on every health check to get new connected clients in sync. :return: ''' update = healthCheckCalled if self.previousUploadFlag != self.app.data.uploadFlag: update = True self.previousUploadFlag = self.app.data.uploadFlag if self.previousPositioningMode != self.app.data.positioningMode: update = True self.previousPositioningMode = self.app.data.positioningMode if self.previousCurrentTool != self.app.data.currentTool: update = True self.previousCurrentTool = self.app.data.currentTool #print("positioning mode = "+str(self.app.data.positioningMode)) if update: statusData = { "uploadFlag": self.app.data.uploadFlag, "positioningMode": self.app.data.positioningMode, "currentTool": self.app.data.currentTool, } socketio.emit("message", { "command": "statusMessage", "data": json.dumps(statusData), "dataFormat": "json" }, namespace="/MaslowCNC")
def off_led(): global led_status global led_pin_num global led_pin_mode # 判斷呼吸燈是否已經打開 if led_status: # TODO: 檢查LED已經正確被關閉 led_status = False data = { 'pin': led_pin_num, 'mode': led_pin_mode, 'code': 200, 'accessory': 'breath_light', 'status': led_status, 'type': 'BreathLightCloseSuccess', 'msg': '呼吸燈已經關閉!' } socketio.emit('LED_off_publish_server', data, json=True, namespace='/pi', broadcast=True) return jsonify(data), 200 else: return jsonify({ 'pin': led_pin_num, 'mode': led_pin_mode, 'accessory': 'breath_light', 'status': led_status, 'error_code': 400, 'error_type': 'BreathLightUnopen', 'error_msg': '請勿在未開啟狀態關閉呼吸燈!!' }), 400 return jsonify(data), 400
def sendPositionMessage(self, position): socketio.emit("message", { "command": "positionMessage", "data": json.dumps(position), "dataFormat": "json" }, namespace="/MaslowCNC")
def check_motor_status(): global motor_status socketio.emit('motor_status_check_pub_system', {'action': 'check'}, json=True, broadcast=True, namespace='/pi') time.sleep(.5)
def sendControllerMessage(self, message): socketio.emit("message", { "command": "controllerMessage", "data": json.dumps(message), "dataFormat": "json" }, namespace="/MaslowCNC")
def off_led(): global infrared_status global pin_num global pin_mode # 判斷紅外線感測器是否已經打開 if infrared_status: # TODO: 檢查元件已經正確被關閉 infrared_status = False data = { 'pin': pin_num, 'mode': pin_mode, 'code': 200, 'accessory': 'infrared_sensor', 'status': infrared_status, 'type': 'InfraredSensorCloseSuccess', 'msg': '紅外線感測器已經關閉!' } socketio.emit('infrared_off_publish_server', data, json=True, namespace='/pi', broadcast=True) return jsonify(data), 200 else: return jsonify({ 'pin': pin_num, 'mode': pin_mode, 'accessory': 'infrared_sensor', 'status': infrared_status, 'error_code': 400, 'error_type': 'InfraredSensorUnopen', 'error_msg': '請勿在未開啟狀態關閉紅外線感測器!!' }), 400 return jsonify(data), 400
def cancel(self): if self.assigned_device: # from app import socketio target_device_id = self.assigned_device.id socketio.emit("cancel_job", { 'device_id': target_device_id, 'job_id': self.id })
def handle_json(json): socketio.emit('json', {'message': 'received ' + json['message']}, room=request.sid) threadPool.condition.acquire() threadPool.put((json['message'], request.sid, socketio)) threadPool.condition.notify() threadPool.condition.release()
def test_namespace(data): logger.debug(f"Namespace connection good {data}") socketio.emit("TEST_SUCCESSFUL", "test_namespace", namespace="/message", broadcast=True)
def start(self, _app): self.app = _app with self.app.app_context(): while True: time.sleep(0.001) while (not self.app.data.ui_queue.empty() ): # if there is new data to be read message = self.app.data.ui_queue.get() # send message to web for display in appropriate column #print(message) if message != "": try: if message[0:8] == "Message:": socketio.emit("webcontrolMessage", {"data": message[8:]}, namespace="/WebMCP") elif message[0:7] == "Action:": if message.find("setAsPause") != -1: socketio.emit( "requestedSetting", { "setting": "pauseButtonSetting", "value": "Pause" }, namespace="/MaslowCNC", ) if message.find("webControlStatus") != -1: msg = message.split("_") socketio.emit("webControlStatus", msg[1], namespace="/WebMCP") if message.find( "webControlResponsivenessStatus" ) != -1: msg = message.split("_") socketio.emit( "webControlResponsivenessStatus", msg[1], namespace="/WebMCP") if message.find("requestCheckIn") != -1: socketio.emit("checkInRequested", 'checkInPlease', namespace="/WebMCP", broadcast=True) #if message.find("connectToWebControl") != -1: # socketio.connect("http://127.0.0.1:5000/WebMCP") elif message[0:6] == "ALARM:": self.activateModal("Notification:", message[7:]) elif message == "ok\r\n": pass # displaying all the 'ok' messages clutters up the display else: #print("UIProcessor:"+message) self.sendUIMessage(message) except Exception as e: print(e) print(message)
def activateModal(self, title, message): socketio.emit( "activateModal", { "title": title, "message": message }, namespace="/WebMCP", )
def sendWebMCPMessage(self, message): ''' Seems to just send a shutdown message to webmcp.. everything else appears to be commented out. :param message: :return: ''' # print(message) # socketio.emit("message", {"command": json.dumps(message), "dataFormat": "json"},namespace="/WebMCP") socketio.emit("shutdown", namespace="/WebMCP")
def processMessage(self, _message): msg = json.loads(_message) if msg["command"] == "Action": if msg["message"] == "gcodeUpdate": self.sendGcodeUpdate() elif msg["message"] == "unitsUpdate": self.unitsUpdate() elif msg["message"] == "distToMoveUpdate": self.distToMoveUpdate() elif msg["message"] == "updateTimer": #Todo: clean this up self.sendCalibrationMessage("updateTimer", json.loads(msg["data"])) elif msg["message"] == "updateCamera": self.sendCameraMessage("updateCamera", json.loads(msg["data"])) else: if msg["message"] == "setAsPause": msg["message"] = "requestedSetting" msg["data"] = json.dumps({ "setting": "pauseButtonSetting", "value": "Pause" }) elif msg["message"] == "setAsResume": msg["message"] = "requestedSetting" msg["data"] = json.dumps({ "setting": "pauseButtonSetting", "value": "Resume" }) elif msg["message"] == "updatePorts": msg["data"] = json.dumps(self.app.data.comPorts) elif msg["message"] == "closeModals": msg["data"] = json.dumps({"title": msg["data"]}) socketio.emit("message", { "command": msg["message"], "data": msg["data"], "dataFormat": "json" }, namespace="/MaslowCNC") elif msg["command"] == "TextMessage": socketio.emit("message", { "command": "controllerMessage", "data": msg["data"], "dataFormat": "json" }, namespace="/MaslowCNC") elif msg["command"] == "Alert": #if message.find("adjust Z-Axis") != -1: # self.app.data.console_queue.put("found adjust Z-Axis in message") # self.activateModal("Notification:", message[9:], "notification", resume="resume") #else: self.activateModal(msg["message"], msg["data"], "notification") elif msg["command"] == "SpinnerMessage": self.activateModal("Notification:", msg["data"], "notification", progress="spinner")
def updatePIDData(self, message, _data=""): data = json.dumps({"command": message, "data": _data}) print(data) socketio.emit("message", { "command": "updatePIDData", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC")
def sendCameraMessage(self, message, _data=""): data = json.dumps({"command": message, "data": _data}) socketio.emit("message", { "command": "cameraMessage", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC")
def sendCalibrationImage(self, message, _data): data = json.dumps({"command": message, "data": _data}) socketio.emit("message", { "command": "updateCalibrationImage", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC")
def bread_led_status(data): global led_status led_status = data['status'] # 將目前狀態發布給Client端(結束LED也會主動發布給Server) emit_data = get_accessory_publish_data('breath_light', led_status) socketio.emit('accessory_status_pub_client', emit_data, json=True, broadcast=True, namespace='/client')
def bread_motor_status(data): global motor_status motor_status = data['status'] # 將目前狀態發布給Client端(結束也會主動發布給Server) emit_data = get_accessory_publish_data('motor', motor_status) socketio.emit('accessory_status_pub_client', emit_data, json=True, broadcast=True, namespace='/client')
def sendAlert(self, message): data = json.dumps({"message": message}) socketio.emit( "message", { "command": "alert", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC", )
def sendHealthMessage(self, healthData): ''' Sends the health message to UI client. Not sure why I separated this from the only function that calls it. :param position: :return: ''' socketio.emit("message", { "command": "healthMessage", "data": json.dumps(healthData), "dataFormat": "json" }, namespace="/MaslowCNC")
def sendErrorValueMessage(self, position): ''' Sends the error value message to UI client. Not sure why I separated this from the only function that calls it. :param position: :return: ''' socketio.emit("message", { "command": "errorValueMessage", "data": json.dumps(position), "dataFormat": "json" }, namespace="/MaslowCNC")
def unitsUpdate(self): units = self.app.data.config.getValue("Computed Settings", "units") data = json.dumps({"setting": "units", "value": units}) socketio.emit( "message", { "command": "requestedSetting", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC", )
def sendControllerMessage(self, message): ''' Sends a message from the controller to the UI client. This occurs for messages that aren't processed by webcontrol in the main UI Processor loop. :param message: :return: ''' socketio.emit("message", { "command": "controllerMessage", "data": json.dumps(message), "dataFormat": "json" }, namespace="/MaslowCNC")
def start(self, _app): print("Starting WebMCP Queue Processor") self.app = _app self.data.webMCPActive = True while True: time.sleep(0.001) while (not self.data.mcp_queue.empty()): # if there is new data to be read message = self.data.mcp_queue.get() #print("MCP Queue:"+message) if self.app is not None: with self.app.app_context(): #print("Emitting:"+message) socketio.emit("webcontrolMessage", {"data": message}, namespace="/WebMCP")
def model_train_status(data): global avatar_model_during_train avatar_model_during_train = data['status'] # 將目前狀態發布給Client端(結束LED也會主動發布給Server) emit_data = General.get_accessory_publish_data('face_model', avatar_model_during_train) print(emit_data) socketio.emit('model_train_pub_client', emit_data, json=True, broadcast=True, namespace='/client')
def updatePIDData(self, message, _data=""): ''' Sends PID test data to UI client. :param message: :param _data: :return: ''' data = json.dumps({"command": message, "data": _data}) socketio.emit("message", { "command": "updatePIDData", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC")
def sendCameraMessage(self, message, _data=""): ''' Sends message to the UI client regarding camera.. message could be to turn camera display on or off, or to update the camera display. :param message: :param _data: :return: ''' data = json.dumps({"command": message, "data": _data}) socketio.emit("message", { "command": "cameraMessage", "data": data, "dataFormat": "json" }, namespace="/MaslowCNC")