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

104 lines
3.2 KiB
C#

using System.Linq;
using System.Runtime.CompilerServices;
using ln.http;
using ln.http.api;
using ln.http.api.attributes;
using ln.json;
using ln.json.mapping;
using ln.logging;
namespace ln.ethercat.service.api.v1
{
public class EthercatApiController : WebApiController
{
ECMaster ECMaster;
public EthercatApiController(ECMaster ecMaster)
{
ECMaster = ecMaster;
}
[GET("/slaves")]
public int GetSlaveCount() => ECMaster.CountSlaves;
[GET("/slaves/:slave/sdo/:index/:subindex")]
[GET("/slaves/:slave/sdo/:index")]
public HttpResponse ReadSDO(int slave,int index,int subindex = 0)
{
if (ECMaster.GetSDO(new SDOAddr(slave, index, subindex), out SDO sdo))
{
Logging.Log(LogLevel.DEBUG, "SDO updated: {0}", sdo);
return HttpResponse
.OK()
.Content(JSONMapper.DefaultMapper.ToJson(sdo))
.ContentType("application/json")
;
}
return HttpResponse.RequestTimeout().Content("master could not read from slave");
}
[GET("/slaves/:slave/sdo")]
public SDO[] GetServiceDescriptors(int slave)
{
return ECMaster.GetSDOs(slave).ToArray();
}
[GET("/slaves/:slave/state")]
public HttpResponse GetEthercatState(int slave) => HttpResponse.OK().Content(ECMaster.ReadSlaveState(slave).ToString());
[POST("/slaves/:slave/state")]
public HttpResponse RequestEthercatState(int slave, ECSlaveState state)
{
if (ECMaster.RequestSlaveState(slave, state) > 0)
return HttpResponse.NoContent();
return HttpResponse.GatewayTimeout();
}
[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();
[GET("/master/pdos")]
public SDO[] GetPDOs() => ECMaster.GetPDOMap().Select((pdo)=>pdo.SDO).ToArray();
[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));
}
}
}
}