Skip to content
This repository has been archived by the owner on Jul 4, 2023. It is now read-only.

Commit

Permalink
Change powerSwitch and Light control to mqtt
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian Benjamin Ries committed Jun 21, 2023
1 parent 014e86e commit c3c2f32
Show file tree
Hide file tree
Showing 10 changed files with 224 additions and 84 deletions.
40 changes: 29 additions & 11 deletions EcosApp/index.js
Expand Up @@ -214,6 +214,21 @@ function relayWebsocketCommand(data) {
});
}

function triggerMqttMessage(data) {
var srv = window.serverHandling;
if (typeof srv === "undefined" || srv == null)
return; // TODO show error

// data.mode := string ['mqtt', ...]
// data.data := object, binary, etc.

srv.sendCommand({
"command": "mqtt",
"timestamp": Date.now(),
"cmddata": data
});
}

function removeTextfieldFromGlobalList(uniqueId) {
if (uniqueId == null)
return;
Expand Down Expand Up @@ -461,13 +476,17 @@ $(document).ready(function () {

window.dialogLightAndPower = new LightAndPower();
window.dialogLightAndPower.install();
window.dialogLightAndPower.on('relayCommand', function (ev) {
let fncPowerLightChanged = function (ev) {
const data = ev.data;
if (data.mode === "websocket")
relayWebsocketCommand(data);
else
console.log("TODO unknown relay mode: " + data.mode);
});
if (data.mode === "mqtt") {
triggerMqttMessage(data);
}
else {
console.log("TODO unknown data mode: " + data.mode);
}
};
window.dialogLightAndPower.on('powerSwitchesChanged', fncPowerLightChanged);
window.dialogLightAndPower.on('lightChanged', fncPowerLightChanged);

window.dialogS88 = new FeedbackVisualization();
window.dialogS88.install();
Expand Down Expand Up @@ -732,29 +751,28 @@ $(document).ready(function () {
const state = jsonCommand.data.state;
if (typeof state === "undefined" || state == null) break;

const fncClearGhost = function() {
const fncClearGhost = function () {
const allFbItems = $('div.ctrlItemFeedback[id]');
const iMax = allFbItems.length;
for (let i = 0; i < iMax; ++i) {
$(allFbItems[i]).removeClass("ghost");
}
}

const fncHideGhostOverlay = function() {
const fncHideGhostOverlay = function () {
$('.overlayGhost').hide();
$('.overlayGhostText').hide();
}

const fncShowGhostOverlay = function(message) {
const fncShowGhostOverlay = function (message) {
$('.overlayGhost').show();
$('.overlayGhostText').html(message);
$('.overlayGhostText').show();
}

if (typeof state.found === "undefined"
|| state.found == null
|| state.found === false)
{
|| state.found === false) {
fncClearGhost();
fncHideGhostOverlay();
} else {
Expand Down
4 changes: 2 additions & 2 deletions EcosApp/railessentials.min.js

Large diffs are not rendered by default.

56 changes: 30 additions & 26 deletions EcosApp/src/lightAndPower.js
Expand Up @@ -352,29 +352,32 @@ class LightAndPower {
const self = this;
const dataToSend = self.__getRgbStripesObject();

self.__trigger('relayCommand',
self.__trigger('lightChanged',
{
'mode': 'websocket',
'target': this.__rgbStripesIpAddr,
'contentType': 'application/json',
'mode': 'mqtt',
'data': dataToSend
});
}

__getRgbStripesObject() {
let rgbW = { r: 255, g: 255, b: 255, w: 1023 };
let rgbW = {
"Haus/Railway/Sky/R": 255,
"Haus/Railway/Sky/G": 255,
"Haus/Railway/Sky/B": 255,
"Haus/Railway/Sky/W": 1023
};
if ($('#rgbColorMorningRadio').is(":checked") === true) {
rgbW = hexToRgbA($('#rgbColorMorning').val());
rgbW.w = 200;
rgbW = hexToRgbA('Haus/Railway/Sky/', $('#rgbColorMorning').val());
rgbW['Haus/Railway/Sky/W'] = 200;
} else if ($('#rgbColorNoonRadio').is(":checked") === true) {
rgbW = hexToRgbA($('#rgbColorNoon').val());
rgbW.w = 1023;
rgbW = hexToRgbA('Haus/Railway/Sky/', $('#rgbColorNoon').val());
rgbW['Haus/Railway/Sky/W'] = 1023;
} else if ($('#rgbColorAfternoonRadio').is(":checked") === true) {
rgbW = hexToRgbA($('#rgbColorAfternoon').val());
rgbW.w = 500;
rgbW = hexToRgbA('Haus/Railway/Sky/', $('#rgbColorAfternoon').val());
rgbW['Haus/Railway/Sky/W'] = 500;
} else if ($('#rgbColorNightRadio').is(":checked") === true) {
rgbW = hexToRgbA($('#rgbColorNight').val());
rgbW.w = 100;
rgbW = hexToRgbA('Haus/Railway/Sky/', $('#rgbColorNight').val());
rgbW['Haus/Railway/Sky/W'] = 100;
}

return rgbW;
Expand All @@ -383,22 +386,23 @@ class LightAndPower {
__sendPowerSwitch() {
const self = this;
const dataToSend = {
"in1": $('#powerChkIn1').is(":checked"),
"in2": $('#powerChkIn2').is(":checked"),
"in3": $('#powerChkIn3').is(":checked"),
"in4": $('#powerChkIn4').is(":checked"),

//"in1delay": parseInt($('#powerChkIn1DelaySecs').val()),
//"in2delay": parseInt($('#powerChkIn2DelaySecs').val()),
//"in3delay": parseInt($('#powerChkIn3DelaySecs').val()),
//"in4delay": parseInt($('#powerChkIn4DelaySecs').val())
"Haus/Switches/Railway01": $('#powerChkIn1').is(":checked"),
"Haus/Switches/Railway02": $('#powerChkIn2').is(":checked"),
"Haus/Switches/Railway03": $('#powerChkIn3').is(":checked"),
"Haus/Switches/Railway04": $('#powerChkIn4').is(":checked"),
};

self.__trigger('relayCommand',
// MQTT
// Haus/Switches/Railway01 True|False
// Haus/Switches/Railway02 True|False
// Haus/Switches/Railway03 True|False
// Haus/Switches/Railway04 True|False
// Haus/Switches/Off
// Haus/Switches/On

self.__trigger('powerSwitchesChanged',
{
'mode': 'websocket',
'target': this.__powerPlugIpAddr,
'contentType': 'application/json',
'mode': 'mqtt',
'data': dataToSend
});
}
Expand Down
22 changes: 14 additions & 8 deletions EcosApp/src/utilities.js
Expand Up @@ -62,7 +62,7 @@ returned value: (String)
rgba(251,175,255,1)
hexToRgbA('#fbafff')
*/
function hexToRgbA(hex) {
function hexToRgbA(topic, hex) {
if (hex.charAt(0) !== '#')
hex = '#' + hex;
var c;
Expand All @@ -72,13 +72,19 @@ function hexToRgbA(hex) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
//return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
return {
r: (c >> 16) & 255,
g: (c >> 8) & 255,
b: c & 255,
w: 1023
};

var r = topic + 'R';
var g = topic + 'G';
var b = topic + 'B';
var w = topic + 'W';

var o = {};
o[r] = (c >> 16) & 255;
o[g] = (c >> 8) & 255;
o[b] = c & 255;
o[w] = 1023;

return o;
}
throw new Error('Bad Hex');
}
Expand Down
37 changes: 14 additions & 23 deletions railessentials/ClientHandler/ClientHandler.Shutdown.cs
Expand Up @@ -12,7 +12,6 @@ namespace railessentials.ClientHandler
public partial class ClientHandler
{
private const string TargetUriRgbStripes = "ws://192.168.178.66:81";
private const string TargetUriSteckdosen = "ws://192.168.178.62:81";

private void ShutdownHandler()
{
Expand All @@ -26,32 +25,24 @@ private void ShutdownHandler()

private void __switchOffSteckdosen()
{
var states = new JObject
{
["in1"] = false,
["in2"] = false,
["in3"] = false,
["in4"] = false
};

var r = RelayCommandWebsocket.Send(TargetUriSteckdosen, states.ToString(Formatting.None));
if(!r.Result)
SendDebug(DebugMessage.Instance($"{r.LastError}", DebugMessageLevel.Error));
_mqtt?.Send("Haus/Switches/Off", string.Empty);
}

private void __resetRgbLight()
{
var states = new JObject
{
["r"] = 255,
["g"] = 255,
["b"] = 255,
["w"] = 1023
};

var r = RelayCommandWebsocket.Send(TargetUriRgbStripes, states.ToString(Formatting.None));
if (!r.Result)
SendDebug(DebugMessage.Instance($"{r.LastError}", DebugMessageLevel.Error));
_mqtt?.Send("Haus/Railway/Sky/On", string.Empty);

//var states = new JObject
//{
// ["r"] = 255,
// ["g"] = 255,
// ["b"] = 255,
// ["w"] = 1023
//};

//var r = RelayCommandWebsocket.Send(TargetUriRgbStripes, states.ToString(Formatting.None));
//if (!r.Result)
// SendDebug(DebugMessage.Instance($"{r.LastError}", DebugMessageLevel.Error));
}
}
}
55 changes: 41 additions & 14 deletions railessentials/ClientHandler/ClientHandler.cs
Expand Up @@ -4,8 +4,6 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using ecoslib;
Expand All @@ -16,6 +14,7 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using railessentials.Feedbacks;
using railessentials.mqtt;
using railessentials.Plan;
using railessentials.Route;
using SuperWebSocket;
Expand All @@ -38,6 +37,7 @@ public partial class ClientHandler
{
internal ClientHandlerCfg _cfg;
internal Sniffer _sniffer;
internal Mqtt _mqtt;
private JArray _themeData;
internal Metadata _metadata;
internal readonly object _metadataLock = new();
Expand Down Expand Up @@ -66,6 +66,8 @@ public void SaveAll()
_metadata = metadata;
_themeData = themeData;

_mqtt = new Mqtt(_cfg.Cfg.Mqtt, _sniffer?.Logger);

Logger = _sniffer?.Logger;

if (_sniffer?.GetWsServer() is WsServer wsServer)
Expand All @@ -76,38 +78,32 @@ public void SaveAll()
}

if (_sniffer is { IsSimulationMode: true })
{
InitializeSystemHandler();
}

InitAccessoryBw();
}

private bool PersistEcosData(JObject jsonObj, out string errorMessage)
private void PersistEcosData(JToken jsonObj)
{
try
{
var p = Program.Cfg.SimulationData;
var pd = Path.GetDirectoryName(p);
if (string.IsNullOrEmpty(pd))
{
errorMessage = "Invalid directory path for Ecos simulation data.";
return false;
return;
}
if (!Directory.Exists(pd))
Directory.CreateDirectory(pd);

var prettyJsonStr = jsonObj.ToString(Formatting.Indented);
File.WriteAllText(Program.Cfg.SimulationData, prettyJsonStr, Encoding.UTF8);

errorMessage = string.Empty;

return true;
return;
}
catch (Exception ex)
{
errorMessage = ex.Message;
return false;
return;
}
}

Expand All @@ -124,7 +120,7 @@ public void HandleEcosData()
{
lock (_metadataLock)
{
PersistEcosData(_metadata.EcosData, out _);
PersistEcosData(_metadata.EcosData);
}
}

Expand Down Expand Up @@ -258,6 +254,13 @@ private void WsServerOnMessageReceived(object sender, MessageEventArgs eventargs
}
break;

case "mqtt":
{
var cmddata = GetCmdData(json);
HandleMqttCommand(cmddata);
}
break;

case "autoMode":
{
var cmddata = GetCmdData(json);
Expand Down Expand Up @@ -1212,6 +1215,30 @@ private void HandleSettingCommand(JObject cmddata)
_sniffer?.SendCommandsToEcosStation();
}

private void HandleMqttCommand(JObject cmddata)
{
var mode = cmddata.GetString("mode")?.ToLower();
if (string.IsNullOrEmpty(mode)) return;

if (mode.Equals("mqtt", StringComparison.OrdinalIgnoreCase))
{
if (cmddata["data"] is not JObject topics) return;

foreach (var it in topics)
{
var topic = it.Key;

if (string.IsNullOrEmpty(topic)) continue;

_mqtt?.Send(topic, it.Value?.ToString());
}

return;
}

SendDebug(DebugMessage.Instance($"RelayCommand mode '{mode}' is unknown.", DebugMessageLevel.Warning));
}

private void HandleRelayCommand(JObject cmddata)
{
var mode = cmddata.GetString("mode")?.ToLower();
Expand Down Expand Up @@ -1497,7 +1524,7 @@ internal void StopAllLocomotives()
foreach (var it in objs)
{
var itLoc = it as Locomotive;
if(IsSimulationMode())
if (IsSimulationMode())
itLoc?.StopSimulation();
else
itLoc?.Stop();
Expand Down

0 comments on commit c3c2f32

Please sign in to comment.