From 15a059c5e8ae62b32102ea7278954470906323f1 Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 12 Feb 2020 09:35:01 -0800 Subject: [PATCH 01/22] some debugger work --- src/adafruit_circuitplayground/debugger_communication_client.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/adafruit_circuitplayground/debugger_communication_client.py b/src/adafruit_circuitplayground/debugger_communication_client.py index d48fe748a..a4743ced5 100644 --- a/src/adafruit_circuitplayground/debugger_communication_client.py +++ b/src/adafruit_circuitplayground/debugger_communication_client.py @@ -41,6 +41,7 @@ def init_connection(port=CONSTANTS.DEFAULT_PORT): def __update_api_state(data, expected_events): try: event_state = json.loads(data) + active_device = event_state.get("active_device") for event in expected_events: express.cpx._Express__state[event] = event_state.get( event, express.cpx._Express__state[event] From 8f36dad7caeffeac09d723c648a59b61ba3a6ec2 Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 12 Feb 2020 11:16:54 -0800 Subject: [PATCH 02/22] debug restructure --- src/adafruit_circuitplayground/constants.py | 2 -- src/adafruit_circuitplayground/express.py | 2 +- src/adafruit_circuitplayground/pixel.py | 2 +- src/common/constants.py | 3 +++ .../debugger_communication_client.py | 24 +++++++++++++------ .../test_debugger_communication_client.py | 2 +- src/debug_user_code.py | 2 +- 7 files changed, 24 insertions(+), 13 deletions(-) rename src/{adafruit_circuitplayground => common}/debugger_communication_client.py (73%) rename src/{adafruit_circuitplayground => common}/test/test_debugger_communication_client.py (97%) diff --git a/src/adafruit_circuitplayground/constants.py b/src/adafruit_circuitplayground/constants.py index 4e6100d97..d0a4ef6fe 100644 --- a/src/adafruit_circuitplayground/constants.py +++ b/src/adafruit_circuitplayground/constants.py @@ -38,11 +38,9 @@ "RED_LED": "API.RED.LED", "PIXELS": "API.PIXELS", } -ERROR_SENDING_EVENT = "Error trying to send event to the process : " TIME_DELAY = 0.03 -DEFAULT_PORT = "5577" EVENTS_BUTTON_PRESS = ["button_a", "button_b", "switch"] diff --git a/src/adafruit_circuitplayground/express.py b/src/adafruit_circuitplayground/express.py index 9e20af4b2..aafc77555 100644 --- a/src/adafruit_circuitplayground/express.py +++ b/src/adafruit_circuitplayground/express.py @@ -12,7 +12,7 @@ from collections import namedtuple from applicationinsights import TelemetryClient from .telemetry import telemetry_py -from . import debugger_communication_client +from common import debugger_communication_client Acceleration = namedtuple("acceleration", ["x", "y", "z"]) diff --git a/src/adafruit_circuitplayground/pixel.py b/src/adafruit_circuitplayground/pixel.py index 631311ce8..d1c6e22d9 100644 --- a/src/adafruit_circuitplayground/pixel.py +++ b/src/adafruit_circuitplayground/pixel.py @@ -9,7 +9,7 @@ from applicationinsights import TelemetryClient from . import constants as CONSTANTS from .telemetry import telemetry_py -from . import debugger_communication_client +from common import debugger_communication_client class Pixel: diff --git a/src/common/constants.py b/src/common/constants.py index 97ea32386..1e28ff603 100644 --- a/src/common/constants.py +++ b/src/common/constants.py @@ -1,3 +1,6 @@ MAC_OS = "darwin" TIME_DELAY = 0.03 + +ERROR_SENDING_EVENT = "Error trying to send event to the process : " +DEFAULT_PORT = "5577" \ No newline at end of file diff --git a/src/adafruit_circuitplayground/debugger_communication_client.py b/src/common/debugger_communication_client.py similarity index 73% rename from src/adafruit_circuitplayground/debugger_communication_client.py rename to src/common/debugger_communication_client.py index a4743ced5..51a461831 100644 --- a/src/adafruit_circuitplayground/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -5,22 +5,31 @@ import json import socketio import copy -from . import express +# from adafruit_circuitplayground import cpx +# from microbit import __mb as mb from . import constants as CONSTANTS from common import utils +from adafruit_circuitplayground.express import cpx +from adafruit_circuitplayground.constants import CPX + +from microbit.__model.microbit_model import __mb as mb +from microbit.__model.constants import MICROBIT + + +device_dict = {CPX: cpx, MICROBIT: mb} previous_state = {} # similar to utils.send_to_simulator, but for debugging # (needs handle to device-specific debugger) -def debug_show(state): +def debug_show(state, active_device): global previous_state if state != previous_state: previous_state = copy.deepcopy(state) - updated_state = utils.update_state_with_device_name(state, CONSTANTS.CPX) + updated_state = utils.update_state_with_device_name(state, active_device) message = utils.create_message(updated_state) update_state(json.dumps(message)) @@ -42,10 +51,11 @@ def __update_api_state(data, expected_events): try: event_state = json.loads(data) active_device = event_state.get("active_device") - for event in expected_events: - express.cpx._Express__state[event] = event_state.get( - event, express.cpx._Express__state[event] - ) + + # for event in expected_events: + # express.cpx._Express__state[event] = event_state.get( + # event, express.cpx._Express__state[event] + # ) except Exception as e: print(CONSTANTS.ERROR_SENDING_EVENT, e, file=sys.stderr, flush=True) diff --git a/src/adafruit_circuitplayground/test/test_debugger_communication_client.py b/src/common/test/test_debugger_communication_client.py similarity index 97% rename from src/adafruit_circuitplayground/test/test_debugger_communication_client.py rename to src/common/test/test_debugger_communication_client.py index b25e27eb8..6c1e158d5 100644 --- a/src/adafruit_circuitplayground/test/test_debugger_communication_client.py +++ b/src/common/test/test_debugger_communication_client.py @@ -3,7 +3,7 @@ from unittest import mock import socketio -from .. import express +from adafruit_circuitplayground import express from .. import debugger_communication_client diff --git a/src/debug_user_code.py b/src/debug_user_code.py index 8d5b57873..724a39b63 100644 --- a/src/debug_user_code.py +++ b/src/debug_user_code.py @@ -20,7 +20,7 @@ # This import must happen after the sys.path is modified from adafruit_circuitplayground.express import cpx -from adafruit_circuitplayground import debugger_communication_client +from common import debugger_communication_client ## Execute User Code ## From 429ef24127d2eb3ec5f02860b788cf61421e3f98 Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 12 Feb 2020 14:42:55 -0800 Subject: [PATCH 03/22] merged listeners --- src/common/constants.py | 10 +++++++++- src/common/debugger_communication_client.py | 13 +++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/common/constants.py b/src/common/constants.py index 1e28ff603..c5eb88463 100644 --- a/src/common/constants.py +++ b/src/common/constants.py @@ -1,6 +1,14 @@ +from enum import Enum + MAC_OS = "darwin" TIME_DELAY = 0.03 ERROR_SENDING_EVENT = "Error trying to send event to the process : " -DEFAULT_PORT = "5577" \ No newline at end of file +DEFAULT_PORT = "5577" + + +# class EventTypes(Enum): +# sensor = 1 +# button = 2 +# all = 3 diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 48d2b5195..56d82500e 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -5,6 +5,7 @@ import json import socketio import copy + # from adafruit_circuitplayground import cpx # from microbit import __mb as mb from . import constants as CONSTANTS @@ -47,15 +48,11 @@ def init_connection(port=CONSTANTS.DEFAULT_PORT): # Transfer the user's inputs to the API -def __update_api_state(data, expected_events): +def __update_api_state(data): try: event_state = json.loads(data) active_device = event_state.get("active_device") - - # for event in expected_events: - # express.cpx._Express__state[event] = event_state.get( - # event, express.cpx._Express__state[event] - # ) + device_dict[active_device].update_state(data) except Exception as e: print(CONSTANTS.ERROR_SENDING_EVENT, e, file=sys.stderr, flush=True) @@ -71,10 +68,10 @@ def update_state(state): # Event : Button pressed (A, B, A+B, Switch) @sio.on("button_press") def button_press(data): - __update_api_state(data, CONSTANTS.EVENTS_BUTTON_PRESS) + __update_api_state(data) # Event : Sensor changed (Temperature, light, Motion) @sio.on("sensor_changed") def sensor_changed(data): - __update_api_state(data, CONSTANTS.EVENTS_SENSOR_CHANGED) + __update_api_state(data) From 8eae51302d8baa16bb8bd4ae9806f318bde2656e Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 12 Feb 2020 16:50:44 -0800 Subject: [PATCH 04/22] fixed circular dependency --- src/adafruit_circuitplayground/express.py | 6 ++++-- src/adafruit_circuitplayground/pixel.py | 9 +++++---- src/common/constants.py | 6 +----- src/common/debugger_communication_client.py | 7 +++---- 4 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/adafruit_circuitplayground/express.py b/src/adafruit_circuitplayground/express.py index aafc77555..e9098ced7 100644 --- a/src/adafruit_circuitplayground/express.py +++ b/src/adafruit_circuitplayground/express.py @@ -12,7 +12,7 @@ from collections import namedtuple from applicationinsights import TelemetryClient from .telemetry import telemetry_py -from common import debugger_communication_client +import common Acceleration = namedtuple("acceleration", ["x", "y", "z"]) @@ -108,7 +108,9 @@ def light(self): def __show(self): if self.__debug_mode: - debugger_communication_client.debug_send_to_simulator(self.__state) + common.debugger_communication_client.debug_send_to_simulator( + self.__state, CONSTANTS.CPX + ) else: utils.send_to_simulator(self.__state, CONSTANTS.CPX) diff --git a/src/adafruit_circuitplayground/pixel.py b/src/adafruit_circuitplayground/pixel.py index d1c6e22d9..6be9906af 100644 --- a/src/adafruit_circuitplayground/pixel.py +++ b/src/adafruit_circuitplayground/pixel.py @@ -3,13 +3,12 @@ import json import sys -from common import utils +import common from . import constants as CONSTANTS from applicationinsights import TelemetryClient from . import constants as CONSTANTS from .telemetry import telemetry_py -from common import debugger_communication_client class Pixel: @@ -23,9 +22,11 @@ def show(self): # Send the state to the extension so that React re-renders the Webview # or send the state to the debugger (within this library) if self.__debug_mode: - debugger_communication_client.debug_send_to_simulator(self.__state) + common.debugger_communication_client.debug_send_to_simulator( + self.__state, CONSTANTS.CPX + ) else: - utils.send_to_simulator(self.__state, CONSTANTS.CPX) + common.utils.send_to_simulator(self.__state, CONSTANTS.CPX) def __show_if_auto_write(self): if self.auto_write: diff --git a/src/common/constants.py b/src/common/constants.py index c5eb88463..28658d4fe 100644 --- a/src/common/constants.py +++ b/src/common/constants.py @@ -7,8 +7,4 @@ ERROR_SENDING_EVENT = "Error trying to send event to the process : " DEFAULT_PORT = "5577" - -# class EventTypes(Enum): -# sensor = 1 -# button = 2 -# all = 3 +ACTIVE_DEVICE_FIELD = "active_device" diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 56d82500e..2a6428546 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -6,10 +6,8 @@ import socketio import copy -# from adafruit_circuitplayground import cpx -# from microbit import __mb as mb from . import constants as CONSTANTS -from common import utils +from . import utils from adafruit_circuitplayground.express import cpx @@ -51,7 +49,8 @@ def init_connection(port=CONSTANTS.DEFAULT_PORT): def __update_api_state(data): try: event_state = json.loads(data) - active_device = event_state.get("active_device") + active_device = event_state.get(CONSTANTS.ACTIVE_DEVICE_FIELD) + # can we do without this? device_dict[active_device].update_state(data) except Exception as e: print(CONSTANTS.ERROR_SENDING_EVENT, e, file=sys.stderr, flush=True) From 997719dd84917891e8c819c3b0ec521b41d26a68 Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Thu, 13 Feb 2020 08:22:12 -0800 Subject: [PATCH 05/22] Remove duplicate emitter --- src/debuggerCommunicationServer.ts | 15 ++++++--------- src/extension.ts | 9 ++++++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index 76eb02f42..3c6a82056 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -24,6 +24,7 @@ export class DebuggerCommunicationServer { this.simulatorWebview = webviewPanel; this.initEventsHandlers(); console.info(`Server running on port ${this.port}`); + } public closeConnection(): void { @@ -36,16 +37,9 @@ export class DebuggerCommunicationServer { this.simulatorWebview = webviewPanel; } - // Emit Buttons Inputs Events - public emitButtonPress(newState: string): void { - console.log(`Emit Button Press: ${newState} \n`); - this.serverIo.emit("button_press", newState); - } - // Emit Sensors Inputs Events - public emitSensorChanged(newState: string): void { - console.log(`Emit Sensor Changed: ${newState} \n`); - this.serverIo.emit("sensor_changed", newState); + public emitInputChanged(newState:string):void{ + this.serverIo.emit("input_changed",newState) } private initHttpServer(): void { @@ -76,11 +70,14 @@ export class DebuggerCommunicationServer { private handleState(data: any): void { try { + console.log("handleState") const messageToWebview = JSON.parse(data); + console.log(messageToWebview) if (messageToWebview.type === "state") { console.log(`State recieved: ${messageToWebview.data}`); if (this.simulatorWebview) { this.simulatorWebview.webview.postMessage({ + active_device:this.currentActiveDevice, command: "set-state", state: JSON.parse(messageToWebview.data), }); diff --git a/src/extension.ts b/src/extension.ts index 463320436..438bb90c3 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -176,7 +176,7 @@ export async function activate(context: vscode.ExtensionContext) { inDebugMode && debuggerCommunicationHandler ) { - debuggerCommunicationHandler.emitButtonPress( + debuggerCommunicationHandler.emitInputChanged( messageJson ); } else if (childProcess) { @@ -223,7 +223,7 @@ export async function activate(context: vscode.ExtensionContext) { inDebugMode && debuggerCommunicationHandler ) { - debuggerCommunicationHandler.emitSensorChanged( + debuggerCommunicationHandler.emitInputChanged( messageJson ); } else if (childProcess) { @@ -425,6 +425,7 @@ export async function activate(context: vscode.ExtensionContext) { const runSimulatorCommand = async () => { // Prevent running new code if a debug session is active if (inDebugMode) { + console.log("debug mode not running simulator command") vscode.window.showErrorMessage( CONSTANTS.ERROR.DEBUGGING_SESSION_IN_PROGESS ); @@ -543,6 +544,7 @@ export async function activate(context: vscode.ExtensionContext) { childProcess.stdout.on("data", data => { dataFromTheProcess = data.toString(); if (currentPanel) { + console.log("receiving message") // Process the data from the process and send one state at a time dataFromTheProcess.split("\0").forEach(message => { if ( @@ -915,7 +917,8 @@ export async function activate(context: vscode.ExtensionContext) { debuggerCommunicationHandler = new DebuggerCommunicationServer( currentPanel, - utils.getServerPortConfig() + utils.getServerPortConfig(), + ); openWebview(); if (currentPanel) { From f657255482cf9292d7d9f633a27519239a1ca7f6 Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Thu, 13 Feb 2020 09:16:37 -0800 Subject: [PATCH 06/22] Load device into script tag for initial open --- src/debuggerCommunicationServer.ts | 5 ++++- src/extension.ts | 8 +++++--- src/view/App.tsx | 8 ++++++++ src/view/index.tsx | 1 - 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index 3c6a82056..eaf9909de 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -11,10 +11,12 @@ export class DebuggerCommunicationServer { private serverHttp: http.Server; private serverIo: socketio.Server; private simulatorWebview: WebviewPanel | undefined; + private currentActiveDevice; constructor( webviewPanel: WebviewPanel | undefined, - port = SERVER_INFO.DEFAULT_SERVER_PORT + port = SERVER_INFO.DEFAULT_SERVER_PORT, + currentActiveDevice:string ) { this.port = port; this.serverHttp = new http.Server(); @@ -25,6 +27,7 @@ export class DebuggerCommunicationServer { this.initEventsHandlers(); console.info(`Server running on port ${this.port}`); + this.currentActiveDevice=currentActiveDevice } public closeConnection(): void { diff --git a/src/extension.ts b/src/extension.ts index 438bb90c3..56de0dc64 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -41,7 +41,7 @@ let currentActiveDevice: string = DEFAULT_DEVICE; export let outChannel: vscode.OutputChannel | undefined; function loadScript(context: vscode.ExtensionContext, scriptPath: string) { - return ``; } @@ -138,6 +138,7 @@ export async function activate(context: vscode.ExtensionContext) { enableScripts: true, } ); + currentPanel.webview.html = getWebviewContent(context); @@ -918,7 +919,7 @@ export async function activate(context: vscode.ExtensionContext) { debuggerCommunicationHandler = new DebuggerCommunicationServer( currentPanel, utils.getServerPortConfig(), - + currentActiveDevice ); openWebview(); if (currentPanel) { @@ -1140,9 +1141,10 @@ function getWebviewContent(context: vscode.ExtensionContext) {
- + ${loadScript(context, "out/vendor.js")} ${loadScript(context, "out/simulator.js")} diff --git a/src/view/App.tsx b/src/view/App.tsx index cff908a5a..c8bff087b 100644 --- a/src/view/App.tsx +++ b/src/view/App.tsx @@ -28,6 +28,14 @@ class App extends React.Component<{}, IState> { this.state = defaultState; } componentDidMount() { + if (document.currentScript) { + const initialDevice = document.currentScript.getAttribute('initialDevice') + + if (initialDevice) { + this.setState({ currentDevice: initialDevice }) + + } + } window.addEventListener("message", this.handleMessage); } componentWillUnmount() { diff --git a/src/view/index.tsx b/src/view/index.tsx index 9b0fc44a2..32e7400b1 100644 --- a/src/view/index.tsx +++ b/src/view/index.tsx @@ -14,7 +14,6 @@ const locale = "en"; const message = { en: messageEn, }; - ReactDOM.render( From f7e5b528410e892a1096713e5c1bee92306d80d0 Mon Sep 17 00:00:00 2001 From: andreamah Date: Thu, 13 Feb 2020 10:27:20 -0800 Subject: [PATCH 07/22] modified debugger listener --- src/adafruit_circuitplayground/constants.py | 1 - src/common/debugger_communication_client.py | 14 ++++---------- .../test/test_debugger_communication_client.py | 4 ++-- 3 files changed, 6 insertions(+), 13 deletions(-) diff --git a/src/adafruit_circuitplayground/constants.py b/src/adafruit_circuitplayground/constants.py index d0a4ef6fe..583181c85 100644 --- a/src/adafruit_circuitplayground/constants.py +++ b/src/adafruit_circuitplayground/constants.py @@ -42,7 +42,6 @@ TIME_DELAY = 0.03 - EVENTS_BUTTON_PRESS = ["button_a", "button_b", "switch"] EVENTS_SENSOR_CHANGED = ["temperature", "light", "motion_x", "motion_y", "motion_z"] diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 2a6428546..e13920fbb 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -61,16 +61,10 @@ def update_state(state): sio.emit("updateState", state) -## Events Handlers ## - +## Events Handler ## # Event : Button pressed (A, B, A+B, Switch) -@sio.on("button_press") -def button_press(data): - __update_api_state(data) - - -# Event : Sensor changed (Temperature, light, Motion) -@sio.on("sensor_changed") -def sensor_changed(data): +# or Sensor changed (Temperature, light, Motion) +@sio.on("input_changed") +def input_changed(data): __update_api_state(data) diff --git a/src/common/test/test_debugger_communication_client.py b/src/common/test/test_debugger_communication_client.py index 6c1e158d5..acc3b2c37 100644 --- a/src/common/test/test_debugger_communication_client.py +++ b/src/common/test/test_debugger_communication_client.py @@ -34,7 +34,7 @@ def test_update_state(self): def test_button_press(self): data = {"button_a": True, "button_b": True, "switch": True} serialized_data = json.dumps(data) - debugger_communication_client.button_press(serialized_data) + debugger_communication_client.input_changed(serialized_data) assert data == express.cpx._Express__state @mock.patch.dict( @@ -51,7 +51,7 @@ def test_sensor_changed(self): "motion_z": 5, } serialized_data = json.dumps(data) - debugger_communication_client.sensor_changed(serialized_data) + debugger_communication_client.input_changed(serialized_data) assert data == express.cpx._Express__state @mock.patch("builtins.print") From 88bff5e12dae335c66a1e5e026e19093d3544b01 Mon Sep 17 00:00:00 2001 From: andreamah Date: Thu, 13 Feb 2020 10:53:02 -0800 Subject: [PATCH 08/22] connected microbit to debugger --- src/common/debugger_communication_client.py | 1 - src/debug_user_code.py | 2 ++ src/microbit/__model/display.py | 12 ++++++++++-- src/microbit/__model/microbit_model.py | 3 +++ 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index e13920fbb..7271c47c3 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -24,7 +24,6 @@ # (needs handle to device-specific debugger) def debug_send_to_simulator(state, active_device): global previous_state - if state != previous_state: previous_state = copy.deepcopy(state) diff --git a/src/debug_user_code.py b/src/debug_user_code.py index 724a39b63..2ea654ac0 100644 --- a/src/debug_user_code.py +++ b/src/debug_user_code.py @@ -20,6 +20,7 @@ # This import must happen after the sys.path is modified from adafruit_circuitplayground.express import cpx +from microbit.__model.microbit_model import __mb as mb from common import debugger_communication_client @@ -45,6 +46,7 @@ cpx._Express__abs_path_to_code_file = abs_path_to_code_file cpx._Express__debug_mode = True cpx.pixels._Pixel__set_debug_mode(True) +mb._MicrobitModel__set_debug_mode(True) # Execute the user's code file with open(abs_path_to_code_file) as user_code_file: diff --git a/src/microbit/__model/display.py b/src/microbit/__model/display.py index ff62e4e59..2aaef6760 100644 --- a/src/microbit/__model/display.py +++ b/src/microbit/__model/display.py @@ -1,7 +1,7 @@ import copy import time import threading -from common import utils +import common from . import constants as CONSTANTS from .image import Image @@ -18,6 +18,7 @@ def __init__(self): self.__current_pid = None self.__lock = threading.Lock() + self.__debug_mode = False def scroll(self, value, delay=150, wait=True, loop=False, monospace=False): """ @@ -336,7 +337,13 @@ def __create_scroll_image(images): def __update_client(self): sendable_json = {"leds": self.__get_array()} - utils.send_to_simulator(sendable_json, CONSTANTS.MICROBIT) + + if self.__debug_mode: + common.debugger_communication_client.debug_send_to_simulator( + sendable_json, CONSTANTS.MICROBIT + ) + else: + common.utils.send_to_simulator(sendable_json, CONSTANTS.MICROBIT) def __update_light_level(self, new_light_level): if new_light_level is not None: @@ -347,3 +354,4 @@ def __update_light_level(self, new_light_level): @staticmethod def sleep_ms(ms): time.sleep(ms / 1000) + diff --git a/src/microbit/__model/microbit_model.py b/src/microbit/__model/microbit_model.py index cf00452be..e1bbb8971 100644 --- a/src/microbit/__model/microbit_model.py +++ b/src/microbit/__model/microbit_model.py @@ -71,5 +71,8 @@ def __update_temp(self, new_state): if new_temp != previous_temp: self._MicrobitModel__set_temperature(new_temp) + def __set_debug_mode(self, mode): + self.display._Display__debug_mode = mode + __mb = MicrobitModel() From c5dddb81f589cd1d99b26f04fd03360c49a049d7 Mon Sep 17 00:00:00 2001 From: andreamah Date: Tue, 18 Feb 2020 16:15:38 -0800 Subject: [PATCH 09/22] handshake for client communication --- src/common/debugger_communication_client.py | 11 +++++++++-- src/debuggerCommunicationServer.ts | 11 ++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 7271c47c3..d552343c8 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -19,6 +19,7 @@ device_dict = {CPX: cpx, MICROBIT: mb} previous_state = {} +processing_state = False # similar to utils.send_to_simulator, but for debugging # (needs handle to device-specific debugger) @@ -58,12 +59,18 @@ def __update_api_state(data): # Method : Update State def update_state(state): sio.emit("updateState", state) + processing_state = False + while not processing_state: + pass -## Events Handler ## - # Event : Button pressed (A, B, A+B, Switch) # or Sensor changed (Temperature, light, Motion) @sio.on("input_changed") def input_changed(data): __update_api_state(data) + + +@sio.on("received_state") +def received_state(data): + processing_state = True diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index eaf9909de..5364c0137 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -16,7 +16,7 @@ export class DebuggerCommunicationServer { constructor( webviewPanel: WebviewPanel | undefined, port = SERVER_INFO.DEFAULT_SERVER_PORT, - currentActiveDevice:string + currentActiveDevice: string ) { this.port = port; this.serverHttp = new http.Server(); @@ -27,7 +27,7 @@ export class DebuggerCommunicationServer { this.initEventsHandlers(); console.info(`Server running on port ${this.port}`); - this.currentActiveDevice=currentActiveDevice + this.currentActiveDevice = currentActiveDevice } public closeConnection(): void { @@ -41,8 +41,8 @@ export class DebuggerCommunicationServer { } - public emitInputChanged(newState:string):void{ - this.serverIo.emit("input_changed",newState) + public emitInputChanged(newState: string): void { + this.serverIo.emit("input_changed", newState) } private initHttpServer(): void { @@ -58,6 +58,7 @@ export class DebuggerCommunicationServer { socket.on("updateState", (data: any) => { this.handleState(data); + this.serverIo.emit("received_state", {}) }); socket.on("disconnect", () => { @@ -80,7 +81,7 @@ export class DebuggerCommunicationServer { console.log(`State recieved: ${messageToWebview.data}`); if (this.simulatorWebview) { this.simulatorWebview.webview.postMessage({ - active_device:this.currentActiveDevice, + active_device: this.currentActiveDevice, command: "set-state", state: JSON.parse(messageToWebview.data), }); From a050aff9ca8a2ba6b45b32d1a549b6c6011b74dc Mon Sep 17 00:00:00 2001 From: andreamah Date: Tue, 18 Feb 2020 16:42:57 -0800 Subject: [PATCH 10/22] updated debugger client --- src/common/debugger_communication_client.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index d552343c8..8abcb9601 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -8,6 +8,7 @@ from . import constants as CONSTANTS from . import utils +import threading from adafruit_circuitplayground.express import cpx @@ -19,7 +20,8 @@ device_dict = {CPX: cpx, MICROBIT: mb} previous_state = {} -processing_state = False +# processing_state = False +processing_state_event = threading.Event() # similar to utils.send_to_simulator, but for debugging # (needs handle to device-specific debugger) @@ -58,19 +60,19 @@ def __update_api_state(data): # Method : Update State def update_state(state): + processing_state_event.clear() sio.emit("updateState", state) - processing_state = False - while not processing_state: - pass + processing_state_event.wait() # Event : Button pressed (A, B, A+B, Switch) # or Sensor changed (Temperature, light, Motion) @sio.on("input_changed") def input_changed(data): + sio.emit("receivedState", {}) __update_api_state(data) @sio.on("received_state") def received_state(data): - processing_state = True + processing_state_event.set() From b3f6567ea438e1b75de7b25f59191309a89cdcc2 Mon Sep 17 00:00:00 2001 From: andreamah Date: Tue, 18 Feb 2020 17:17:26 -0800 Subject: [PATCH 11/22] modifications to active device microbit --- src/common/debugger_communication_client.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 8abcb9601..2427c6f83 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -51,9 +51,12 @@ def init_connection(port=CONSTANTS.DEFAULT_PORT): def __update_api_state(data): try: event_state = json.loads(data) + print(event_state) active_device = event_state.get(CONSTANTS.ACTIVE_DEVICE_FIELD) + print(active_device) # can we do without this? - device_dict[active_device].update_state(data) + if active_device is None: + device_dict[active_device].update_state(data) except Exception as e: print(CONSTANTS.ERROR_SENDING_EVENT, e, file=sys.stderr, flush=True) @@ -69,7 +72,8 @@ def update_state(state): # or Sensor changed (Temperature, light, Motion) @sio.on("input_changed") def input_changed(data): - sio.emit("receivedState", {}) + print("input changed!") + sio.emit("receivedState", data) __update_api_state(data) From 7f5bdb2d7ee431deec62783a0f6f896acc1bd6bc Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Wed, 19 Feb 2020 08:59:13 -0800 Subject: [PATCH 12/22] Emit only when the calls are finished --- src/debuggerCommunicationServer.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index 5364c0137..f06dbc3d1 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -12,6 +12,8 @@ export class DebuggerCommunicationServer { private serverIo: socketio.Server; private simulatorWebview: WebviewPanel | undefined; private currentActiveDevice; + private isWaitingResponse = false; + private currentCall :Array= [] constructor( webviewPanel: WebviewPanel | undefined, @@ -42,7 +44,18 @@ export class DebuggerCommunicationServer { public emitInputChanged(newState: string): void { - this.serverIo.emit("input_changed", newState) + if(this.isWaitingResponse){ + console.log('I have added a call to the queue') + this.currentCall.push(()=>{ + console.log("I will send another input for sensor_changed") + this.serverIo.emit("input_changed", newState) + this.isWaitingResponse=true; + }) + + }else{ + this.serverIo.emit("input_changed", newState) + this.isWaitingResponse=true; + } } private initHttpServer(): void { @@ -60,6 +73,17 @@ export class DebuggerCommunicationServer { this.handleState(data); this.serverIo.emit("received_state", {}) }); + socket.on("receivedState",()=>{ + this.isWaitingResponse=false; + if(this.currentCall.length>0){ + let currentCall = this.currentCall.shift() + console.log("The previous state has been received by the python api") + currentCall() + } + + } + + ); socket.on("disconnect", () => { console.log("Socket disconnected"); From 297dd8750a27959c8c9ef99508488fe5971851fc Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Wed, 19 Feb 2020 11:31:17 -0800 Subject: [PATCH 13/22] Reformatting --- src/microbit/__model/display.py | 1 - src/view/App.tsx | 7 ++++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/microbit/__model/display.py b/src/microbit/__model/display.py index 2aaef6760..5b0eef549 100644 --- a/src/microbit/__model/display.py +++ b/src/microbit/__model/display.py @@ -354,4 +354,3 @@ def __update_light_level(self, new_light_level): @staticmethod def sleep_ms(ms): time.sleep(ms / 1000) - diff --git a/src/view/App.tsx b/src/view/App.tsx index c8bff087b..3e96b0adf 100644 --- a/src/view/App.tsx +++ b/src/view/App.tsx @@ -29,11 +29,12 @@ class App extends React.Component<{}, IState> { } componentDidMount() { if (document.currentScript) { - const initialDevice = document.currentScript.getAttribute('initialDevice') + const initialDevice = document.currentScript.getAttribute( + "initialDevice" + ); if (initialDevice) { - this.setState({ currentDevice: initialDevice }) - + this.setState({ currentDevice: initialDevice }); } } window.addEventListener("message", this.handleMessage); From 2fb6f9f385e52d55953343b97758058be3ad04d6 Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 19 Feb 2020 15:01:34 -0800 Subject: [PATCH 14/22] fixed backend socket issue --- src/common/constants.py | 5 +++-- src/common/debugger_communication_client.py | 16 ++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/common/constants.py b/src/common/constants.py index 28658d4fe..1f43e131c 100644 --- a/src/common/constants.py +++ b/src/common/constants.py @@ -1,5 +1,3 @@ -from enum import Enum - MAC_OS = "darwin" TIME_DELAY = 0.03 @@ -8,3 +6,6 @@ DEFAULT_PORT = "5577" ACTIVE_DEVICE_FIELD = "active_device" +STATE_FIELD = "state" + +CONNECTION_ATTEMPTS = 10 diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 2427c6f83..13848af6d 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -37,7 +37,7 @@ def debug_send_to_simulator(state, active_device): # Create Socket Client -sio = socketio.Client(reconnection_attempts=2) +sio = socketio.Client(reconnection_attempts=CONSTANTS.CONNECTION_ATTEMPTS) # TODO: Get port from process_user_code.py via childprocess communication @@ -51,12 +51,13 @@ def init_connection(port=CONSTANTS.DEFAULT_PORT): def __update_api_state(data): try: event_state = json.loads(data) - print(event_state) - active_device = event_state.get(CONSTANTS.ACTIVE_DEVICE_FIELD) - print(active_device) - # can we do without this? - if active_device is None: - device_dict[active_device].update_state(data) + active_device_string = event_state.get(CONSTANTS.ACTIVE_DEVICE_FIELD) + + if active_device_string is not None: + active_device = device_dict.get(active_device_string) + if active_device is not None: + active_device.update_state(event_state.get(CONSTANTS.STATE_FIELD)) + except Exception as e: print(CONSTANTS.ERROR_SENDING_EVENT, e, file=sys.stderr, flush=True) @@ -72,7 +73,6 @@ def update_state(state): # or Sensor changed (Temperature, light, Motion) @sio.on("input_changed") def input_changed(data): - print("input changed!") sio.emit("receivedState", data) __update_api_state(data) From 5ab2a1b285bc6b5b72ad44e04d1a4ffc1087d4f7 Mon Sep 17 00:00:00 2001 From: andreamah Date: Wed, 19 Feb 2020 17:34:21 -0800 Subject: [PATCH 15/22] disconnect works when program is done --- src/common/debugger_communication_client.py | 17 +++++++++++++++++ src/debug_user_code.py | 2 ++ src/debuggerCommunicationServer.ts | 21 +++++++++++---------- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 13848af6d..9ccf9059d 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -80,3 +80,20 @@ def input_changed(data): @sio.on("received_state") def received_state(data): processing_state_event.set() + + +# @sio.event +# def disconnect(): +# print("I'm disconnected!") + + +@sio.on("frontend_disconnected") +def frontend_disconnected(data): + print("disconnecting...") + sio.disconnect() + + +def disconnect_socket(): + print("disconnecting here!") + sio.disconnect() + diff --git a/src/debug_user_code.py b/src/debug_user_code.py index 2ea654ac0..0e356880b 100644 --- a/src/debug_user_code.py +++ b/src/debug_user_code.py @@ -63,3 +63,5 @@ for frameIndex in range(2, len(stackTrace) - 1): errorMessage += "\t" + str(stackTrace[frameIndex]) print(e, errorMessage, file=sys.stderr, flush=True) + + debugger_communication_client.disconnect_socket() diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index f06dbc3d1..e942f2737 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -13,7 +13,7 @@ export class DebuggerCommunicationServer { private simulatorWebview: WebviewPanel | undefined; private currentActiveDevice; private isWaitingResponse = false; - private currentCall :Array= [] + private currentCall: Array = [] constructor( webviewPanel: WebviewPanel | undefined, @@ -44,17 +44,17 @@ export class DebuggerCommunicationServer { public emitInputChanged(newState: string): void { - if(this.isWaitingResponse){ + if (this.isWaitingResponse) { console.log('I have added a call to the queue') - this.currentCall.push(()=>{ + this.currentCall.push(() => { console.log("I will send another input for sensor_changed") this.serverIo.emit("input_changed", newState) - this.isWaitingResponse=true; + this.isWaitingResponse = true; }) - }else{ + } else { this.serverIo.emit("input_changed", newState) - this.isWaitingResponse=true; + this.isWaitingResponse = true; } } @@ -73,19 +73,20 @@ export class DebuggerCommunicationServer { this.handleState(data); this.serverIo.emit("received_state", {}) }); - socket.on("receivedState",()=>{ - this.isWaitingResponse=false; - if(this.currentCall.length>0){ + socket.on("receivedState", () => { + this.isWaitingResponse = false; + if (this.currentCall.length > 0) { let currentCall = this.currentCall.shift() console.log("The previous state has been received by the python api") currentCall() } - + } ); socket.on("disconnect", () => { + this.serverIo.emit("frontend_disconnected", {}) console.log("Socket disconnected"); if (this.simulatorWebview) { this.simulatorWebview.webview.postMessage({ From ca7d7ea1f97e43a4f6c424b75a711ec080cc4a13 Mon Sep 17 00:00:00 2001 From: andreamah Date: Thu, 20 Feb 2020 14:04:35 -0800 Subject: [PATCH 16/22] debugger work --- src/common/debugger_communication_client.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 9ccf9059d..28852ad9c 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -97,3 +97,9 @@ def disconnect_socket(): print("disconnecting here!") sio.disconnect() +import signal + +def handler(signum, frame): + print('Signal handler called with signal', signum) + +signal.signal(signal.SIGABRT, handler) \ No newline at end of file From b6453024d8e6e3f7e35c972b88135c54529c3916 Mon Sep 17 00:00:00 2001 From: andreamah Date: Thu, 20 Feb 2020 15:57:11 -0800 Subject: [PATCH 17/22] backend cleanup --- src/common/constants.py | 5 ++-- src/common/debugger_communication_client.py | 26 +-------------------- 2 files changed, 3 insertions(+), 28 deletions(-) diff --git a/src/common/constants.py b/src/common/constants.py index 1f43e131c..73984933a 100644 --- a/src/common/constants.py +++ b/src/common/constants.py @@ -1,11 +1,10 @@ MAC_OS = "darwin" -TIME_DELAY = 0.03 - ERROR_SENDING_EVENT = "Error trying to send event to the process : " -DEFAULT_PORT = "5577" ACTIVE_DEVICE_FIELD = "active_device" STATE_FIELD = "state" CONNECTION_ATTEMPTS = 10 +TIME_DELAY = 0.03 +DEFAULT_PORT = "5577" diff --git a/src/common/debugger_communication_client.py b/src/common/debugger_communication_client.py index 28852ad9c..4760020d0 100644 --- a/src/common/debugger_communication_client.py +++ b/src/common/debugger_communication_client.py @@ -19,9 +19,8 @@ device_dict = {CPX: cpx, MICROBIT: mb} -previous_state = {} -# processing_state = False processing_state_event = threading.Event() +previous_state = {} # similar to utils.send_to_simulator, but for debugging # (needs handle to device-specific debugger) @@ -80,26 +79,3 @@ def input_changed(data): @sio.on("received_state") def received_state(data): processing_state_event.set() - - -# @sio.event -# def disconnect(): -# print("I'm disconnected!") - - -@sio.on("frontend_disconnected") -def frontend_disconnected(data): - print("disconnecting...") - sio.disconnect() - - -def disconnect_socket(): - print("disconnecting here!") - sio.disconnect() - -import signal - -def handler(signum, frame): - print('Signal handler called with signal', signum) - -signal.signal(signal.SIGABRT, handler) \ No newline at end of file From 25f2d5a3490016af8b699106c7db0bf985be0bee Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Thu, 20 Feb 2020 16:12:21 -0800 Subject: [PATCH 18/22] Make messages constant --- src/debuggerCommunicationServer.ts | 61 +++++++++++++++++------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index e942f2737..307f475ae 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -6,6 +6,19 @@ import * as socketio from "socket.io"; import { WebviewPanel } from "vscode"; import { SERVER_INFO } from "./constants"; +const DEBUGGER_MESSAGES = { + EMITTER: { + INPUT_CHANGED: "input_changed", + RECEIVED_STATE: "received_state", + DISCONNECT: "frontend_disconnected", + }, + LISTENER: { + UPDATE_STATE: "updateState", + RECEIVED_STATE: "receivedState", + DISCONNECT: "disconnect", + }, +}; + export class DebuggerCommunicationServer { private port: number; private serverHttp: http.Server; @@ -13,7 +26,7 @@ export class DebuggerCommunicationServer { private simulatorWebview: WebviewPanel | undefined; private currentActiveDevice; private isWaitingResponse = false; - private currentCall: Array = [] + private currentCall: Array = []; constructor( webviewPanel: WebviewPanel | undefined, @@ -29,7 +42,7 @@ export class DebuggerCommunicationServer { this.initEventsHandlers(); console.info(`Server running on port ${this.port}`); - this.currentActiveDevice = currentActiveDevice + this.currentActiveDevice = currentActiveDevice; } public closeConnection(): void { @@ -42,18 +55,20 @@ export class DebuggerCommunicationServer { this.simulatorWebview = webviewPanel; } - public emitInputChanged(newState: string): void { if (this.isWaitingResponse) { - console.log('I have added a call to the queue') this.currentCall.push(() => { - console.log("I will send another input for sensor_changed") - this.serverIo.emit("input_changed", newState) + this.serverIo.emit( + DEBUGGER_MESSAGES.EMITTER.INPUT_CHANGED, + newState + ); this.isWaitingResponse = true; - }) - + }); } else { - this.serverIo.emit("input_changed", newState) + this.serverIo.emit( + DEBUGGER_MESSAGES.EMITTER.INPUT_CHANGED, + newState + ); this.isWaitingResponse = true; } } @@ -67,27 +82,23 @@ export class DebuggerCommunicationServer { private initEventsHandlers(): void { this.serverIo.on("connection", (socket: any) => { - console.log("Connection received"); - - socket.on("updateState", (data: any) => { + socket.on(DEBUGGER_MESSAGES.LISTENER.UPDATE_STATE, (data: any) => { this.handleState(data); - this.serverIo.emit("received_state", {}) + this.serverIo.emit( + DEBUGGER_MESSAGES.EMITTER.RECEIVED_STATE, + {} + ); }); - socket.on("receivedState", () => { + socket.on(DEBUGGER_MESSAGES.LISTENER.RECEIVED_STATE, () => { this.isWaitingResponse = false; if (this.currentCall.length > 0) { - let currentCall = this.currentCall.shift() - console.log("The previous state has been received by the python api") - currentCall() + let currentCall = this.currentCall.shift(); + currentCall(); } + }); - } - - ); - - socket.on("disconnect", () => { - this.serverIo.emit("frontend_disconnected", {}) - console.log("Socket disconnected"); + socket.on(DEBUGGER_MESSAGES.LISTENER.DISCONNECT, () => { + this.serverIo.emit(DEBUGGER_MESSAGES.EMITTER.DISCONNECT, {}); if (this.simulatorWebview) { this.simulatorWebview.webview.postMessage({ command: "reset-state", @@ -99,9 +110,7 @@ export class DebuggerCommunicationServer { private handleState(data: any): void { try { - console.log("handleState") const messageToWebview = JSON.parse(data); - console.log(messageToWebview) if (messageToWebview.type === "state") { console.log(`State recieved: ${messageToWebview.data}`); if (this.simulatorWebview) { From e951947cfb9d7c5516d0457f046401872fe73b4e Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Thu, 20 Feb 2020 16:15:14 -0800 Subject: [PATCH 19/22] remove temporary console logs --- src/extension.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index cc080cba4..62eb6e541 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -141,7 +141,6 @@ export async function activate(context: vscode.ExtensionContext) { } ); - currentPanel.webview.html = getWebviewContent(context); if (messageListener !== undefined) { @@ -452,7 +451,6 @@ export async function activate(context: vscode.ExtensionContext) { const runSimulatorCommand = async () => { // Prevent running new code if a debug session is active if (inDebugMode) { - console.log("debug mode not running simulator command") vscode.window.showErrorMessage( CONSTANTS.ERROR.DEBUGGING_SESSION_IN_PROGESS ); @@ -571,7 +569,6 @@ export async function activate(context: vscode.ExtensionContext) { childProcess.stdout.on("data", data => { dataFromTheProcess = data.toString(); if (currentPanel) { - console.log("receiving message") // Process the data from the process and send one state at a time dataFromTheProcess.split("\0").forEach(message => { if ( @@ -1034,7 +1031,7 @@ const updateCurrentFileIfPython = async ( if ( currentTextDocument && utils.getActiveEditorFromPath(currentTextDocument.fileName) === - undefined + undefined ) { await vscode.window.showTextDocument( currentTextDocument, From 470282df0205405c3be95b56e24e6a0ba2a065c3 Mon Sep 17 00:00:00 2001 From: andreamah Date: Mon, 24 Feb 2020 12:16:39 -0800 Subject: [PATCH 20/22] src/adafruit_circuitplayground --- .../test_debugger_communication_client.py | 133 ++++++++++++++++-- 1 file changed, 124 insertions(+), 9 deletions(-) diff --git a/src/common/test/test_debugger_communication_client.py b/src/common/test/test_debugger_communication_client.py index acc3b2c37..0706ad149 100644 --- a/src/common/test/test_debugger_communication_client.py +++ b/src/common/test/test_debugger_communication_client.py @@ -2,9 +2,12 @@ import json # Remove from unittest import mock import socketio +import threading from adafruit_circuitplayground import express -from .. import debugger_communication_client +from common import debugger_communication_client +from common import constants as CONSTANTS +from adafruit_circuitplayground.constants import CPX class TestDebuggerCommunicationClient(object): @@ -21,43 +24,155 @@ def test_init_connection1(self): socketio.Client.connect.assert_called_once() def test_update_state(self): + threading.Event.clear = mock.Mock() + threading.Event.wait = mock.Mock() socketio.Client.emit = mock.Mock() socketio.Client.emit.return_value = None - debugger_communication_client.update_state({}) + debugger_communication_client.update_state( + {CONSTANTS.ACTIVE_DEVICE_FIELD: CPX, CONSTANTS.STATE_FIELD: {}} + ) socketio.Client.emit.assert_called_once() @mock.patch.dict( express.cpx._Express__state, - {"button_a": False, "button_b": False, "switch": True}, + { + "brightness": 1.0, + "button_a": False, + "button_b": False, + "pixels": [ + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + ], + "red_led": False, + "switch": False, + "temperature": 0, + "light": 0, + "motion_x": 0, + "motion_y": 0, + "motion_z": 0, + "touch": [False] * 7, + "shake": False, + }, clear=True, ) def test_button_press(self): - data = {"button_a": True, "button_b": True, "switch": True} + data = { + CONSTANTS.ACTIVE_DEVICE_FIELD: CPX, + CONSTANTS.STATE_FIELD: {"button_a": True, "button_b": True, "switch": True}, + } + expected_data = { + "brightness": 1.0, + "button_a": True, + "button_b": True, + "pixels": [ + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + ], + "red_led": False, + "switch": True, + "temperature": 0, + "light": 0, + "motion_x": 0, + "motion_y": 0, + "motion_z": 0, + "touch": [False] * 7, + "shake": False, + } serialized_data = json.dumps(data) debugger_communication_client.input_changed(serialized_data) - assert data == express.cpx._Express__state + assert expected_data == express.cpx._Express__state @mock.patch.dict( express.cpx._Express__state, - {"temperature": 0, "light": 0, "motion_x": 0, "motion_y": 0, "motion_z": 0}, + { + "brightness": 1.0, + "button_a": False, + "button_b": False, + "pixels": [ + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + ], + "red_led": False, + "switch": False, + "temperature": 0, + "light": 0, + "motion_x": 0, + "motion_y": 0, + "motion_z": 0, + "touch": [False] * 7, + "shake": False, + }, clear=True, ) - def test_sensor_changed(self): + def test_input_changed(self): data = { + CONSTANTS.ACTIVE_DEVICE_FIELD: CPX, + CONSTANTS.STATE_FIELD: { + "temperature": 1, + "light": 2, + "motion_x": 3, + "motion_y": 4, + "motion_z": 5, + }, + } + expected_data = { + "brightness": 1.0, + "button_a": False, + "button_b": False, + "pixels": [ + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + (0, 0, 0), + ], + "red_led": False, + "switch": False, "temperature": 1, "light": 2, "motion_x": 3, "motion_y": 4, "motion_z": 5, + "touch": [False] * 7, + "shake": False, } serialized_data = json.dumps(data) debugger_communication_client.input_changed(serialized_data) - assert data == express.cpx._Express__state + assert expected_data == express.cpx._Express__state @mock.patch("builtins.print") @mock.patch.dict(express.cpx._Express__state, {}, clear=True) def test_update_api_state_fail(self, mocked_print): data = [] - debugger_communication_client.sensor_changed(data) + debugger_communication_client.input_changed(data) # Exception is caught and a print is stated to stderr mocked_print.assert_called_once() From e029bee03e919281c565e457dc0a3376315c9fcd Mon Sep 17 00:00:00 2001 From: andreamah Date: Mon, 24 Feb 2020 12:35:15 -0800 Subject: [PATCH 21/22] removed bad call from debug user code --- src/debug_user_code.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/debug_user_code.py b/src/debug_user_code.py index 0e356880b..2ea654ac0 100644 --- a/src/debug_user_code.py +++ b/src/debug_user_code.py @@ -63,5 +63,3 @@ for frameIndex in range(2, len(stackTrace) - 1): errorMessage += "\t" + str(stackTrace[frameIndex]) print(e, errorMessage, file=sys.stderr, flush=True) - - debugger_communication_client.disconnect_socket() From 997cf2a64a5fce0dbd29d0a6385c77b9aec245e1 Mon Sep 17 00:00:00 2001 From: xnkevinnguyen Date: Mon, 24 Feb 2020 15:03:37 -0800 Subject: [PATCH 22/22] Update with feedback --- src/debuggerCommunicationServer.ts | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/debuggerCommunicationServer.ts b/src/debuggerCommunicationServer.ts index 307f475ae..1d73b8c29 100644 --- a/src/debuggerCommunicationServer.ts +++ b/src/debuggerCommunicationServer.ts @@ -25,8 +25,8 @@ export class DebuggerCommunicationServer { private serverIo: socketio.Server; private simulatorWebview: WebviewPanel | undefined; private currentActiveDevice; - private isWaitingResponse = false; - private currentCall: Array = []; + private isPendingResponse = false; + private pendingCallbacks: Array = []; constructor( webviewPanel: WebviewPanel | undefined, @@ -54,22 +54,21 @@ export class DebuggerCommunicationServer { public setWebview(webviewPanel: WebviewPanel | undefined) { this.simulatorWebview = webviewPanel; } - + // Events are pushed when the previous processed event is over public emitInputChanged(newState: string): void { - if (this.isWaitingResponse) { - this.currentCall.push(() => { + if (this.isPendingResponse) { + this.pendingCallbacks.push(() => { this.serverIo.emit( DEBUGGER_MESSAGES.EMITTER.INPUT_CHANGED, newState ); - this.isWaitingResponse = true; }); } else { this.serverIo.emit( DEBUGGER_MESSAGES.EMITTER.INPUT_CHANGED, newState ); - this.isWaitingResponse = true; + this.isPendingResponse = true; } } @@ -90,10 +89,12 @@ export class DebuggerCommunicationServer { ); }); socket.on(DEBUGGER_MESSAGES.LISTENER.RECEIVED_STATE, () => { - this.isWaitingResponse = false; - if (this.currentCall.length > 0) { - let currentCall = this.currentCall.shift(); + if (this.pendingCallbacks.length > 0) { + const currentCall = this.pendingCallbacks.shift(); currentCall(); + this.isPendingResponse = true; + } else { + this.isPendingResponse = false; } });