ln.ethercat/ln.ethercat.service/api/v1/RecorderWebSocket.cs

64 lines
2.2 KiB
C#

using System.Net.Http;
using ln.http.api;
using ln.http.websocket;
using ln.json;
using ln.json.mapping;
namespace ln.ethercat.service.api.v1
{
public class RecorderWebSocket : JSONEventWebSocketResponse
{
EthercatProcessDataRecorder DataRecorder;
public RecorderWebSocket(EthercatProcessDataRecorder dataRecorder)
{
OnWebSocketStateChanged += (s,state)=>{
switch (state)
{
case WebSocketState.OPEN:
dataRecorder.OnRecordingWindowCompleted += RecordingWindowCompleted;
dataRecorder.OnStartRecording += RecordingStarted;
dataRecorder.OnStopRecording += RecordingStopped;
break;
case WebSocketState.CLOSED:
dataRecorder.OnStartRecording -= RecordingStarted;
dataRecorder.OnStopRecording -= RecordingStopped;
dataRecorder.OnRecordingWindowCompleted -= RecordingWindowCompleted;
break;
}
};
}
void RecordingStarted(EthercatProcessDataRecorder recorder)
{
JSONObject jsonMessage = new JSONObject();
jsonMessage.Add("event","start");
if (JSONMapper.DefaultMapper.Serialize(recorder.CurrentPDOMap, out JSONValue jsonValue))
jsonMessage.Add("value", jsonValue);
Send(jsonMessage);
}
void RecordingStopped(EthercatProcessDataRecorder recorder)
{
JSONObject jsonMessage = new JSONObject();
jsonMessage.Add("event","stop");
jsonMessage.Add("value", JSONNull.Instance);
Send(jsonMessage);
}
void RecordingWindowCompleted(EthercatProcessDataRecorder recorder, EthercatProcessDataRecorder.RecordingWindow recordingWindow)
{
JSONObject jsonMessage = new JSONObject();
jsonMessage.Add("event","window");
if (JSONMapper.DefaultMapper.Serialize(recordingWindow.GetRecords(), out JSONValue jsonRecords))
jsonMessage.Add("value", jsonRecords);
Send(jsonMessage);
}
}
}