Skip to content

Commit

Permalink
feat: event is a worker now
Browse files Browse the repository at this point in the history
  • Loading branch information
owulveryck committed Nov 16, 2023
1 parent 038b14d commit 021ccdd
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 80 deletions.
45 changes: 42 additions & 3 deletions client/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@ const canvasPresent = document.getElementById("canvasPresent");
const iFrame = document.getElementById("content");

// Initialize the worker
const worker = new Worker('worker_stream_processing.js');
const streamWorker = new Worker('worker_stream_processing.js');
const eventWorker = new Worker('worker_event_processing.js');

// Send the OffscreenCanvas to the worker for initialization
worker.postMessage({
streamWorker.postMessage({
type: 'init',
width: width,
height: height
});

// Listen for updates from the worker
worker.onmessage = (event) => {
streamWorker.onmessage = (event) => {
const data = event.data;

switch (data.type) {
Expand All @@ -44,6 +45,44 @@ worker.onmessage = (event) => {
}
};


// Determine the WebSocket protocol based on the current window protocol
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsURL = `${wsProtocol}//${window.location.host}/events`;
// Send the OffscreenCanvas to the worker for initialization
eventWorker.postMessage({
type: 'init',
width: width,
height: height,
rotate: true,
wsURL: wsURL
});

// Listen for updates from the worker
eventWorker.onmessage = (event) => {
const data = event.data;

switch (data.type) {
case 'clear':
clearLaser();
break;
case 'update':
// Handle the update
const X = event.data.X;
const Y = event.data.Y;
drawLaser(X,Y);

break;
case 'error':
console.error('Error from worker:', event.data.message);
waiting(event.data.message)
// Handle the error, maybe show a user-friendly message or take some corrective action
break;
// ... handle other message types as needed
}
};


window.onload = function() {
// Function to get the value of a query parameter by name
function getQueryParam(name) {
Expand Down
70 changes: 0 additions & 70 deletions client/pointer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,73 +22,3 @@ function clearLaser() {
ctxCanvasPresent.clearRect(0, 0, canvasPresent.width, canvasPresent.height); // Clear the canvasPresent
}

// Function to establish a WebSocket connection
function connectWebSocket() {
// Determine the WebSocket protocol based on the current window protocol
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsURL = `${wsProtocol}//${window.location.host}/events`;
let draw = true;

ws = new WebSocket(wsURL);

ws.onmessage = (event) => {
const message = JSON.parse(event.data);
//if (message.Type === 0) {
// Code 0: Clear the laser pointer
// clearLaser();
//} else if (message.Type === 3) {
if (message.Type === 3) {
if (message.Code === 24) {
draw = false;
clearLaser();
} else if (message.Code === 25) {
draw = true;

}
}
if (message.Type === 3) {
// Code 3: Update and draw laser pointer
if (rotate) {
if (message.Code === 1) { // Horizontal position
latestX = scaleValue(message.Value, MAX_X_VALUE, canvasPresent.width);
} else if (message.Code === 0) { // Vertical position
latestY = canvasPresent.height - scaleValue(message.Value, MAX_Y_VALUE, canvasPresent.height);
}
} else {
if (message.Code === 1) { // Horizontal position
latestX = canvasPresent.width - scaleValue(message.Value, MAX_X_VALUE, canvasPresent.width);
} else if (message.Code === 0) { // Vertical position
latestY = scaleValue(message.Value, MAX_Y_VALUE, canvasPresent.height);
}
}
if (draw) {
drawLaser(latestX, latestY);
}
}
};

ws.onerror = () => {
console.error('WebSocket error occurred. Attempting to reconnect...');
//setTimeout(connectWebSocket, 3000); // Reconnect after 3 seconds
};

ws.onclose = () => {
console.log('WebSocket connection closed. Attempting to reconnect...');
//setTimeout(connectWebSocket, 3000); // Reconnect after 3 seconds
};
}
// Function to scale the incoming value to the canvas size
function scaleValue(value, maxValue, canvasSize) {
return (value / maxValue) * canvasSize;
}
function stopWebSocket() {
if (ws) {
ws.close();
}
clearLaser();
}

function isWebSocketConnected(ws) {
return ws && ws.readyState === WebSocket.OPEN;
}
connectWebSocket();
88 changes: 88 additions & 0 deletions client/worker_event_processing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
let height;
let width;
let wsURL;
let rotate;
let draw;
let latestX;
let latestY;
// Constants for the maximum values from the WebSocket messages
const MAX_X_VALUE = 15725;
const MAX_Y_VALUE = 20966;

onmessage = (event) => {
const data = event.data;

switch (data.type) {
case 'init':
height = event.data.height;
width = event.data.width;
wsURL = event.data.wsURL;
rotate = event.data.rotate;
initiateEventsListener();
break;
}
};


async function initiateEventsListener() {
const RETRY_DELAY_MS = 3000; // Delay before retrying the connection (in milliseconds)
ws = new WebSocket(wsURL);
draw = true;
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.Type === 3) {
if (message.Code === 24) {
draw = false;
postMessage({ type: 'clear' });
// clearLaser();
} else if (message.Code === 25) {
draw = true;

}
}
if (message.Type === 3) {
// Code 3: Update and draw laser pointer
if (rotate) {
if (message.Code === 1) { // Horizontal position
latestX = scaleValue(message.Value, MAX_X_VALUE, width);
} else if (message.Code === 0) { // Vertical position
latestY = height - scaleValue(message.Value, MAX_Y_VALUE, height);
}
} else {
if (message.Code === 1) { // Horizontal position
latestX = width - scaleValue(message.Value, MAX_X_VALUE, width);
} else if (message.Code === 0) { // Vertical position
latestY = scaleValue(message.Value, MAX_Y_VALUE, height);
}
}
if (draw) {
postMessage({ type: 'update', X: latestX, Y: latestY });
//drawLaser(latestX, latestY);
}
}
}

ws.onerror = () => {
postMessage({
type: 'error',
message: error.message
});
console.error('WebSocket error occurred. Attempting to reconnect...');
//setTimeout(connectWebSocket, 3000); // Reconnect after 3 seconds
};

ws.onclose = () => {
postMessage({
type: 'error',
message: error.message
});
console.log('WebSocket connection closed. Attempting to reconnect...');
//setTimeout(connectWebSocket, 3000); // Reconnect after 3 seconds
};
}

// Function to scale the incoming value to the canvas size
function scaleValue(value, maxValue, canvasSize) {
return (value / maxValue) * canvasSize;
}

31 changes: 31 additions & 0 deletions gzip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"compress/gzip"
"io"
"net/http"
"strings"
)

type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}

func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}

func gzMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz, _ := gzip.NewWriterLevel(w, 1)
defer gz.Close()
gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
next.ServeHTTP(gzr, r)
})
}
7 changes: 6 additions & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ func setMuxer(eventPublisher *pubsub.PubSub) *http.ServeMux {
})

streamHandler := stream.NewStreamHandler(file, pointerAddr, eventPublisher)
mux.Handle("/stream", streamHandler)
if c.Compression {
mux.Handle("/stream", gzMiddleware(streamHandler))
} else {
mux.Handle("/stream", streamHandler)
}

wsHandler := eventhttphandler.NewEventHandler(eventPublisher)
mux.Handle("/events", wsHandler)

Expand Down
14 changes: 8 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import (
)

type configuration struct {
BindAddr string `envconfig:"SERVER_BIND_ADDR" default:":2001" required:"true" description:"The server bind address"`
Username string `envconfig:"SERVER_USERNAME" default:"admin"`
Password string `envconfig:"SERVER_PASSWORD" default:"password"`
TLS bool `envconfig:"HTTPS" default:"true"`
DevMode bool `envconfig:"DEV_MODE" default:"false"`
BindAddr string `envconfig:"SERVER_BIND_ADDR" default:":2001" required:"true" description:"The server bind address"`
Username string `envconfig:"SERVER_USERNAME" default:"admin"`
Password string `envconfig:"SERVER_PASSWORD" default:"password"`
TLS bool `envconfig:"HTTPS" default:"true"`
Compression bool `envconfig:"COMPRESSION" default:"false"`
DevMode bool `envconfig:"DEV_MODE" default:"false"`
}

const (
Expand Down Expand Up @@ -68,7 +69,8 @@ func main() {
mux := setMuxer(eventPublisher)

// handler := BasicAuthMiddleware(gzMiddleware(mux))
handler := BasicAuthMiddleware(mux)
var handler http.Handler
handler = BasicAuthMiddleware(mux)
if *unsafe {
handler = mux
}
Expand Down

0 comments on commit 021ccdd

Please sign in to comment.