Fire kind of finished and connection to ESP32 working for force sensor

This commit is contained in:
Nicklas 2024-02-29 18:07:03 +01:00
parent 5e76f7f3ab
commit b0b7f57f24
23 changed files with 10730 additions and 1 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

BIN
Assets/.DS_Store vendored Normal file

Binary file not shown.

@ -0,0 +1,79 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using WebSocketSharp; // Ensure this matches the WebSocket library you're using
public class ConnectUnityWithSensors : MonoBehaviour
{
// Websocket Service
WebSocket ws;
//public AudioSource audioSource; // Assign in inspector
//public AudioClip narrationClip; // Assign in inspector
//
public string esp32IPAddress = "10.204.0.249"; // Assign your ESP32 IP Address
public string esp32WebsocketPort = "81"; // Assign your ESP32 WebSocket port, typically "81"
private bool forceDataReceived = false;
private int receivedForceValue = 0;
void Start()
{
ConnectWithESP32();
//StartCoroutine(NarrationAndSignalCoroutine());
}
public void ConnectWithESP32()
{
Debug.Log("Connecting Unity with ESP32 via Websockets...");
ws = new WebSocket($"ws://{esp32IPAddress}:{esp32WebsocketPort}");
ws.OnOpen += (sender, e) =>
{
Debug.Log("WebSocket connected");
ws.Send("Hello from Unity!");
};
ws.OnMessage += (sender, e) =>
{
Debug.Log("Received message: " + e.Data);
int parsedValue;
bool isNumeric = int.TryParse(e.Data, out parsedValue);
if (isNumeric)
{
receivedForceValue = parsedValue;
forceDataReceived = true; // Indicate that new data has been received
}
};
ws.Connect();
Debug.Log("Websocket state - " + ws.ReadyState);
}
/*IEnumerator NarrationAndSignalCoroutine()
{
audioSource.PlayOneShot(narrationClip);
yield return new WaitForSeconds(narrationClip.length);
if (ws.IsAlive)
{
ws.Send("Need Force");
}
}*/
void Update()
{
if (forceDataReceived)
{
if (receivedForceValue > 50)
{
Debug.Log("Force threshold exceeded, action triggered.");
}
forceDataReceived = false; // Reset for the next message
}
}
void OnDestroy()
{
if (ws != null && ws.IsAlive)
{
ws.Close();
}
}
}

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0ecd28734b48f4313bff134f6df55396
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

16
Assets/NuGet.config Normal file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<disabledPackageSources />
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
<config>
<add key="repositoryPath" value="./Packages" />
<add key="PackagesConfigDirectoryPath" value="." />
<add key="slimRestore" value="true" />
</config>
</configuration>

23
Assets/NuGet.config.meta Normal file

@ -0,0 +1,23 @@
fileFormatVersion: 2
guid: 3bfefe5057a8141f5b38c75f10dda552
labels:
- NuGetForUnity
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,92 @@
#include <ArduinoWebsockets.h>
#include <WiFi.h>
const char* ssid = "dsv-extrality-lab"; // Change to your WiFi network name
const char* password = "expiring-unstuck-slider"; // Change to your WiFi password
using namespace websockets;
WebsocketsServer server;
WebsocketsClient client;
int forceSensorValue = 0;
const int forceSensorPin = 34; // Change to your actual force sensor pin
void setup() {
Serial.begin(115200);
// Initialize force sensor pin as input
pinMode(forceSensorPin, INPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
// Wait to connect to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Start WebSocket server
server.listen(81);
Serial.println("WebSocket server started.");
}
void loop() {
//Serial.println(WiFi.localIP());
if (server.poll()) { //server.poll() checks if any client is waiting to connect
Serial.println("Client is available to connect...");
client = server.accept(); // Accept() --> what server.accept does, is: "server, please wait until there is a client knocking on the door. when there is a client knocking, let him in and give me it's object".
Serial.println("Client connected...");
while (client.available()) {
Serial.println("Waiting for client to send a message...");
WebsocketsMessage msg = client.readBlocking();//readBlocking(removes the need for calling poll()) will return the first message or event received. readBlocking can also return Ping, Pong and Close messages.
// log
Serial.print("Got Message: ");
Serial.println(msg.data());
// Condition to blink the light at the start of program as a hello indication
if(msg.data().startsWith("Hello")){
for(int i=0;i<4;i++){
digitalWrite(11, HIGH); //Blink on
delay(170);
digitalWrite(11, LOW); //Blink off
}
client.send(String(10));
}
if (msg.data().equalsIgnoreCase("Need Force")) {
digitalWrite(11, HIGH); //Notify user to use force sensor
Serial.println("Reading value from Force Sensor...");
while (forceSensorValue <= 20) {
analogReadResolution(10); // This statement tells in how many bits the AnalogRead should happen.
// analogRead function returns the integer 10 bit integer (0 to 1023)
forceSensorValue = analogRead(A0);
if (forceSensorValue > 20) {
digitalWrite(13, HIGH);
Serial.print(forceSensorValue, DEC);
Serial.print("\n"); // Sending New Line character is important to read data in unity
Serial.flush();
// return echo
client.send(String(forceSensorValue));
digitalWrite(11, LOW); //Notify user NOT to use force sensor
digitalWrite(13, LOW); // Turn off built-in LED to notify user that value reading is done.
forceSensorValue = 0;
break;
}
}
}
}
// close the connection
client.close();
}
}

8
Assets/Packages.meta Normal file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ba626952818604530b1a713a3f4c9e15
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b48e8c73bd75840d084f07aa471692a6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>WebSocketSharp-netstandard</id>
<version>1.0.1</version>
<authors>sta</authors>
<owners>sta</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<licenseUrl>https://github.com/PingmanTools/websocket-sharp/blob/master/LICENSE.txt</licenseUrl>
<projectUrl>https://github.com/PingmanTools/websocket-sharp/</projectUrl>
<description>websocket-sharp provides the WebSocket protocol client and server.
It supports:
- RFC 6455
- WebSocket Client and Server
- Per-message Compression extension
- Secure Connection
- HTTP Authentication (Basic/Digest)
- Query String, Origin header and Cookies
- Connecting through the HTTP Proxy server
- .NET 3.5 or later (includes compatible)</description>
<copyright>sta.blockhead</copyright>
<tags>websocket</tags>
<repository url="https://github.com/PingmanTools/websocket-sharp/" />
<dependencies>
<group targetFramework=".NETFramework3.5" />
<group targetFramework=".NETFramework4.5" />
<group targetFramework=".NETStandard2.0" />
</dependencies>
</metadata>
</package>

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b2cc6a0b16ab14fe4ba051dc7f34b6c2
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a39cc4c82400245839717ac5f918c11f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b0cecdec8c24e4c089316e744ff04271
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,23 @@
fileFormatVersion: 2
guid: 625d580f04cb2464cad5256f498f47a9
labels:
- NuGetForUnity
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: cf0f4143cd53f4c9683577a5bfbc0649
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

@ -10812,6 +10812,52 @@ Transform:
- {fileID: 1342061459}
m_Father: {fileID: 1617586590}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &979159584
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 979159585}
- component: {fileID: 979159586}
m_Layer: 0
m_Name: GameManager
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &979159585
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 979159584}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -1.1969378, y: 1.3545454, z: -0.41485047}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &979159586
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 979159584}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 0ecd28734b48f4313bff134f6df55396, type: 3}
m_Name:
m_EditorClassIdentifier:
esp32IPAddress: 10.204.0.249
esp32WebsocketPort: 81
--- !u!1001 &980743549
PrefabInstance:
m_ObjectHideFlags: 0
@ -19343,7 +19389,7 @@ PrefabInstance:
- target: {fileID: 1446526844107249175, guid: 8c24f4efc20ae488386410c07ba7ec0c,
type: 3}
propertyPath: m_LocalPosition.x
value: -0.313
value: 0.2
objectReference: {fileID: 0}
- target: {fileID: 1446526844107249175, guid: 8c24f4efc20ae488386410c07ba7ec0c,
type: 3}
@ -23867,3 +23913,4 @@ SceneRoots:
- {fileID: 977726988}
- {fileID: 1117825302}
- {fileID: 350103768}
- {fileID: 979159585}

4
Assets/packages.config Normal file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="WebSocketSharp-netstandard" version="1.0.1" manuallyInstalled="true" />
</packages>

@ -0,0 +1,23 @@
fileFormatVersion: 2
guid: 19514aafa78aa4bee841c36d9526ca93
labels:
- NuGetForUnity
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:

@ -1,5 +1,6 @@
{
"dependencies": {
"com.github-glitchenzo.nugetforunity": "https://github.com/GlitchEnzo/NuGetForUnity.git?path=/src/NuGetForUnity",
"com.meta.xr.sdk.all": "60.0.0",
"com.meta.xr.sdk.interaction.ovr.samples": "62.0.0",
"com.unity.collab-proxy": "2.2.0",

@ -1,5 +1,12 @@
{
"dependencies": {
"com.github-glitchenzo.nugetforunity": {
"version": "https://github.com/GlitchEnzo/NuGetForUnity.git?path=/src/NuGetForUnity",
"depth": 0,
"source": "git",
"dependencies": {},
"hash": "75f68222d0a4bd2b468dbf3e6a17a191d28041ab"
},
"com.meta.xr.mrutilitykit": {
"version": "60.0.0",
"depth": 1,