Skip to content
Snippets Groups Projects
Commit b1b90530 authored by Kayson Ijisesan's avatar Kayson Ijisesan
Browse files

Add project files

parent 3b1f87ac
No related branches found
No related tags found
No related merge requests found
node_modules/
import bluetooth
import json
target_name = "raspberrypi"
sock = None
# TODO: Implement server for p2p comms
def start_client():
target_address = None
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
print(bluetooth.lookup_name( bdaddr ))
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print ("found target bluetooth device with address ", target_address)
else:
print ("could not find target bluetooth device nearby")
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((target_address, port))
def set_target(target):
target_name = target
def send_data(data):
sock.send(json.dumps(data))
def terminate():
sock.close()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.container { display: flex; }
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="./index.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pi Car Control</h2>
<img src="./media/default_background.png" id="pics">
</div>
</div>
<div class="row">
<div class="container">
<div class="jumbotron text-center col-md-6">
<!-- Arrow keys -->
<span id="upArrow" style='font-size:50px; color:grey;'>&#8679;</span>
<br>
<span id="leftArrow" style='font-size:45px; color:grey;'>&#8678;</span>
<span id="rightArrow" style='font-size:45px; color:grey;'>&#8680;</span>
<br>
<span id="downArrow" style='font-size:50px; color:grey;'>&#8681;</span>
<br>
<button id="stopbutt" class="btn btn-danger" style="margin-top: 10px;">Stop</button>
</div>
<div class="jumbotron text-left col-md-6">
<input id="message" type="text" placeholder="Message to Pi">
<button class="btn btn-success" onclick="send_data(document.getElementById('message').value)">Submit</button>
<p>
<span id="direction_dot" style="color:Green">&bull;</span> Car Direction: <span id="direction">Stopped</span>
<br>
<span id="distance_dot" style="color:green">&bull;</span> Ultrasonic Distance: <span id="distance">0.0</span>
<br>
</p>
<button id="getDistance" class="btn btn-info" style="margin-top: 10px;" onclick="send_data('distance')">Get Distance</button>
</div>
</div>
</div>
</body>
</html>
index.js 0 → 100644
document.onkeydown = updateKey;
document.onkeyup = resetKey;
var server_port = 65432;
var server_addr = "10.0.0.65"; // the IP address of your Raspberry PI
// Send data to the Raspberry Pi
function send_data(command) {
const net = require('net');
const client = net.createConnection({ port: server_port, host: server_addr }, () => {
console.log('Connected to server');
client.write(command + "\r\n");
});
client.on('data', (data) => {
let response = data.toString().trim();
console.log("Server Response:", response);
if (response.startsWith("Distance")) {
document.getElementById("distance").innerHTML = response.split(": ")[1]; // Display the distance
} else if (response.startsWith("Direction")) {
document.getElementById("direction").innerHTML = response.split(": ")[1]; // Display the direction
}
});
client.on('end', () => {
console.log('Disconnected from server');
});
}
// Update key color and send data on key press (w, a, s, d)
function updateKey(e) {
e = e || window.event;
if (e.keyCode == '38') { // up (w)
document.getElementById("upArrow").style.color = "green";
send_data("forward");
}
else if (e.keyCode == '40') { // down (s)
document.getElementById("downArrow").style.color = "green";
send_data("backward");
}
else if (e.keyCode == '37') { // left (a)
document.getElementById("leftArrow").style.color = "green";
send_data("left");
}
else if (e.keyCode == '39') { // right (d)
document.getElementById("rightArrow").style.color = "green";
send_data("right");
}
else if (e.keyCode == '32') { // stop
document.getElementById("stopbutt").style.color = "green";
send_data("stop");
}
else if (e.keyCode == '13') { // distance
document.getElementById("distancebutt").style.color = "green";
send_data("distance");
}
}
// Reset arrow colors when key is released
function resetKey(e) {
e = e || window.event;
document.getElementById("upArrow").style.color = "grey";
document.getElementById("downArrow").style.color = "grey";
document.getElementById("leftArrow").style.color = "grey";
document.getElementById("rightArrow").style.color = "grey";
document.getElementById("stopbutt").style.color = "black";
document.getElementById("distancebutt").style.color = "black";
}
// Clickable arrows
function setupClickableArrows() {
document.getElementById("upArrow").onclick = function() {
document.getElementById("upArrow").style.color = "green";
send_data("forward"); // forward
};
document.getElementById("downArrow").onclick = function() {
document.getElementById("downArrow").style.color = "green";
send_data("backward"); //backward
};
document.getElementById("leftArrow").onclick = function() {
document.getElementById("leftArrow").style.color = "green";
send_data("left"); // left
};
document.getElementById("rightArrow").onclick = function() {
document.getElementById("rightArrow").style.color = "green";
send_data("right"); s// right
};
document.getElementById("stopbutt").onclick = function() {
document.getElementById("stopbutt").style.color = "green";
send_data("stop"); // stop
};
}
/* // Request ultrasonic data periodically
setInterval(function() {
send_data("distance");
}, 1000);
*/
// Initialize clickable arrows when the page loads
window.onload = function() {
setupClickableArrows();
};
main.js 0 → 100644
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1000,
height: 1000,
webPreferences: {
nodeIntegration: true,
contextIsolation:false, // Add this
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
// if (process.platform !== 'darwin') app.quit()
app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
File added
media/default_background.png

218 KiB

File added
This diff is collapsed.
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^35.0.1"
}
}
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
import socket
import sys
import threading
import time
# Add Freenove libraries
sys.path.append('/home/pi/Freenove_4WD_Smart_Car_Kit_for_Raspberry_Pi/Code/Server')
from motor import Ordinary_Car
from ultrasonic import Ultrasonic
# Initialize motor and ultrasonic modules
car = Ordinary_Car()
ultrasonic = Ultrasonic()
# Server configuration
HOST = "10.0.0.65"
PORT = 65432 # port number
clients = [] # List clients
current_direction = "Stopped"
def handle_client(client_socket):
"""Handles communication with client."""
global current_direction
try:
while True:
# Receive data
data = client_socket.recv(1024).decode().strip()
print(f"Raw data received: {repr(data)}") # Debugging
if not data:
break
if data in ['forward', 'backward', 'left', 'right', 'stop', 'distance', 'exit']:
print(f"Received command: {data}")
power_val = 1000 # Initial motor value
# Process commands
if data == 'forward' or data == 'backward' or data == 'left' or data == 'right':
if data == 'forward':
car.set_motor_model(power_val, power_val, power_val, power_val)
current_direction = "Moving Forward"
elif data == 'backward':
car.set_motor_model(-power_val, -power_val, -power_val, -power_val)
current_direction = "Moving Backward"
elif data == 'left':
car.set_motor_model(-power_val, -power_val, power_val, power_val)
current_direction = "Turning Left"
elif data == 'right':
car.set_motor_model(power_val, power_val, -power_val, -power_val)
current_direction = "Turning Right"
# Send direction update to client
client_socket.sendall(f"Direction: {current_direction}\n".encode())
elif data == 'stop':
car.set_motor_model(0, 0, 0, 0)
current_direction = "Stopped"
# Send direction update to the client
client_socket.sendall(f"Direction: {current_direction}\n".encode())
elif data == 'distance':
try:
# Get distance from the ultrasonic
distance = ultrasonic.get_distance()
if distance is not None:
client_socket.sendall(f"Distance: {distance:.2f} cm\n".encode()) # Send distance to client
else:
client_socket.sendall("Error: Could not read distance\n".encode()) # Error message
except Exception as e:
client_socket.sendall(f"Error reading distance: {e}\n".encode())
elif data == 'exit':
client_socket.sendall("Closing connection\n".encode())
break
else:
client_socket.sendall("Invalid command\n".encode())
except Exception as e:
print(f"Error handling client: {e}")
finally:
client_socket.close()
def start_server():
"""Starts the Wi-Fi server."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print(f"Server listening")
try:
while True:
client_socket, addr = server_socket.accept()
print(f"Connection established with {addr}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
except KeyboardInterrupt:
print("Shutting down server.")
finally:
server_socket.close()
if __name__ == "__main__":
start_server()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment