dev #1
8
Samples~/Websockets-Comm/ArduinoESP32-Code.meta
Normal file
8
Samples~/Websockets-Comm/ArduinoESP32-Code.meta
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: f48181e263f4549d298428afd28e7455
|
||||||
|
folderAsset: yes
|
||||||
|
DefaultImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 4906cc41f86cc469aa5f4063b497807e
|
||||||
|
folderAsset: yes
|
||||||
|
DefaultImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
|
||||||
|
//==================================
|
||||||
|
//ESP32 WebSocket Server: Toggle LED
|
||||||
|
//by: Ulas Dikme
|
||||||
|
//modified by: António Pinheiro Braga
|
||||||
|
//==================================
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <WebServer.h>
|
||||||
|
#include <WebSocketsServer.h>
|
||||||
|
//-----------------------------------------------
|
||||||
|
|
||||||
|
const char* ssid = "ChangeMe"; //Change this to match your network name
|
||||||
|
const char* password = "ChangeMe"; //Change this to match your network password
|
||||||
|
|
||||||
|
//-----------------------------------------------
|
||||||
|
|
||||||
|
//NOTE: You might need to change the following code depending on the model of your ESP32
|
||||||
|
|
||||||
|
#define BUILTIN_LED 13 //Default Sparkfun ESP32-S2 Built in LED
|
||||||
|
#define LED 10
|
||||||
|
#define POTENTIOMETER A5
|
||||||
|
#define RGBLED_RED A1
|
||||||
|
#define RGBLED_GREEN A2
|
||||||
|
#define RGBLED_BLUE A0
|
||||||
|
#define BUTTON 34
|
||||||
|
//-----------------------------------------------
|
||||||
|
WebServer server(80);
|
||||||
|
WebSocketsServer webSocket = WebSocketsServer(81);
|
||||||
|
//-----------------------------------------------
|
||||||
|
boolean LEDonoff=false; String JSONtxt; String oldJSON; int currentClientNumber; int currentpotVal; int oldpotVal; int mappedPotVal; bool buttonMessageSent; int buttonState;
|
||||||
|
//-----------------------------------------------
|
||||||
|
#include "html.h"
|
||||||
|
#include "header.h"
|
||||||
|
//====================================================================
|
||||||
|
|
||||||
|
void setup()
|
||||||
|
{
|
||||||
|
Serial.begin(115200); pinMode(LED, OUTPUT); pinMode(BUILTIN_LED, OUTPUT); pinMode(RGBLED_RED, OUTPUT); pinMode(RGBLED_GREEN, OUTPUT); pinMode(RGBLED_BLUE, OUTPUT); pinMode(BUTTON, INPUT);
|
||||||
|
//-----------------------------------------------
|
||||||
|
connect2Network();
|
||||||
|
|
||||||
|
buttonMessageSent = false;
|
||||||
|
}
|
||||||
|
//====================================================================
|
||||||
|
|
||||||
|
int mapPotentiometerValue(int potValue) {
|
||||||
|
int mappedValue;
|
||||||
|
// Ensure the potentiometer value is within the expected range (0-8191)
|
||||||
|
if (potValue < 0) potValue = 0;
|
||||||
|
if (potValue > 8191) potValue = 8191;
|
||||||
|
|
||||||
|
// Map the value from the range [0, 8191] to [0, 100]
|
||||||
|
mappedValue = (potValue * 100) / 8191;
|
||||||
|
return mappedValue;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop()
|
||||||
|
{
|
||||||
|
currentpotVal = analogRead(POTENTIOMETER);
|
||||||
|
buttonState = digitalRead(BUTTON);
|
||||||
|
//int brightness = currentpotVal / 4;
|
||||||
|
// int brightness = map(currentpotVal, 0, 8191, 0, 255);
|
||||||
|
// analogWrite(LED_ANALOG, brightness);
|
||||||
|
|
||||||
|
mappedPotVal = mapPotentiometerValue(currentpotVal);
|
||||||
|
int threshold = 2;
|
||||||
|
int margin = 2;
|
||||||
|
|
||||||
|
if(mappedPotVal <= margin) mappedPotVal = 0;
|
||||||
|
if(mappedPotVal >= 100 - margin) mappedPotVal = 100;
|
||||||
|
|
||||||
|
if(abs(mappedPotVal - oldpotVal) >= threshold)
|
||||||
|
{
|
||||||
|
|
||||||
|
Serial.println("Pot value: " + String(mappedPotVal));
|
||||||
|
webSocket.broadcastTXT("Pot value: " + String(mappedPotVal));
|
||||||
|
oldpotVal = mappedPotVal;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(WiFi.status() != WL_CONNECTED) {
|
||||||
|
Serial.println("Lost connection to network! Attempting to reconnect...");
|
||||||
|
connect2Network();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
webSocket.loop(); server.handleClient();
|
||||||
|
if(currentClientNumber != webSocket.connectedClients()){
|
||||||
|
if(currentClientNumber < webSocket.connectedClients()) Serial.println("A new client has connected!");
|
||||||
|
else Serial.println("A client has disconnected");
|
||||||
|
Serial.print("Number of clients currently connected: ");
|
||||||
|
Serial.println(webSocket.connectedClients());
|
||||||
|
|
||||||
|
currentClientNumber = webSocket.connectedClients();
|
||||||
|
webSocket.broadcastTXT(JSONtxt);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(buttonState == HIGH && buttonMessageSent == false) {
|
||||||
|
|
||||||
|
webSocket.broadcastTXT("Button Pressed: true");
|
||||||
|
buttonMessageSent = true;
|
||||||
|
|
||||||
|
} else if(buttonState == LOW) buttonMessageSent = false;
|
||||||
|
|
||||||
|
//-----------------------------------------------
|
||||||
|
if(LEDonoff == false) {digitalWrite(LED, LOW); digitalWrite(BUILTIN_LED, LOW);}
|
||||||
|
else {digitalWrite(LED, HIGH); digitalWrite(BUILTIN_LED, HIGH);}
|
||||||
|
//-----------------------------------------------
|
||||||
|
String LEDstatus = "OFF";
|
||||||
|
if(LEDonoff == true) LEDstatus = "ON";
|
||||||
|
JSONtxt = "{\"LEDonoff\":\""+LEDstatus+"\"}";
|
||||||
|
sendMessage2Clients();
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
fileFormatVersion: 2
|
fileFormatVersion: 2
|
||||||
guid: 1c2e1682bdb9e4175a9feeab09836777
|
guid: 7ca6d6400bdb1423289a70ccdd257957
|
||||||
DefaultImporter:
|
DefaultImporter:
|
||||||
externalObjects: {}
|
externalObjects: {}
|
||||||
userData:
|
userData:
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
//=======================================
|
||||||
|
//handle function: send webpage to client
|
||||||
|
//=======================================
|
||||||
|
void webpage()
|
||||||
|
{
|
||||||
|
server.send(200,"text/html", webpageCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
void changeLEDBrightness(int pinNumber, int brightness) {
|
||||||
|
int mappedBrightness = map(brightness, 0, 100, 0, 255);
|
||||||
|
analogWrite(pinNumber, mappedBrightness);
|
||||||
|
}
|
||||||
|
|
||||||
|
//=====================================================
|
||||||
|
//function process event: new data received from client
|
||||||
|
//=====================================================
|
||||||
|
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t welength)
|
||||||
|
{
|
||||||
|
String payloadString = (const char *)payload;
|
||||||
|
Serial.print("payloadString= ");
|
||||||
|
Serial.println(payloadString);
|
||||||
|
|
||||||
|
if(type == WStype_TEXT) //receive text from client
|
||||||
|
{
|
||||||
|
byte separator=payloadString.indexOf('=');
|
||||||
|
String var = payloadString.substring(0,separator);
|
||||||
|
Serial.print("var= ");
|
||||||
|
Serial.println(var);
|
||||||
|
String val = payloadString.substring(separator+1);
|
||||||
|
Serial.print("val= ");
|
||||||
|
Serial.println(val);
|
||||||
|
Serial.println(" ");
|
||||||
|
|
||||||
|
if(var == "LEDonoff")
|
||||||
|
{
|
||||||
|
LEDonoff = false;
|
||||||
|
if(val == "ON") LEDonoff = true;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if(var == "RedLEDintensity") changeLEDBrightness(RGBLED_RED, val.toInt());
|
||||||
|
if(var == "GreenLEDintensity") changeLEDBrightness(RGBLED_GREEN, val.toInt());
|
||||||
|
if(var == "BlueLEDintensity") changeLEDBrightness(RGBLED_BLUE, val.toInt());
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void connect2Network()
|
||||||
|
{
|
||||||
|
WiFi.begin(ssid, password);
|
||||||
|
Serial.println("Printing this device's details bellow...");
|
||||||
|
Serial.print("MacAddress: ");
|
||||||
|
Serial.println(WiFi.macAddress());
|
||||||
|
Serial.print("Device Name: ");
|
||||||
|
Serial.println(WiFi.getHostname());
|
||||||
|
Serial.print("Attempting to connect to " + String(ssid) + " network...");
|
||||||
|
while(WiFi.status() != WL_CONNECTED){Serial.print("."); delay(500);}
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
Serial.println();
|
||||||
|
Serial.println("Successfully connected to network!");
|
||||||
|
Serial.print("Local IP: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
//-----------------------------------------------
|
||||||
|
server.on("/", webpage);
|
||||||
|
//-----------------------------------------------
|
||||||
|
server.begin(); webSocket.begin();
|
||||||
|
webSocket.onEvent(webSocketEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendMessage2Clients() {
|
||||||
|
if(oldJSON != JSONtxt) webSocket.broadcastTXT(JSONtxt);
|
||||||
|
oldJSON = JSONtxt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 4801fbfd7a8a84d15a79904fcef7189a
|
||||||
100
Samples~/Websockets-Comm/ArduinoESP32-Code/ESP32_Server/html.h
Normal file
100
Samples~/Websockets-Comm/ArduinoESP32-Code/ESP32_Server/html.h
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
//=====================
|
||||||
|
//HTML code for webpage
|
||||||
|
//=====================
|
||||||
|
const char webpageCode[] PROGMEM =
|
||||||
|
R"=====(
|
||||||
|
<!DOCTYPE HTML>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>ESP32 Web Server</title>
|
||||||
|
</head>
|
||||||
|
<!-------------------------------C S S------------------------------>
|
||||||
|
<style>
|
||||||
|
#btn
|
||||||
|
{
|
||||||
|
display: inline-block;
|
||||||
|
text-decoration: none;
|
||||||
|
background: #8CD460;
|
||||||
|
color: rgba(255,255,255, 0.80);
|
||||||
|
font-weight: bold;
|
||||||
|
font: 60px arial, sans-serif;
|
||||||
|
width: 150px;
|
||||||
|
height: 150px;
|
||||||
|
line-height: 150px;
|
||||||
|
border-radius: 50%;
|
||||||
|
text-align: center;
|
||||||
|
vertical-align: middle;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0px 0px 0px 8px #8CD460;
|
||||||
|
border: solid 2px rgba(255,255,255, 0.47);
|
||||||
|
transition: 0.5s;
|
||||||
|
}
|
||||||
|
#btn2
|
||||||
|
{
|
||||||
|
display: inline-block;
|
||||||
|
text-decoration: none;
|
||||||
|
background: #8CD460;
|
||||||
|
color: rgba(255,255,255, 0.80);
|
||||||
|
font-weight: bold;
|
||||||
|
font: 60px arial, sans-serif;
|
||||||
|
width: 150px;
|
||||||
|
height: 150px;
|
||||||
|
line-height: 150px;
|
||||||
|
border-radius: 50%;
|
||||||
|
text-align: center;
|
||||||
|
vertical-align: middle;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0px 0px 0px 8px #8CD460;
|
||||||
|
border: solid 2px rgba(255,255,255, 0.47);
|
||||||
|
transition: 0.5s;
|
||||||
|
}
|
||||||
|
body {text-align:center; font-family:"Calibri"; background-color:rgba(0, 3, 8, 0.26)}
|
||||||
|
h1 {color: rgba(0, 0, 255, 0.87); font-size: 50px;}
|
||||||
|
</style>
|
||||||
|
<!------------------------------H T M L----------------------------->
|
||||||
|
<body>
|
||||||
|
<h1>E S P 3 2<br>WebSocket Server</h1>
|
||||||
|
<a href="#" id="btn" ONCLICK='button()'> </a>
|
||||||
|
<a href="#" id="btn2" ONCLICK='button2()'> </a>
|
||||||
|
<!-----------------------------JavaScript--------------------------->
|
||||||
|
<script>
|
||||||
|
InitWebSocket()
|
||||||
|
function InitWebSocket()
|
||||||
|
{
|
||||||
|
websock = new WebSocket('ws://'+window.location.hostname+':81/');
|
||||||
|
websock.onmessage = function(evt)
|
||||||
|
{
|
||||||
|
JSONobj = JSON.parse(evt.data);
|
||||||
|
document.getElementById('btn').innerHTML = JSONobj.LEDonoff;
|
||||||
|
if(JSONobj.LEDonoff == 'ON')
|
||||||
|
{
|
||||||
|
document.getElementById('btn').style.background='#FF0000';
|
||||||
|
document.getElementById('btn').style["boxShadow"] = "0px 0px 0px 8px #FF0000";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
document.getElementById('btn').style.background='#111111';
|
||||||
|
document.getElementById('btn').style["boxShadow"] = "0px 0px 0px 8px #111111";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//-------------------------------------------------------------
|
||||||
|
function button()
|
||||||
|
{
|
||||||
|
btn = 'LEDonoff=ON';
|
||||||
|
if(document.getElementById('btn').innerHTML == 'ON')
|
||||||
|
{
|
||||||
|
btn = 'LEDonoff=OFF';
|
||||||
|
}
|
||||||
|
websock.send(btn);
|
||||||
|
}
|
||||||
|
|
||||||
|
function button2()
|
||||||
|
{
|
||||||
|
message = 'message=test';
|
||||||
|
websock.send(message);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)=====";
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 73fce3693b7d840fdbe8086d26eb8356
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,8 @@ using UnityEngine;
|
|||||||
using NativeWebSocket;
|
using NativeWebSocket;
|
||||||
using UnityEngine.UI;
|
using UnityEngine.UI;
|
||||||
using TMPro;
|
using TMPro;
|
||||||
|
using System.Net.NetworkInformation;
|
||||||
|
using System.Collections;
|
||||||
|
|
||||||
public class WebSocketClient : MonoBehaviour
|
public class WebSocketClient : MonoBehaviour
|
||||||
{
|
{
|
||||||
@@ -20,10 +22,18 @@ public class WebSocketClient : MonoBehaviour
|
|||||||
[SerializeField]
|
[SerializeField]
|
||||||
private int Port = 7890; //The Port your WebSocket Connection will "talk" to
|
private int Port = 7890; //The Port your WebSocket Connection will "talk" to
|
||||||
|
|
||||||
|
[SerializeField]
|
||||||
|
private TextMeshProUGUI connectionStatusText; //Text to show the connection status
|
||||||
|
|
||||||
|
private Color connectedColor = Color.green; //Color for connected status
|
||||||
|
private Color disconnectedColor = Color.red; //Color for disconnected status
|
||||||
|
|
||||||
private WebSocket webSocket;
|
private WebSocket webSocket;
|
||||||
|
|
||||||
private void initWebSocket() //Starts WebSocket Client Connection
|
private void initWebSocket() //Starts WebSocket Client Connection
|
||||||
{
|
{
|
||||||
|
connectionStatusText.text = "Connecting to device with IP - " + IPAdress + "...";
|
||||||
|
|
||||||
webSocket = new WebSocket($"ws://{IPAdress}:{Port}");
|
webSocket = new WebSocket($"ws://{IPAdress}:{Port}");
|
||||||
//while (webSocket.State == WebSocketState.Connecting) {
|
//while (webSocket.State == WebSocketState.Connecting) {
|
||||||
webSocket.Connect();
|
webSocket.Connect();
|
||||||
@@ -42,11 +52,16 @@ public class WebSocketClient : MonoBehaviour
|
|||||||
Debug.Log("Connecion opened!");
|
Debug.Log("Connecion opened!");
|
||||||
string message = "Hello from Unity! = Device name: " + SystemInfo.deviceName + " | Device Mac Address: " + SystemInfo.deviceUniqueIdentifier;
|
string message = "Hello from Unity! = Device name: " + SystemInfo.deviceName + " | Device Mac Address: " + SystemInfo.deviceUniqueIdentifier;
|
||||||
SendWebSocketMessage(message);
|
SendWebSocketMessage(message);
|
||||||
|
connectionStatusText.text = "Connected to device with IP - " + IPAdress;
|
||||||
|
connectionStatusText.color = connectedColor;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void WebSocket_OnError(string error) //Alerts on console when WebSocket Connection is Unsuccessfull
|
private void WebSocket_OnError(string error) //Alerts on console when WebSocket Connection is Unsuccessfull
|
||||||
{
|
{
|
||||||
Debug.Log($"Error: {error}");
|
Debug.Log($"Error: {error}");
|
||||||
|
connectionStatusText.text = "Error on connnecting to server! (Check IP Adress and Port)";
|
||||||
|
connectionStatusText.color = disconnectedColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void WebSocket_OnClose(WebSocketCloseCode closeCode) //Alerts on console when WebSocket Connection is Closed
|
private void WebSocket_OnClose(WebSocketCloseCode closeCode) //Alerts on console when WebSocket Connection is Closed
|
||||||
@@ -122,11 +137,37 @@ public class WebSocketClient : MonoBehaviour
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private IEnumerator checkConnection()
|
||||||
|
{
|
||||||
|
string baseText = "Connecting to device with IP - " + IPAdress;
|
||||||
|
string[] dots = new[] { ".", "..", "..." };
|
||||||
|
int dotIndex = 0;
|
||||||
|
float timeout = 5f;
|
||||||
|
float elapsed = 0f;
|
||||||
|
|
||||||
|
while (elapsed < timeout)
|
||||||
|
{
|
||||||
|
connectionStatusText.text = baseText + dots[dotIndex];
|
||||||
|
dotIndex = (dotIndex + 1) % dots.Length;
|
||||||
|
yield return new WaitForSeconds(1f);
|
||||||
|
elapsed += 1f;
|
||||||
|
}
|
||||||
|
|
||||||
|
Debug.Log("State is: " + webSocket.State.ToString());
|
||||||
|
if (webSocket.State == WebSocketState.Connecting)
|
||||||
|
{
|
||||||
|
connectionStatusText.text = "Could not connect to device. " + "(Device powered on? | Connected to same network? | IP Correct? | Port Correct?)";
|
||||||
|
connectionStatusText.color = disconnectedColor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Start is called before the first frame update
|
// Start is called before the first frame update
|
||||||
void Start()
|
void Start()
|
||||||
{
|
{
|
||||||
initWebSocket();
|
initWebSocket();
|
||||||
Debug.Log("Started");
|
Debug.Log("Started");
|
||||||
|
StartCoroutine(checkConnection());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update is called once per frame
|
// Update is called once per frame
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "se.su.dsv.extralitylab.unity",
|
"name": "se.su.dsv.extralitylab.unity",
|
||||||
"version": "0.1.3",
|
"version": "0.1.4",
|
||||||
"displayName": "ExtralityLab@DSV",
|
"displayName": "ExtralityLab@DSV",
|
||||||
"description": "Package for ExtralityLab at DSV Stockholm University.",
|
"description": "Package for ExtralityLab at DSV Stockholm University.",
|
||||||
"unity": "2022.3",
|
"unity": "2022.3",
|
||||||
|
|||||||
Reference in New Issue
Block a user