This commit is contained in:
Your Name
2024-02-15 23:36:30 -06:00
parent a5adf74b23
commit 8c60f0956b
7 changed files with 117 additions and 8 deletions

0
logs/blank Normal file
View File

View File

@@ -2,7 +2,7 @@
# Check if nodejs is installed # Check if nodejs is installed
if ! which nodejs > /dev/null; then if ! which nodejs > /dev/null; then
#sudo mount -o remount,rw /
# Node.js is not installed, setting up the NodeSource Node.js 21.x repo # Node.js is not installed, setting up the NodeSource Node.js 21.x repo
echo "Node.js not found. Setting up NodeSource Node.js 21.x repository..." echo "Node.js not found. Setting up NodeSource Node.js 21.x repository..."
@@ -10,5 +10,5 @@ if ! which nodejs > /dev/null; then
# Install Node.js from the NodeSource repository # Install Node.js from the NodeSource repository
echo "Installing Node.js..." echo "Installing Node.js..."
sudo apt-get install -y nodejs npm sudo apt-get install -y nodejs
fi fi

View File

@@ -1,3 +1,4 @@
bash /data/openpilot/shell/configure_ssh.sh bash /data/openpilot/shell/configure_ssh.sh
bash /data/openpilot/shell/set_logo.sh bash /data/openpilot/shell/set_logo.sh
screen -dmS "watcher" "bash /data/openpilot/shell/watcher_run_loop.sh"

32
shell/watcher.example.py Normal file
View File

@@ -0,0 +1,32 @@
import socket
import json
# Initialize the socket without connecting
sock = None
def ensure_socket_connected():
global sock
if sock is None or sock.fileno() == -1: # Checks if socket is not initialized or closed
try:
# Attempt to initialize and connect the socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect("/tmp/oscar_watcher.sock")
except socket.error:
# If connection fails, set sock to None and do nothing
sock = None
def log_watch(var_name, message):
ensure_socket_connected() # Ensure the socket is connected before attempting to log
if sock: # Proceed only if sock is not None (i.e., is connected)
message_json = json.dumps(message)
try:
sock.sendall(message_json.encode('utf-8') + b'\n')
except socket.error:
# Handle potential error in sending (e.g., if connection was lost)
global sock
sock.close() # Close the current socket to clean up resources
sock = None # Reset sock to ensure reconnection attempt on next call
#message = {"variable": "car_stats", "value": {"car_lights_on": [3, 5, 7], "car_state": "on"}}
#log_watch(sock, message)

29
shell/watcher.html Normal file
View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Replace 'ws://localhost/ws' with your WebSocket server address
var ws = new WebSocket('ws://localhost/ws');
ws.onopen = function() {
console.log('WebSocket connection established');
};
ws.onmessage = function(event) {
console.log('Message received: ' + event.data);
};
ws.onclose = function() {
console.log('WebSocket connection closed');
};
});
</script>
</head>
<body>
<h1>WebSocket Test Page</h1>
</body>
</html>

View File

@@ -1,6 +1,8 @@
const net = require('net'); const net = require('net');
const fs = require('fs'); const fs = require('fs');
const socketPath = '/tmp/node-server.sock'; const socketPath = '/tmp/oscar_watcher.sock';
//// UNIXSOCKET SERVER ////
let progvars = {}; let progvars = {};
@@ -15,7 +17,7 @@ try {
} }
const unix_socket_server = net.createServer((connection) => { const unix_socket_server = net.createServer((connection) => {
console.log('Client connected.'); console.log('UnixSocket Client connected.');
let buffer = ''; let buffer = '';
@@ -31,12 +33,12 @@ const unix_socket_server = net.createServer((connection) => {
}); });
connection.on('end', () => { connection.on('end', () => {
console.log('Client disconnected.'); console.log('UnixSocket Client disconnected.');
}); });
}); });
unix_socket_server.listen(socketPath, () => { unix_socket_server.listen(socketPath, () => {
console.log(`Server listening on ${socketPath}`); console.log(`UnixSocket Server listening on ${socketPath}`);
}); });
function processMessage(message) { function processMessage(message) {
@@ -49,7 +51,7 @@ function processMessage(message) {
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
const logEntry = `log_time="${timestamp}";\n${diff}\n`; const logEntry = `log_time="${timestamp}";\n${diff}\n`;
fs.writeFile('variable_changes.log', logEntry, { flag: 'a' }, (err) => { fs.writeFile('/data/openpilot/logs/watcher.log', logEntry, { flag: 'a' }, (err) => {
if (err) { if (err) {
console.error('Error writing to log file:', err); console.error('Error writing to log file:', err);
} }
@@ -103,6 +105,8 @@ function calculateDiff(oldValue, newValue) {
return changes.join('\n'); return changes.join('\n');
} }
//// WEBSOCKET SERVER ////
const WebSocket = require('ws'); const WebSocket = require('ws');
const http = require('http'); const http = require('http');
const url = require('url'); const url = require('url');
@@ -156,5 +160,37 @@ function send_ws_message(message) {
// Start the HTTP server // Start the HTTP server
const PORT = 3001; // Ensure this port is different from the UNIX socket server if running on the same machine const PORT = 3001; // Ensure this port is different from the UNIX socket server if running on the same machine
websocket_server.listen(PORT, () => { websocket_server.listen(PORT, () => {
console.log(`WebSocket server is running on port ${PORT}`); console.log(`WebSocket listening on port ${PORT}`);
});
//// HTTP SERVER ////
const http = require('http');
const fs = require('fs');
const path = require('path');
const hostname = '0.0.0.0';
const port = 1024;
const server = http.createServer((req, res) => {
if(req.url === '/') {
// Serve the HTML file
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if(err) {
res.writeHead(500);
res.end('Error loading index.html');
return;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
} else {
// Handle 404
res.writeHead(404);
res.end('Not found');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
}); });

11
shell/watcher_run_loop.sh Normal file
View File

@@ -0,0 +1,11 @@
cd /data/openpilot/shell
while true
do
nodejs watcher.js
echo crashed, waiting 30 seconds
sleep 30
done