02-27-2023, 12:48 AM
(This post was last modified: 02-27-2023, 12:49 AM by iliaslamprou.)
Hi,
I think the the Sinric library can works at the same time with the WebSockets library
I have modified the Sinric example. It works to me. I used ESP32 device. Please check it:
I think the the Sinric library can works at the same time with the WebSockets library
I have modified the Sinric example. It works to me. I used ESP32 device. Please check it:
Code:
#ifdef ENABLE_DEBUG
#define DEBUG_ESP_PORT Serial
#define NODEBUG_WEBSOCKETS
#define NDEBUG
#endif
#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#endif
#include "SinricPro.h"
#include "SinricProSwitch.h"
#define WIFI_SSID "WIFI NAME"
#define WIFI_PASS "1234567890"
#define APP_KEY "f161e12c-axxxxxxxxxxxxxxxxxxxxxxx"
#define APP_SECRET "15a30521-f6aaxxxxxxxxxxxxxxxxxxxxxxxxxx"
#define SWITCH_ID "63fbf5e71xxxxxxxxx"
#define BAUD_RATE 9600 // Change baudrate to your need
#define BUTTON_PIN 0 // GPIO for BUTTON (inverted: LOW = pressed, HIGH = released)
#define LED_PIN 4 // GPIO for LED (inverted)
#include <WebSocketsServer.h>
WebSocketsServer webSocket = WebSocketsServer(8000);
bool myPowerState = false;
unsigned long lastBtnPress = 0;
//---- Enter all the Tags here. You have to use the same Tags on Virtuino variables
const char* pin4_tag= "V4"; // tag for digital input
const char* pin22_tag= "V22"; // tag for digital output
// const char* pin17_tag= "V17"; // add more here
const char* sensor1_tag= "V40"; // tag for sensor1 value
const char* sensor2_tag= "V41"; // tag for sensor2 value
//---- Enter some variables to hold the last state of the inputs.
uint8_t pin4_lastValue=0;
uint8_t pin22_lastValue=0;
//uint8_t pin17_lastValue=0;
unsigned long lastSensorRedingTime=0;
//===================================================== sendPinStatus
// It is called every time a new client is connected.
// The void informs Virtuino app about the current pin states and variable values.
void sendPinsStatus(){
sendValue(pin4_tag, String(digitalRead(4))); // send the digital input D0 state
sendValue(pin22_tag, String(digitalRead(22))); // send the digital input D1 state
//sendValue(pin17_tag, String(digitalRead(17))); // send the digital input D1 state
// add more here...
}
//===================================================== onValueReceived
// It is called every time a new value received
void onValueReceived(String tag, String value){
Serial.println("Received: tag="+tag+ " value="+value);
if (tag== pin22_tag) { // write to digital pin D5
int v=value.toInt();
if (v==1) digitalWrite(22,HIGH); else digitalWrite(22,LOW);
}
/*
if (tag== pin17_tag) { // write to digital pin 17
int v=value.toInt();
if (v==1) digitalWrite(17,HIGH); else digitalWrite(17,LOW);
}
*/
// add more here...
}
/* bool onPowerState(String deviceId, bool &state)
*
* Callback for setPowerState request
* parameters
* String deviceId (r)
* contains deviceId (useful if this callback used by multiple devices)
* bool &state (r/w)
* contains the requested state (true:on / false:off)
* must return the new state
*
* return
* true if request should be marked as handled correctly / false if not
*/
bool onPowerState(const String &deviceId, bool &state) {
Serial.printf("Device %s turned %s (via SinricPro) \r\n", deviceId.c_str(), state?"on":"off");
myPowerState = state;
digitalWrite(LED_PIN, myPowerState?LOW:HIGH);
return true; // request handled properly
}
void handleButtonPress() {
unsigned long actualMillis = millis(); // get actual millis() and keep it in variable actualMillis
if (digitalRead(BUTTON_PIN) == LOW && actualMillis - lastBtnPress > 1000) { // is button pressed (inverted logic! button pressed = LOW) and debounced?
if (myPowerState) { // flip myPowerState: if it was true, set it to false, vice versa
myPowerState = false;
} else {
myPowerState = true;
}
digitalWrite(LED_PIN, myPowerState?LOW:HIGH); // if myPowerState indicates device turned on: turn on led (builtin led uses inverted logic: LOW = LED ON / HIGH = LED OFF)
// get Switch device back
SinricProSwitch& mySwitch = SinricPro[SWITCH_ID];
// send powerstate event
mySwitch.sendPowerStateEvent(myPowerState); // send the new powerState to SinricPro server
Serial.printf("Device %s turned %s (manually via flashbutton)\r\n", mySwitch.getDeviceId().c_str(), myPowerState?"on":"off");
lastBtnPress = actualMillis; // update last button press variable
}
}
// setup function for WiFi connection
void setupWiFi() {
Serial.printf("\r\n[Wifi]: Connecting");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
Serial.printf(".");
delay(250);
}
Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());
}
// setup function for SinricPro
void setupSinricPro() {
// add device to SinricPro
SinricProSwitch& mySwitch = SinricPro[SWITCH_ID];
// set callback function to device
mySwitch.onPowerState(onPowerState);
// setup SinricPro
SinricPro.onConnected([](){ Serial.printf("Connected to SinricPro\r\n"); });
SinricPro.onDisconnected([](){ Serial.printf("Disconnected from SinricPro\r\n"); });
//SinricPro.restoreDeviceStates(true); // Uncomment to restore the last known state from the server.
SinricPro.begin(APP_KEY, APP_SECRET);
}
// main setup function
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // GPIO 0 as input, pulled high
pinMode(LED_PIN, OUTPUT); // define LED GPIO as output
digitalWrite(LED_PIN, HIGH); // turn off LED on bootup
Serial.begin(BAUD_RATE); Serial.printf("\r\n\r\n");
setupWiFi();
pinMode(4,INPUT); // on this example the pin 5 is used as INPUT
pinMode(22,OUTPUT); // on this example the pin 22 is used as OUTPUT
//pinMode(D17,OUTPUT);
webSocket.begin();
webSocket.onEvent(webSocketEvent);
setupSinricPro();
}
void loop() {
handleButtonPress();
SinricPro.handle();
webSocket.loop();
}
/*=====================================================
====================== UTILS =======================
=====================================================
You don't need to make changes to the code below
*/
//===================================================== sendValue
// This function sends a value to a Tag.
// The tag and the value are converted to a json message before sending
bool sendValue(const char* tag, String value){
String json = "{\"";
json+=tag;
json+="\":\"";
json+=value;
json+="\"}";
Serial.println("Send: "+json);
return webSocket.broadcastTXT(json); // This function sends the message to all connected clients.
}
//===================================================== webSocketEvent
//This is the server handler. It receives all the messages
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] New client connected - IP: %d.%d.%d.%d \n", num, ip[0], ip[1], ip[2], ip[3]);
sendPinsStatus(); // send the initial pin and variable values to the connected clients
break;
}
case WStype_TEXT: // a new message received
Serial.printf("[%u] Received: %s\n", num, payload);
//-- The incoming payload is a json message. The following code extracts the value from json without extra library
String str = (char*)payload;
int p1 = str.indexOf("{\"");
if (p1==0) {
int p2 = str.indexOf("\":");
if (p2>p1) {
String tag = str.substring(p1+2,p2);
p1 = str.indexOf(":\"",p2);
if (p1>0) {
p2 = str.lastIndexOf("\"}");
if (p2>0){
String value = str.substring(p1+2,p2);
onValueReceived(tag,value);
}
}
}
}
break;
}
}
//============================================================== vDelay
void vDelay(int delayInMillis){long t=millis()+delayInMillis;while (millis()<t) webSocket.loop();}