Skip to content
This repository has been archived by the owner on May 17, 2019. It is now read-only.

Add multi user Websocket and chat exemple #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions WebSocketServer.cpp
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,8 @@ void WebSocketServer::disconnectStream() {
socket_client->stop();
}

String WebSocketServer::getData() {
String WebSocketServer::getData(Client &client) {
socket_client = &client;
String data;

if (hixie76style) {
Expand All @@ -372,7 +373,8 @@ String WebSocketServer::getData() {
return data;
}

void WebSocketServer::sendData(const char *str) {
void WebSocketServer::sendData(const char *str, Client &client) {
socket_client = &client;
#ifdef DEBUGGING
Serial.print(F("Sending data: "));
Serial.println(str);
Expand All @@ -388,7 +390,9 @@ void WebSocketServer::sendData(const char *str) {
}
}

void WebSocketServer::sendData(String str) {
void WebSocketServer::sendData(String str, Client &client) {
socket_client = &client;

#ifdef DEBUGGING
Serial.print(F("Sending data: "));
Serial.println(str);
Expand Down
6 changes: 3 additions & 3 deletions WebSocketServer.h
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ class WebSocketServer {
bool handshake(Client &client);

// Get data off of the stream
String getData();
String getData(Client &client);

// Write data to the stream
void sendData(const char *str);
void sendData(String str);
void sendData(const char *str,Client &client);
void sendData(String str,Client &client);

private:
Client *socket_client;
Expand Down
Empty file modified examples/WebSocketClient_Demo/WebSocketClient_Demo.ino
100644 → 100755
Empty file.
140 changes: 43 additions & 97 deletions examples/WebSocketServer.html
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,101 +1,47 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>
WebSocket Test
</title>
<style>
#redbar {
color: #fff;
background-color: #f00;
width: 500px;
height: 30px;
}
#greenbar {
color: #fff;
background-color: #0f0;
width: 500px;
height: 30px;
}
#bluebar {
color: #fff;
background-color: #00f;
width: 500px;
height: 30px;
}
</style>
<head>
<meta charset="utf-8">
<title>Chat example</title>
<script>
var connection
window.addEventListener("load", function () {
connection = new WebSocket("ws://192.168.1.20:8081")
connection.onopen = function () {
var div = document.createElement("div")
div.textContent = "Connection opened";
document.body.appendChild(div);

<script language = "javascript"type = "text/javascript">
var wsUri = "ws://10.1.1.33/";
var output;

function init() {
testWebSocket();
}

function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
console.log("CONNECTED");
};
websocket.onclose = function(evt) {
console.log("DISCONNECTED");
};
websocket.onmessage = function(evt) {
var pin = evt.data.charAt(1);
var element;
document.getElementById("form").onsubmit = function (event) {
var msg = document.getElementById("msg")
if (msg.value)
connection.send(msg.value)
msg.value = ""
event.preventDefault()
}
}
connection.onclose = function () {
var div = document.createElement("div")
div.textContent = "Connection closed";
document.body.appendChild(div);
}
connection.onerror = function () {
var div = document.createElement("div")
div.textContent = "Connection error";
document.body.appendChild(div);
}
connection.onmessage = function (event) {
var div = document.createElement("div")
div.textContent = event.data
document.body.appendChild(div)
}
})
</script>
</head>

if (pin == 1) {
element = document.getElementById("redbar");
element.style.width = evt.data.substring(2) + "px";
} else if (pin == 2) {
element = document.getElementById("greenbar");
element.style.width = evt.data.substring(2) + "px";
} else if (pin == 3) {
element = document.getElementById("bluebar");
element.style.width = evt.data.substring(2) + "px";
}

};
websocket.onerror = function(evt) {
console.log("ERROR: " + evt.data);
};
}

function changeRed() {
var value = document.getElementById("red").checked;
var message = "d8";

message += value ? "1" : "0";

console.log("SENT: " + message);
websocket.send(message);
}

function changeGreen() {
var value = document.getElementById("green").checked;
var message = "d9";

message += value ? "1" : "0";

console.log("SENT: " + message);
websocket.send(message);
}


window.addEventListener("load", init, false);
</script>
</head>
<body>
<h2>
WebSocket Test
</h2>
<input id="red" type="checkbox" onchange="changeRed();">Pin 8</input>
<input id="green" type="checkbox" onchange="changeGreen();">Pin 9</input>

<div id="redbar">Pin 1</div>
<div id="greenbar">Pin 2</div>
<div id="bluebar">Pin 3</div>
</body>
<body>
<form id="form">
Message: <input size="50" id="msg"> <input type="submit" value="Submit">
</form>
</body>
</html>
178 changes: 77 additions & 101 deletions examples/WebSocketServer_Demo/WebSocketServer_Demo.ino
Original file line number Diff line number Diff line change
@@ -1,123 +1,99 @@
#include <SPI.h>
#include <SC16IS750.h>
#include <WiFly.h>
/*
Based on WiFiTelnetToSerial
*/
#include <ESP8266WiFi.h>
#include <WebSocketServer.h>//https://github.com/morrissinger/ESP8266-Websocket

// Enabe debug tracing to Serial port.
#define DEBUGGING
//how many clients should be able to WebSocket to this ESP8266
#define MAX_SRV_CLIENTS 10

// Here we define a maximum framelength to 64 bytes. Default is 256.
#define MAX_FRAME_LENGTH 64
const char* ssid = "XXXXXXXX";
const char* password = "XXXXXXXX";

// Define how many callback functions you have. Default is 1.
#define CALLBACK_FUNCTIONS 1
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete

#include <WebSocketServer.h>

WiFlyServer server(80);
WiFiServer server(8081);
WebSocketServer webSocketServer;


// Called when a new message from the WebSocket is received
// Looks for a message in this form:
//
// DPV
//
// Where:
// D is either 'd' or 'a' - digital or analog
// P is a pin #
// V is the value to apply to the pin
//

void handleClientData(String &dataString) {
bool isDigital = dataString[0] == 'd';
int pin = dataString[1] - '0';
int value;

value = dataString[2] - '0';


pinMode(pin, OUTPUT);

if (isDigital) {
digitalWrite(pin, value);
} else {
analogWrite(pin, value);
}

Serial.println(dataString);
}

// send the client the analog value of a pin
void sendClientData(int pin) {
String data = "a";

pinMode(pin, INPUT);
data += String(pin) + String(analogRead(pin));
webSocketServer.sendData(data);
}
WiFiClient serverClients[MAX_SRV_CLIENTS];

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);


Serial.begin(9600);
SC16IS750.begin();

WiFly.setUart(&SC16IS750);

WiFly.begin();
Serial.print("\nConnecting to "); Serial.println(ssid);
uint8_t i = 0;

// This is for an unsecured network
// For a WPA1/2 network use auth 3, and in another command send 'set wlan phrase PASSWORD'
// For a WEP network use auth 2, and in another command send 'set wlan key KEY'
WiFly.sendCommand(F("set wlan auth 1"));
WiFly.sendCommand(F("set wlan channel 0"));
WiFly.sendCommand(F("set ip dhcp 1"));
while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
if(i == 21){
Serial.print("Could not connect to"); Serial.println(ssid);
while(1) delay(500);
}

//start UART and the server
server.begin();
Serial.println(F("Joining WiFi network..."));
server.setNoDelay(true);

Serial.print("Ready! Use 'telnet ");
Serial.print(WiFi.localIP());
Serial.println(" 8081' to connect");
}

// Here is where you set the network name to join
if (!WiFly.sendCommand(F("join arduino_wifi"), "Associated!", 20000, false)) {
Serial.println(F("Association failed."));
while (1) {
// Hang on failure.
void loop() {
uint8_t i;
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
while(!serverClients[i].available())
{
//Serial.println("wait");
}
webSocketServer.handshake(serverClients[i]);
Serial.print("New client: "); Serial.println(i);
break;
}
}

WiFiClient serverClient = server.available();
serverClient.stop();
}

if (!WiFly.waitForResponse("DHCP in", 10000)) {
Serial.println(F("DHCP failed."));
while (1) {
// Hang on failure.
//check clients for data
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
while(serverClients[i].available()){
String data = webSocketServer.getData(serverClients[i]);
if (data.length() > 0) {
Serial.print("receive Data from client ");
Serial.print(i);
Serial.print(":");
Serial.println(data);
//ECHO to the client:
webSocketServer.sendData("you sent :"+data, serverClients[i]);
}
}
}
}
}

// This is how you get the local IP as an IPAddress object
Serial.println(WiFly.localIP());

// This delay is needed to let the WiFly respond properly
delay(100);
}

void loop() {
String data;
WiFlyClient client = server.available();

if (client.connected() && webSocketServer.handshake(client)) {

while (client.connected()) {
data = webSocketServer.getData();

if (data.length() > 0) {
handleClientData(data);
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
webSocketServer.sendData(inputString, serverClients[i]);
delay(1);
}
}

sendClientData(1);
sendClientData(2);
sendClientData(3);
inputString = "";
}
}

// wait to fully let the client disconnect
delay(100);
}
}