Skip to content

Commit

Permalink
Merge branch 'v2.0' into mega
Browse files Browse the repository at this point in the history
  • Loading branch information
psy0rz committed Jan 18, 2018
2 parents fe9a579 + 017aad0 commit a6ea35e
Show file tree
Hide file tree
Showing 12 changed files with 246 additions and 78 deletions.
22 changes: 13 additions & 9 deletions src/Command.ino
Original file line number Diff line number Diff line change
Expand Up @@ -366,15 +366,19 @@ void ExecuteCommand(byte source, const char *Line)
}
if (strcasecmp_P(Command, PSTR("Publish")) == 0 && WiFi.status() == WL_CONNECTED)
{
success = true;
String event = Line;
event = event.substring(8);
int index = event.indexOf(',');
if (index > 0)
{
String topic = event.substring(0, index);
String value = event.substring(index + 1);
MQTTclient.publish(topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
// ToDo TD-er: Not sure about this function, but at least it sends to an existing MQTTclient
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
success = true;
String event = Line;
event = event.substring(8);
int index = event.indexOf(',');
if (index > 0)
{
String topic = event.substring(0, index);
String value = event.substring(index + 1);
MQTTpublish(enabledMqttController, topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
}
}
}

Expand Down
46 changes: 30 additions & 16 deletions src/Controller.ino
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,12 @@ void callback(char* c_topic, byte* b_payload, unsigned int length) {
char c_payload[384];

statusLED(true);

if (length>sizeof(c_payload)-1)
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController < 0) {
addLog(LOG_LEVEL_ERROR, F("MQTT : No enabled MQTT controller"));
return;
}
if ((length + 1) > sizeof(c_payload))
{
addLog(LOG_LEVEL_ERROR, F("MQTT : Ignored too big message"));
return;
Expand All @@ -108,19 +112,19 @@ void callback(char* c_topic, byte* b_payload, unsigned int length) {
struct EventStruct TempEvent;
TempEvent.String1 = c_topic;
TempEvent.String2 = c_payload;
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[enabledMqttController]);
CPlugin_ptr[ProtocolIndex](CPLUGIN_PROTOCOL_RECV, &TempEvent, dummyString);
}


/*********************************************************************************************\
* Connect to MQTT message broker
\*********************************************************************************************/
void MQTTConnect()
void MQTTConnect(int controller_idx)
{
if (WiFi.status() != WL_CONNECTED) return;
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings)); // todo index is now fixed to 0
LoadControllerSettings(controller_idx, (byte*)&ControllerSettings, sizeof(ControllerSettings));

if (ControllerSettings.UseDNS) {
MQTTclient.setServer(ControllerSettings.getHost().c_str(), ControllerSettings.Port);
Expand All @@ -145,8 +149,8 @@ void MQTTConnect()
String log = "";
boolean MQTTresult = false;

if ((SecuritySettings.ControllerUser[0] != 0) && (SecuritySettings.ControllerPassword[0] != 0))
MQTTresult = MQTTclient.connect(clientid.c_str(), SecuritySettings.ControllerUser[0], SecuritySettings.ControllerPassword[0], LWTTopic.c_str(), 0, 1, "Connection Lost");
if ((SecuritySettings.ControllerUser[controller_idx] != 0) && (SecuritySettings.ControllerPassword[controller_idx] != 0))
MQTTresult = MQTTclient.connect(clientid.c_str(), SecuritySettings.ControllerUser[controller_idx], SecuritySettings.ControllerPassword[controller_idx], LWTTopic.c_str(), 0, 0, "Connection Lost");
else
MQTTresult = MQTTclient.connect(clientid.c_str(), LWTTopic.c_str(), 0, 1, "Connection Lost");

Expand Down Expand Up @@ -184,9 +188,9 @@ void MQTTConnect()
/*********************************************************************************************\
* Check connection MQTT message broker
\*********************************************************************************************/
void MQTTCheck()
void MQTTCheck(int controller_idx)
{
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[controller_idx]);
if (Protocol[ProtocolIndex].usesMQTT)
{
if (!MQTTclient.connected() || WiFi.status() != WL_CONNECTED)
Expand All @@ -196,7 +200,7 @@ void MQTTCheck()
MQTTclient.disconnect();
if (WiFi.status() == WL_CONNECTED) {
delay(1000);
MQTTConnect();
MQTTConnect(controller_idx);
}
}
else if (connectionFailures)
Expand Down Expand Up @@ -226,17 +230,27 @@ void SendStatus(byte source, String status)
}
}

boolean MQTTpublish(int controller_idx, const char* topic, const char* payload, boolean retained)
{
if (MQTTclient.publish(topic, payload, retained))
return true;
addLog(LOG_LEVEL_DEBUG, F("MQTT : publish failed"));
MQTTConnect(controller_idx);
return false;
}

/*********************************************************************************************\
* Send status info back to channel where request came from
\*********************************************************************************************/
void MQTTStatus(String& status)
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings)); // todo index is now fixed to 0

String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
pubname.replace(F("%sysname%"), Settings.Name);
MQTTclient.publish(pubname.c_str(), status.c_str(),Settings.MQTTRetainFlag);
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
pubname.replace(F("%sysname%"), Settings.Name);
MQTTpublish(enabledMqttController, pubname.c_str(), status.c_str(),Settings.MQTTRetainFlag);
}
}
30 changes: 24 additions & 6 deletions src/ESPEasy.ino
Original file line number Diff line number Diff line change
Expand Up @@ -1002,9 +1002,11 @@ void setup()
portUDP.begin(Settings.UDPPort);

// Setup MQTT Client
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
if (Protocol[ProtocolIndex].usesMQTT && Settings.ControllerEnabled[0])
MQTTConnect();
// ToDo TD-er: Controller index is forced to the first enabled MQTT controller.
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
MQTTConnect(enabledMqttController);
}

sendSysInfoUDP(3);

Expand All @@ -1031,6 +1033,16 @@ void setup()

}

int firstEnabledMQTTController() {
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[i]);
if (Protocol[ProtocolIndex].usesMQTT && Settings.ControllerEnabled[i]) {
return i;
}
}
return -1;
}


/*********************************************************************************************\
* MAIN LOOP
Expand Down Expand Up @@ -1074,8 +1086,10 @@ void loop()
}

//dont do this in backgroundtasks(), otherwise causes crashes. (https://github.com/letscontrolit/ESPEasy/issues/683)
if(Settings.ControllerEnabled[0])
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
MQTTclient.loop();
}

backgroundtasks();

Expand Down Expand Up @@ -1217,8 +1231,12 @@ void runEach30Seconds()
addLog(LOG_LEVEL_INFO, log);
sendSysInfoUDP(1);
refreshNodeList();
if(Settings.ControllerEnabled[0])
MQTTCheck();

int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
MQTTCheck(enabledMqttController);
}

#if defined(ESP8266)
if (Settings.UseSSDP)
SSDP_update();
Expand Down
5 changes: 1 addition & 4 deletions src/_C002.ino
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,8 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
pubname.replace(F("%tskname%"), ExtraTaskSettings.TaskDeviceName);
pubname.replace(F("%id%"), String(event->idx));

if (!MQTTclient.publish(pubname.c_str(), json.c_str(), Settings.MQTTRetainFlag))
if (!MQTTpublish(event->ControllerIndex, pubname.c_str(), json.c_str(), Settings.MQTTRetainFlag))
{
log = F("MQTT : publish failed");
addLog(LOG_LEVEL_DEBUG, log);
MQTTConnect();
connectionFailures++;
}
else if (connectionFailures)
Expand Down
3 changes: 2 additions & 1 deletion src/_C005.ino
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
value = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
else
value = formatUserVar(event, x);
MQTTclient.publish(tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);

MQTTpublish(event->ControllerIndex, tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
String log = F("MQTT : ");
log += tmppubname;
log += " ";
Expand Down
2 changes: 1 addition & 1 deletion src/_C006.ino
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
value = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
else
value = formatUserVar(event, x);
MQTTclient.publish(tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
MQTTpublish(event->ControllerIndex, tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
}
break;
}
Expand Down
29 changes: 15 additions & 14 deletions src/_P037_MQTTImport.ino
Original file line number Diff line number Diff line change
Expand Up @@ -324,21 +324,23 @@ void mqttcallback_037(char* c_topic, byte* b_payload, unsigned int length)
// It would be nice to understand this....

boolean MQTTConnect_037(String clientid)

{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings)); // todo index is now fixed to 0

boolean result = false;

// @ToDo TD-er: Plugin allows for more than one MQTT controller, but we're now using only the first enabled one.
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController < 0) {
// No enabled MQTT controller
return false;
}
// Do nothing if already connected

if (MQTTclient_037->connected())return true;
if (MQTTclient_037->connected()) return true;

// define stuff for the client - this could also be done in the intial declaration of MQTTclient_037
if (WiFi.status() != WL_CONNECTED) {
return false; // Not connected, so no use in wasting time to connect to a host.
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
if (ControllerSettings.UseDNS) {
MQTTclient_037->setServer(ControllerSettings.getHost().c_str(), ControllerSettings.Port);
} else {
Expand All @@ -352,8 +354,8 @@ boolean MQTTConnect_037(String clientid)
{
String log = "";

if ((SecuritySettings.ControllerUser[0][0] != 0) && (SecuritySettings.ControllerPassword[0][0] != 0)) //
result = MQTTclient_037->connect(clientid.c_str(), SecuritySettings.ControllerUser[0], SecuritySettings.ControllerPassword[0]); // todo
if ((SecuritySettings.ControllerUser[enabledMqttController][0] != 0) && (SecuritySettings.ControllerPassword[enabledMqttController][0] != 0))
result = MQTTclient_037->connect(clientid.c_str(), SecuritySettings.ControllerUser[enabledMqttController], SecuritySettings.ControllerPassword[enabledMqttController]);
else
result = MQTTclient_037->connect(clientid.c_str());

Expand Down Expand Up @@ -453,20 +455,19 @@ float string2float(String myString) {
len = myString.length();
char tmp[(len + 1)]; // one extra for the zero termination
byte start = 0;

// Look for decimal point - they can be anywhere but no more than one of them!

int dotIndex = myString.indexOf(".");
int dotIndex = myString.indexOf('.');
//Serial.println(dotIndex);

if (dotIndex != -1)
{
int dotIndex2 = (myString.substring(dotIndex + 1)).indexOf(".");
int dotIndex2 = (myString.substring(dotIndex + 1)).indexOf('.');
//Serial.println(dotIndex2);
if (dotIndex2 != -1)return -999.00; // Give error if there is more than one dot
}

if (myString.substring(0, 1) == "-") {
if (myString.charAt(0) == '-') {
tmp[0] = '-';
start = 1; //allow a minus in front of string
}

Expand Down
5 changes: 5 additions & 0 deletions test/espcore.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
### low level logging and protocol handling

# normally you shouldnt need to look into this file too much

import logging
import colorlog
import config
Expand All @@ -18,6 +20,9 @@
### mqtt stuff
logging.getLogger("MQTT").debug("Connecting to {mqtt_broker}".format(mqtt_broker=config.mqtt_broker))


log=logging.getLogger("testcore")

mqtt_client = mqtt.Client()
mqtt_client.connect(config.mqtt_broker, 1883, 60)
mqtt_client.loop_start()
Expand Down
19 changes: 13 additions & 6 deletions test/espeasy.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,25 @@ def controller_domoticz_http(self, **kwargs):
""".format(**kwargs)
)

def recv_domoticz_http(self, sensor_type, timeout=60):
def recv_domoticz_http(self, sensor_type, idx, timeout=60):
"""recv a domoticz http request from espeasy, and convert back to espeasy values"""

start_time=time.time()
logging.getLogger("domoticz http").info("Waiting for request with sensortype {sensor_type}".format(sensor_type=sensor_type))
logging.getLogger("domoticz http").info("Waiting for request idx {idx} with sensortype {sensor_type}".format(sensor_type=sensor_type,idx=idx))

# read and parse http requests
while not http_requests.empty():
http_requests.get()

while time.time()-start_time<timeout:
request=http_requests.get(block=True, timeout=timeout)
if request.path == "/json.html":
if reuqest.params.get('param')=='udevice':
svalues=request.params.get('svalue').split(";")
if request.path == "/json.htm" and int(request.params.get('idx'))==idx:
if request.params.get('param')=='udevice':
svalues_str=request.params.get('svalue').split(";")
svalues=[]
for svalue in svalues_str:
svalues.append(float(svalue))

if sensor_type==SENSOR_TYPE_SINGLE and len(svalues)==1:
return svalues
elif sensor_type==SENSOR_TYPE_DUAL and len(svalues)==2:
Expand All @@ -122,7 +129,7 @@ def recv_domoticz_http(self, sensor_type, timeout=60):
elif request.params.get('switchcmd') == 'On':
return [1]
elif request.params.get('switchcmd') == 'Set Level':
return [request.params.get('level')]
return [int(request.params.get('level'))]

raise(Exception("Timeout"))

Expand Down
Loading

0 comments on commit a6ea35e

Please sign in to comment.