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

99 lines
3.2 KiB
C#

using System;
using ln.http;
using ln.http.api;
using ln.http.api.attributes;
using ln.json;
namespace ln.ethercat.service.api.v1
{
public class EthercatApiController : WebApiController
{
ECMaster ECMaster => EthercatService.ECMaster;
EthercatService EthercatService;
public EthercatApiController(EthercatService ethercatService)
{
EthercatService = ethercatService;
}
[GET("/slaves")]
public int GetSlaveCount() => ECMaster.CountSlaves;
[GET("/slaves/:slave_id/sdo")]
public HttpResponse GetServiceDescriptors(UInt16 slave_id)
{
if (ECMaster.GetSlave(slave_id, out ECSlave slave))
{
JSONArray descriptorList = new JSONArray();
foreach (SDODescriptor sdoDescriptor in slave.GetSDODescriptors())
{
descriptorList.Add(new JSONObject()
.Add("slave", sdoDescriptor.SlaveId)
.Add("index", sdoDescriptor.Index)
.Add("datatype", sdoDescriptor.DataType.ToString())
.Add("objectcode", sdoDescriptor.ObjectCode.ToString())
.Add("name", sdoDescriptor.Name)
);
}
return HttpResponse.OK().Content(descriptorList);
}
return HttpResponse.NoContent();
}
[GET("/slaves/:slave/state")]
public HttpResponse GetEthercatState(int slave) => HttpResponse.OK().Content(ECMaster.ReadSlaveState(slave).ToString());
[GET("/master/state")]
public HttpResponse GetFullState()
{
JSONArray slaveStates = new JSONArray();
for (int slave=1; slave <= ECMaster.CountSlaves; slave++)
{
slaveStates.Add(new JSONObject()
.Add("id", new JSONNumber(slave))
.Add("state", new JSONString(ECMaster.ReadSlaveState(slave).ToString()))
);
}
JSONObject fullState = new JSONObject()
.Add("bus_state", new JSONString(ECMaster.EthercatState.ToString()))
.Add("slaves", slaveStates)
;
return HttpResponse.OK().Content(fullState);
}
[GET("/master/pdomap")]
public PDO[] GetPDOMap() => ECMaster.GetPDOMap();
[POST("/master/action")]
public HttpResponse PostMasterAction(string action)
{
switch (action)
{
case "stop":
ECMaster.Stop();
return HttpResponse.NoContent();
case "start":
ECMaster.Start();
return HttpResponse.NoContent();
default:
return HttpResponse.BadRequest().Content(string.Format("{0} is no valid action", action));
}
}
[GET("/socket")]
HttpResponse OpenWebSocket(HttpRequest httpRequest) => new EthercatWebSocket(EthercatService);
[GET("")]
HttpResponse OpenRecorderSocket(HttpRequest httpRequest) => new RecorderWebSocket(EthercatService.ProcessDataRecorder);
}
}