115 lines
3.7 KiB
C#
115 lines
3.7 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using ln.ethercat.controller;
|
|
using ln.ethercat.controller.drives;
|
|
using ln.http.websocket;
|
|
using ln.json;
|
|
using ln.logging;
|
|
|
|
namespace ln.ethercat.service.api.v1
|
|
{
|
|
public class ControllerWebSocket : WebSocketResponse
|
|
{
|
|
static List<ControllerWebSocket> webSockets = new List<ControllerWebSocket>();
|
|
static bool sendingUpdates;
|
|
public static void SendUpdates(Controller controller)
|
|
{
|
|
lock (webSockets)
|
|
{
|
|
if (sendingUpdates)
|
|
return;
|
|
sendingUpdates = true;
|
|
}
|
|
|
|
try
|
|
{
|
|
|
|
JSONArray jsonDriveControllers = new JSONArray();
|
|
|
|
foreach (DriveController driveController in controller.ECMaster.DriveControllers)
|
|
{
|
|
JSONObject jsonDriveController =
|
|
new JSONObject()
|
|
.Add("DriveState", driveController.DriveState.ToString())
|
|
.Add("OEMState", driveController.OEMDriveState)
|
|
.Add("DriveMode", driveController.DriveMode.ToString())
|
|
.Add("TargetValue", driveController.TargetValue)
|
|
.Add("ActualSpeed", driveController.ActualSpeed)
|
|
.Add("ActualTorque", driveController.ActualTorque)
|
|
.Add("ActualLoad", driveController.ActualLoad)
|
|
;
|
|
|
|
jsonDriveControllers.Add(jsonDriveController);
|
|
}
|
|
|
|
JSONObject jsonController =
|
|
new JSONObject()
|
|
.Add("State", controller.ControllerState.ToString())
|
|
.Add("Drives", jsonDriveControllers)
|
|
.Add("CycleCounter", controller.CycleCounter)
|
|
;
|
|
|
|
|
|
JSONObject jsonMessage =
|
|
new JSONObject()
|
|
.Add("event", "update")
|
|
.Add("value", jsonController)
|
|
;
|
|
|
|
string jsonMessageText = jsonMessage.ToString();
|
|
|
|
ControllerWebSocket[] currentSockets;
|
|
lock (webSockets)
|
|
currentSockets = webSockets.ToArray();
|
|
|
|
foreach (ControllerWebSocket webSocket in currentSockets)
|
|
{
|
|
if (webSocket.Controller.Equals(controller) && (webSocket.State == WebSocketState.OPEN))
|
|
webSocket.Send(jsonMessageText);
|
|
}
|
|
} catch (Exception e)
|
|
{
|
|
Logging.Log(e);
|
|
} finally
|
|
{
|
|
sendingUpdates = false;
|
|
}
|
|
}
|
|
|
|
Controller Controller;
|
|
|
|
public ControllerWebSocket(Controller controller)
|
|
{
|
|
Controller = controller;
|
|
OnWebSocketStateChanged += (WebSocketResponse webSocket, WebSocketState newState) => {
|
|
switch (newState)
|
|
{
|
|
case WebSocketState.OPEN:
|
|
lock (webSockets)
|
|
webSockets.Add(this);
|
|
break;
|
|
default:
|
|
lock (webSockets)
|
|
webSockets.Remove(this);
|
|
break;
|
|
}
|
|
};
|
|
}
|
|
|
|
|
|
public override void Received(string textMessage)
|
|
{
|
|
base.Received(textMessage);
|
|
|
|
JSONValue jsonTextValue = JSONParser.Parse(textMessage);
|
|
if (jsonTextValue is JSONObject jsonMessage)
|
|
{
|
|
string eventName = jsonMessage["event"].ToNative().ToString();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|
|
} |