Parcourir la source

Added ws auto conn

TC il y a 6 jours
Parent
commit
c1b0aaa81c
4 fichiers modifiés avec 160 ajouts et 66 suppressions
  1. 4 3
      remdeskd/main.go
  2. 38 0
      remdeskd/mod/remdeshid/hidcomm.go
  3. 8 0
      remdeskd/mod/remdeshid/hidconv.go
  4. 110 63
      remdeskd/www/index.html

+ 4 - 3
remdeskd/main.go

@@ -41,6 +41,10 @@ func init() {
 		}
 		webfs = http.FS(subFS)
 	}
+}
+
+func main() {
+	flag.Parse()
 
 	// Initiate the HID controller
 	usbKVM = remdeshid.NewHIDController(&remdeshid.Config{
@@ -48,9 +52,6 @@ func init() {
 		BaudRate: *usbKVMBaudRate,
 	})
 
-}
-
-func main() {
 	//Start the HID controller
 	err := usbKVM.Connect()
 	if err != nil {

+ 38 - 0
remdeskd/mod/remdeshid/hidcomm.go

@@ -8,6 +8,7 @@ package remdeshid
 
 */
 import (
+	"errors"
 	"fmt"
 )
 
@@ -193,6 +194,40 @@ func appendMouseScrollEventSubtypes(data []byte, cmd HIDCommand) ([]byte, error)
 	return data, nil
 }
 
+// Append the switch subtypes to the data
+func appendSwitchOperationsEventSubtypes(data []byte, cmd HIDCommand) ([]byte, error) {
+	if cmd.EventSubType == "hid" {
+		data = append(data, SUBTYPE_SWITCH_USB_HID)
+		if cmd.Data == "connect" {
+			//Set switch state to 0x00
+			data = append(data, 0x00)
+			return data, nil
+		} else if cmd.Data == "disconnect" {
+			//Set switch state to 0x01
+			data = append(data, 0x01)
+			return data, nil
+		} else if cmd.Data == "reset" {
+			data = append(data, 0x02)
+			return data, nil
+		}
+		return []byte{}, errors.New("unknown value: only support 'connect' and 'disconnect'")
+	} else if cmd.EventSubType == "mass-storage" {
+		data = append(data, SUBTYPE_SWITCH_USB_MASS)
+		if cmd.Data == "host" {
+			//Set switch state to 0x00
+			data = append(data, 0x00)
+			return data, nil
+		} else if cmd.Data == "slave" {
+			//Set switch state to 0x01
+			data = append(data, 0x01)
+			return data, nil
+		}
+		return []byte{}, errors.New("unknown value: only support 'host' and 'slave'")
+	}
+	//Unknown operatuins
+	return []byte{}, errors.New("unknown switch subtypes")
+}
+
 // Entry function for converting a HIDCommand to bytes that can be sent over the USBKVM device
 func ConvHIDCommandToBytes(cmd HIDCommand) ([]byte, error) {
 	// Convert the HID command to bytes
@@ -213,6 +248,9 @@ func ConvHIDCommandToBytes(cmd HIDCommand) ([]byte, error) {
 		/* Mouse Scroll Event */
 		data = []byte{OPR_TYPE_MOUSE_SCROLL}
 		return appendMouseScrollEventSubtypes(data, cmd)
+	} else if cmd.EventType == FRONTEND_OPR_TYPE_SWITCH {
+		data = []byte{OPR_TYPE_SWITCH_SET}
+		return appendSwitchOperationsEventSubtypes(data, cmd)
 	} else if cmd.EventType == FRONT_END_OPR_RESET {
 		/* Reset Event */
 		data = []byte{OPR_TYPE_DATA_RESET, //Reset the data queue

+ 8 - 0
remdeskd/mod/remdeshid/hidconv.go

@@ -14,6 +14,7 @@ const (
 	FRONTEND_OPR_TYPE_MOUSE_WRITE    = "mw"
 	FRONTEND_OPR_TYPE_MOUSE_MOVE     = "mm"
 	FRONTEND_OPR_TYPE_MOUSE_SCROLL   = "ms"
+	FRONTEND_OPR_TYPE_SWITCH         = "sw"
 
 	// USBKVM Operation Types
 	OPR_TYPE_RESERVED       = 0x00
@@ -21,6 +22,7 @@ const (
 	OPR_TYPE_MOUSE_WRITE    = 0x02
 	OPR_TYPE_MOUSE_MOVE     = 0x03
 	OPR_TYPE_MOUSE_SCROLL   = 0x04
+	OPR_TYPE_SWITCH_SET     = 0x05
 	OPR_TYPE_DATA_RESET     = 0xFF
 )
 
@@ -109,6 +111,12 @@ const (
 	PAYLOAD_MOUSE_BTN_MID   = 0x03
 )
 
+// Switch Subtypes
+const (
+	SUBTYPE_SWITCH_USB_HID  = 0x01
+	SUBTYPE_SWITCH_USB_MASS = 0x02
+)
+
 // Control Code
 const (
 	FRONT_END_OPR_RESET = "reset" // Reset all the mouse and keyboard states

+ 110 - 63
remdeskd/www/index.html

@@ -13,6 +13,7 @@
     <meta property="og:type" content="website">
     <meta property="og:url" content="http://example.com">
     <meta property="og:image" content="http://example.com/image.jpg">
+    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
     <style>
         body{
             margin: 0;
@@ -22,25 +23,40 @@
             pointer-events: none;
             user-select: none;
         }
+
+        #remoteCaptureWrapper{
+            box-shadow: none !important;
+            border: 0px solid transparent !important;
+            background: none !important;
+        }
     </style>
 </head>
 <body>
-    <img id="remoteCapture" src="/stream"></img>
+    <button id="remoteCaptureWrapper" onclick="startCapture();">
+        <img id="remoteCapture" src="/stream"></img>
+    </button>
     <p>Click start to start connection to backend and start Capture to start KVM-ing</p>
-    <button id="startButton">Start</button>
-    <button id="stopButton">Stop</button>
+    <!-- <button id="startButton">Start</button>
+    <button id="stopButton">Stop</button> -->
     <button id="capture">Capture</button>
     <button id="screenshot">Win + Shift + S</button>
+    <button id="reconnect">Reset HID</button>
     <script>
         let socket;
         let protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
         let port = window.location.port ? window.location.port : (protocol === 'wss' ? 443 : 80);
         let socketURL = `${protocol}://${window.location.hostname}:${port}/hid`;
         
-        /* Mouse */
-        document.getElementById('capture').addEventListener('click', function(event) {
-            event.preventDefault();
-            event.stopPropagation();
+        function isPointerLocked() {
+            return document.pointerLockElement === document.body;
+        }
+
+        function startCapture(){
+            if (!socket) {
+                alert("control websocket is not opened");
+                return;
+            }
+            console.log("Start capture called");
 
             // Remove old listeners if they exist
             document.removeEventListener('mousemove', handleMouseMove);
@@ -55,29 +71,39 @@
             document.addEventListener('mouseup', handleMouseUp);
             document.addEventListener('wheel', handleScroll);
 
-            if (socket) {
-                // Reset USBKVM state to avoid stuck keys
-                socket.send(JSON.stringify({ t: 'reset'}));
-            }
+            // Reset USBKVM state to avoid stuck keys
+            socket.send(JSON.stringify({ t: 'reset'}));
+        }
+
+        document.getElementById('capture').addEventListener('click', function(event) {
+            event.preventDefault();
+            event.stopPropagation();
+            startCapture();
+        });
+
+        $("#remoteCapture").on("click", function(){
+            startCapture();
         });
 
+
+        /* Mouse */
         function handleMouseDown(event) {
             console.log(`Mouse button pressed: Button=${event.button}`);
-            if (socket) {
+            if (socket && isPointerLocked()) {
                 socket.send(JSON.stringify({ t: 'mw', s: 'md', d: event.button+"" }));
             }
         }
 
         function handleMouseUp(event) {
             console.log(`Mouse button released: Button=${event.button}`);
-            if (socket) {
+            if (socket && isPointerLocked()) {
                 socket.send(JSON.stringify({ t: 'mw', s: 'mu', d: event.button+"" }));
             }
         }
 
         function handleScroll(event) {
             console.log(`Mouse scrolled: DeltaX=${event.deltaX}, DeltaY=${event.deltaY}`);
-            if (socket) {
+            if (socket && isPointerLocked()) {
                 socket.send(JSON.stringify({ t: 'ms', y: event.deltaY }));
             }
         }
@@ -93,58 +119,12 @@
 
         function handleMouseMove(event) {
             console.log(`Mouse moved: X=${event.movementX}, Y=${event.movementY}`);
-            if (socket) {
+            if (socket && isPointerLocked()) {
                 socket.send(JSON.stringify({ t: 'mm', x: event.movementX, y: event.movementY }));
             }
         }
         
         /* Keyboard */
-        document.getElementById('startButton').addEventListener('click', function() {
-            const socketUrl = socketURL;
-            socket = new WebSocket(socketUrl);
-
-            socket.addEventListener('open', function(event) {
-                console.log('WebSocket is connected.');
-            });
-
-            socket.addEventListener('message', function(event) {
-                console.log('Message from server ', event.data);
-            });
-
-            document.addEventListener('keydown', handleKeyDown);
-            document.addEventListener('keyup', handleKeyUp);
-        });
-
-        document.getElementById('stopButton').addEventListener('click', function() {
-            if (socket) {
-                socket.close();
-                console.log('WebSocket is disconnected.');
-            }
-
-            document.removeEventListener('keydown', handleKeyDown);
-            document.removeEventListener('keyup', handleKeyUp);
-        });
-
-        document.getElementById('screenshot').addEventListener('click', function() {
-            if (socket) {
-                // Send keydown for Shift
-                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 'LEFT_Shift' }));
-                // Send keydown for Windows key
-                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 'Meta' }));
-                // Send keydown for S
-                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 's' }));
-                
-                setTimeout(function() {
-                    // Send keyup for S
-                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 's' }));
-                    // Send keyup for Windows key
-                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 'Meta' }));
-                    // Send keyup for Shift
-                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 'LEFT_Shift' }));
-                }, 1000);
-            }
-        });
-
         function isNumpadEvent(event) {
             return event.location === 3;
         }
@@ -153,7 +133,7 @@
             event.preventDefault();
             event.stopImmediatePropagation();
             const key = event.key;
-            if (socket){
+            if (socket && isPointerLocked()){
                 if (key == "Shift" || key == "Control" || key == "Alt"){
                     if (event.location == 1){
                         socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: "LEFT_" + key }));
@@ -174,7 +154,7 @@
             event.preventDefault();
             event.stopImmediatePropagation();
             const key = event.key;
-            if (socket) {
+            if (socket && isPointerLocked()) {
                 if (key == "Shift" || key == "Control" || key == "Alt") {
                     if (event.location == 1) {
                         socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: "LEFT_" + key }));
@@ -191,7 +171,74 @@
             }
         }
 
+        /* Start and Stop events */
+        function startWebSocket(){
+            if (socket){
+                //Already started
+                alert("Websocket already started");
+                return;
+            }
+            const socketUrl = socketURL;
+            socket = new WebSocket(socketUrl);
+
+            socket.addEventListener('open', function(event) {
+                console.log('WebSocket is connected.');
+            });
+
+            socket.addEventListener('message', function(event) {
+                console.log('Message from server ', event.data);
+            });
+
+            document.addEventListener('keydown', handleKeyDown);
+            document.addEventListener('keyup', handleKeyUp);
+        }
+
+        function stopWebSocket(){
+            if (!socket){
+                alert("No ws connection to stop");
+                return;
+            }
+
+            socket.close();
+            console.log('WebSocket is disconnected.');
+            document.removeEventListener('keydown', handleKeyDown);
+            document.removeEventListener('keyup', handleKeyUp);
+        }
+
+        document.getElementById('screenshot').addEventListener('click', function() {
+            if (socket) {
+                // Send keydown for Shift
+                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 'LEFT_Shift' }));
+                // Send keydown for Windows key
+                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 'Meta' }));
+                // Send keydown for S
+                socket.send(JSON.stringify({ t: 'kw', s: 'kd', d: 's' }));
+                
+                setTimeout(function() {
+                    // Send keyup for S
+                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 's' }));
+                    // Send keyup for Windows key
+                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 'Meta' }));
+                    // Send keyup for Shift
+                    socket.send(JSON.stringify({ t: 'kw', s: 'ku', d: 'LEFT_Shift' }));
+                }, 1000);
+            }
+        });
+
+        /* Reconnect USB HID to slave device */
+        $("#reconnect").on("click", function(){
+            if (socket) {   
+                socket.send(JSON.stringify({ t: 'sw', s: 'hid', d: "reset"}));
+            }else{
+                alert("Websocket conn not established");
+            }
+        });
+
         
+
+        $(document).ready(function(){
+            startWebSocket();
+        });
     </script>
 </body>
 </html>