portale sinric pro - pasqua - 02-25-2023
Buongiorno
Sto usando una scheda ESP8266 per comunicare con il cloud HiveMQ dove leggo i topic inviati da Virtuino IoT.
Volevo capire se è possibile collegare la scheda anche al portale Sinric Pro in modo da rendere l'app compatibile con Alexa.
RE: portale sinric pro - pasqua - 02-25-2023
(02-25-2023, 02:54 PM)pasqua Wrote: Buongiorno
Sto usando una scheda ESP8266 per comunicare con il cloud HiveMQ dove leggo i topic inviati da Virtuino IoT.
Volevo capire se è possibile collegare la scheda anche al portale Sinric Pro in modo da rendere l'app compatibile con Alexa.
Ci sono riuscito ora con le routine di alexa posso impostare il dimmer
#ifdef ESP8266
#include <ESP8266WiFi.h> // Pins for board ESP8266 Wemos-NodeMCU
#else
#include <WiFi.h>
#endif
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
//---- WiFi settings
const char* ssid = "xxxxxxxxxxxxxxxx";
const char* password = "xxxxxxxxxxxxxxxx";
//---- MQTT Broker settings
const char* mqtt_server = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx.s1.eu.hivemq.cloud"; // replace with your broker url
const char* mqtt_username = "xxxxxxxxxxx";
const char* mqtt_password = "xxxxxxxxxxxxxx";
const int mqtt_port =xxxx;
//sinric
#include "SinricPro.h"
#include "SinricProDimSwitch.h"
#define APP_KEY "cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf"
#define APP_SECRET "dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxd"
#define DIMSWITCH_ID "xxxxxxxxxxxxxxxxxxxxxxx"
#define BAUD_RATE 9600 // Change baudrate to your need
WiFiClientSecure espClient; // for no secure connection use WiFiClient instead of WiFiClientSecure
//WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int command2 =0;
const char* command2_topic="mytopic";
//==========================================
void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}
//====================mqtt=================
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-"; // Create a random client ID
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(command2_topic); // subscribe the topics here
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
setup_wifi();
delay(5000);
}
}
}
//================================================ setup
//================================================
void setup() {
Serial.begin(9600);
setup_wifi();
//pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
espClient.setInsecure();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
setupSinricPro();
}
//================================================ loop
//================================================
void loop() {
if (!client.connected()) reconnect();
client.loop();
//---- example: how to publish sensor values every 5 sec
unsigned long now = millis();
SinricPro.handle();
}
//=======================================
// This void is called every time we have a message from the broker
void callback(char* topic, byte* payload, unsigned int length) {
String incommingMessage = "";
for (int i = 0; i < length; i++) incommingMessage+=(char)payload[i];
Serial.println("Message arrived ["+String(topic)+"]"+incommingMessage);
if( strcmp(topic,command2_topic) == 0){//mytopic
if (incommingMessage.equals("80")) {
Serial.println("HAI IMPOSTATO IL DIMMER AD 80 ");
}
}
}
//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str(), true))
Serial.println("Message publised ["+String(topic)+"]: "+payload);
}
// SINRIC PRO
struct {
bool powerState = false;
int powerLevel = 0;
} device_state;
bool onPowerState(const String &deviceId, bool &state) {
Serial.printf("Device %s power turned %s \r\n", deviceId.c_str(), state?"on":"off");
device_state.powerState = state;
return true; // request handled properly
}
bool onPowerLevel(const String &deviceId, int &powerLevel) {
device_state.powerLevel = powerLevel;
Serial.printf("Device %s power level changed to %d\r\n", deviceId.c_str(), device_state.powerLevel);
// PUBBLICA QUANTO RICEVUTO SU HIVEMQ
delay(50);
Serial.println(powerLevel);
publishMessage(command2_topic,String(powerLevel),true);
return true;
}
bool onAdjustPowerLevel(const String &deviceId, int &levelDelta) {
device_state.powerLevel += levelDelta;
Serial.printf("Device %s power level changed about %i to %d\r\n", deviceId.c_str(), levelDelta, device_state.powerLevel);
levelDelta = device_state.powerLevel;
return true;
}
void setupSinricPro() {
SinricProDimSwitch &myDimSwitch = SinricPro[DIMSWITCH_ID];
// set callback function to device
myDimSwitch.onPowerState(onPowerState);
myDimSwitch.onPowerLevel(onPowerLevel);
myDimSwitch.onAdjustPowerLevel(onAdjustPowerLevel);
// setup SinricPro
SinricPro.onConnected([](){ Serial.printf("Connected to SinricPro\r\n"); });
SinricPro.onDisconnected([](){ Serial.printf("Disconnected from SinricPro\r\n"); });
SinricPro.begin(APP_KEY, APP_SECRET);
}
RE: portale sinric pro - iliaslamprou - 02-27-2023
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:
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();}
|