using System; using System.IO; using System.Timers; using ln.application; using ln.ethercat.service.api.v1; using ln.http; using ln.http.api; using ln.http.router; using ln.logging; using ln.type; namespace ln.ethercat.service { public class EthercatService { public ECMaster ECMaster { get; private set; } [StaticArgument(Option = 'i', LongOption = "interface")] public string EthercatInterfaceName { get; set; } [StaticArgument(LongOption = "web-root")] public string WebRootPath { get; set; } HTTPServer httpServer; LoggingRouter httpLoggingRouter; SimpleRouter httpRouter; StaticRouter staticRouter; StaticRouter templateRouter; EthercatApiController apiController; ControllerApiController controllerApiController; System.Timers.Timer timerWebsockets; EthercatProcessDataRecorder processDataRecorder; public EthercatProcessDataRecorder ProcessDataRecorder { get { if (processDataRecorder == null) processDataRecorder = new EthercatProcessDataRecorder(ECMaster); return processDataRecorder; } } public EthercatService(){} public void Initialize() { if (EthercatInterfaceName == null) throw new ArgumentNullException(nameof(EthercatInterfaceName)); if (WebRootPath == null) WebRootPath = AppContext.BaseDirectory; ECMaster = new ECMaster(EthercatInterfaceName); ECMaster.OnStateChange += MasterStateChanged; httpRouter = new SimpleRouter(); httpLoggingRouter = new LoggingRouter(httpRouter); apiController = new EthercatApiController(this); httpRouter.AddSimpleRoute("/api/v1/*", apiController); staticRouter = new StaticRouter(Path.Combine(WebRootPath, "www", "static")); httpRouter.AddSimpleRoute("/*", staticRouter); templateRouter = new StaticRouter(Path.Combine(WebRootPath, "www", "html")); templateRouter.AddIndex("spa.html"); httpRouter.AddSimpleRoute("/*", templateRouter); httpServer = new HTTPServer(httpLoggingRouter); httpServer.AddEndpoint(new Endpoint(IPv6.ANY, 7676)); httpServer.AddEndpoint(new Endpoint(IPv6.V4Space, 7676)); controllerApiController = new ControllerApiController(ECMaster.Controller); httpRouter.AddSimpleRoute("/api/v1/*", controllerApiController); timerWebsockets = new System.Timers.Timer(250); timerWebsockets.Elapsed += WebSocketTimerMethod; } public void Start() { httpServer.Start(); ECMaster.Start(); timerWebsockets.Start(); } void WebSocketTimerMethod(object sender, ElapsedEventArgs e) { try{ EthercatWebSocket.SendProcessData(ECMaster); ControllerWebSocket.SendUpdates(ECMaster.Controller); JSONEventWebSocketResponse.SendUpdates(); } catch (Exception ex) { Logging.Log(ex); } } void MasterStateChanged(ECMaster sender,ECSlaveState newState) { switch (newState) { case ECSlaveState.OPERATIONAL: //Controller.Start(); break; default: //Controller.Stop(); break; } } } }