diff --git a/Libs/CMS_CORE_Library.dll b/Libs/CMS_CORE_Library.dll index ea86433e..59d8545e 100644 Binary files a/Libs/CMS_CORE_Library.dll and b/Libs/CMS_CORE_Library.dll differ diff --git a/Step.Database/Controllers/UsersController.cs b/Step.Database/Controllers/UsersController.cs index 9d49289f..ec0880a7 100644 --- a/Step.Database/Controllers/UsersController.cs +++ b/Step.Database/Controllers/UsersController.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Linq; using System.Web.Helpers; using Step.Model.DatabaseModels; +using Step.Model.DTOModels; namespace Step.Database.Controllers { @@ -36,6 +37,7 @@ namespace Step.Database.Controllers // Create a new user model with params return new UserModel() { + UserId = id, Username = username, Password = Crypto.HashPassword(password), FirstName = firstName, @@ -50,22 +52,38 @@ namespace Step.Database.Controllers return CreateUserModel(0, username, password, firstName, lastName, roleId, language); } - public UserModel Find(int id) + public DTOUserModel GetUserInfo(int id) + { + // Find user by Id with Role object included + UserModel userDatabaseModel = dbCtx.Users.Include("Role").Where(u => u.UserId == id).FirstOrDefault(); + + return new DTOUserModel() + { + Id = userDatabaseModel.UserId, + Username = userDatabaseModel.Username, + FirstName = userDatabaseModel.FirstName, + LastName = userDatabaseModel.LastName, + Language = userDatabaseModel.Language, + RoleId = userDatabaseModel.RoleId + }; + } + + public UserModel FindById(int id) { // Find user by Id with Role object included return dbCtx.Users.Include("Role").Where(u => u.UserId == id).FirstOrDefault(); } - public UserModel Find(string username) + private UserModel FindByUsername(string username) { // Find user by Id with Role object included return dbCtx.Users.Include("Role").Where(u => u.Username == username).FirstOrDefault(); } - public UserModel Find(string username, string password) + public UserModel FindByUsernameAndPassword(string username, string password) { // Find if username exists - UserModel user = Find(username); + UserModel user = FindByUsername(username); if (user != null) { diff --git a/Step.Database/Migrations/Configuration.cs b/Step.Database/Migrations/Configuration.cs index 113665ad..6b5a18da 100644 --- a/Step.Database/Migrations/Configuration.cs +++ b/Step.Database/Migrations/Configuration.cs @@ -13,7 +13,6 @@ namespace Step.Database.Migrations public Configuration() { AutomaticMigrationsEnabled = true; - } protected override void Seed(DatabaseContext context) @@ -25,12 +24,14 @@ namespace Step.Database.Migrations ); context.FunctionsAccess.AddOrUpdate( new FunctionAccessModel() { FunctionAccessId = 1, Name = "test", Area = "production", Enabled = true, WriteLevelMin = 7, ReadLevelMin = 1 }, - new FunctionAccessModel() { FunctionAccessId = 2, Name = "ncData", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 }, - new FunctionAccessModel() { FunctionAccessId = 3, Name = "functionAccess", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 } + new FunctionAccessModel() { FunctionAccessId = 2, Name = "userData", Area = "production", Enabled = true, WriteLevelMin = 1, ReadLevelMin = 1 }, + new FunctionAccessModel() { FunctionAccessId = 3, Name = "ncData", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 }, + new FunctionAccessModel() { FunctionAccessId = 4, Name = "functionAccess", Area = "production", Enabled = true, WriteLevelMin = 100, ReadLevelMin = 1 } ); + context.Users.AddOrUpdate ( - UsersController.CreateUserModel("cms", "cms", "cms", "cms", 1, new CultureInfo("en")) + UsersController.CreateUserModel(1, "cms", "cms", "cms", "cms", 1, new CultureInfo("en")) ); } } diff --git a/Step.NC/NcHandler.cs b/Step.NC/NcHandler.cs index da9b3b60..ade68def 100644 --- a/Step.NC/NcHandler.cs +++ b/Step.NC/NcHandler.cs @@ -10,6 +10,7 @@ using CMS_CORE.Osai; using Step.Model.DTOModels; using System.Globalization; using static Step.Utils.ExceptionManager; +using static CMS_CORE.Nc; namespace Step.NC { @@ -19,16 +20,17 @@ namespace Step.NC public NcHandler() { - // Choose NC numericalControl = SetNumericalControl(); } - public void Connect() + public CmsError Connect() { // Connect NC if (!numericalControl.NC_IsConnected()) - numericalControl.NC_Connect(); + return numericalControl.NC_Connect(); + + return null; } @@ -44,57 +46,81 @@ namespace Step.NC case NC_VENDOR.SIEMENS: return new Nc_Siemens(2000); case NC_VENDOR.OSAI: - return new Nc_Osai(NcConfig.NcIpAddress, NcConfig.NcPort, 2); + return new Nc_Osai(NcConfig.NcIpAddress, NcConfig.NcPort, 2000); } return null; } - public DTONcGenericDataModel GetNcGenericData() + public CmsError GetNcGenericData(out DTONcGenericDataModel genericData) { - DTONcGenericDataModel genericData = new DTONcGenericDataModel(); + genericData = new DTONcGenericDataModel(); // Get date time DateTime dateTime = new DateTime(); - numericalControl.NC_RDateTime(ref dateTime); + CmsError cmsError = numericalControl.NC_RDateTime(ref dateTime); + if (cmsError.errorCode != 0) + return cmsError; + genericData.DateTime = dateTime; // Get language CultureInfo lang = new CultureInfo("en"); - numericalControl.NC_RLanguage(ref lang); + cmsError = numericalControl.NC_RLanguage(ref lang); + if (cmsError.errorCode != 0) + return cmsError; + genericData.Language = lang; string tmpInfo = ""; // Get serial number - numericalControl.NC_RSerialNumber(ref tmpInfo); + cmsError = numericalControl.NC_RSerialNumber(ref tmpInfo); + if (cmsError.errorCode != 0) + return cmsError; + genericData.SerialNumber = tmpInfo; // Get software version numericalControl.NC_RSoftwareVersion(ref tmpInfo); + if (cmsError.errorCode != 0) + return cmsError; + genericData.SoftwareVersion = tmpInfo; // Get model name numericalControl.NC_RModelName(ref tmpInfo); + if (cmsError.errorCode != 0) + return cmsError; + genericData.Model = tmpInfo; // Get machine number numericalControl.NC_RMachineNumber(ref tmpInfo); + if (cmsError.errorCode != 0) + return cmsError; + genericData.MachineNumber = tmpInfo; // Get max process number ushort procNum = 0; numericalControl.NC_RProcessesNum(ref procNum); + if (cmsError.errorCode != 0) + return cmsError; + genericData.ProcessNumber = procNum; - return genericData; + return cmsError; } - public DTOAlarmsModel GetNcAlarms() + public CmsError GetNcAlarms(out DTOAlarmsModel alarms) { - DTOAlarmsModel alarms = new DTOAlarmsModel(); + alarms = new DTOAlarmsModel(); List tmpAlarms = new List(); + // Read NC active alarms - numericalControl.NC_RActiveAlarms(ref tmpAlarms); + CmsError cmsError = numericalControl.NC_RActiveAlarms(ref tmpAlarms); + if (cmsError.errorCode != 0) + return cmsError; // Create response list from strings foreach (string alarmMessage in tmpAlarms) @@ -107,7 +133,9 @@ namespace Step.NC // Get NC max process number ushort maxProcNumber = 0; - numericalControl.NC_RProcessesNum(ref maxProcNumber); + cmsError = numericalControl.NC_RProcessesNum(ref maxProcNumber); + if (cmsError.errorCode != 0) + return cmsError; // For each process for (ushort i = 1; i <= maxProcNumber; i++) @@ -126,7 +154,10 @@ namespace Step.NC } // Read PLC Active Messages - numericalControl.PLC_RActiveMessages(ref tmpAlarms); + cmsError = numericalControl.PLC_RActiveMessages(ref tmpAlarms); + if (cmsError.errorCode != 0) + return cmsError; + // Formatting response list from strings foreach (string alarmMessage in tmpAlarms) { @@ -136,41 +167,57 @@ namespace Step.NC }); } - return alarms; + return cmsError; } - public List GetAxesPositions() + public CmsError GetAxesPositions(out List axes) { - List axes = new List(); + axes = new List(); + // Get NC max process number ushort maxProcNumber = 0; - numericalControl.NC_RProcessesNum(ref maxProcNumber); + CmsError cmsError = numericalControl.NC_RProcessesNum(ref maxProcNumber); + if (cmsError.errorCode != 0) + return cmsError; // For each process for (ushort i = 1; i <= maxProcNumber; i++) { - DTOAxesModel axis = GetAxesPositionsByProcess(i); + cmsError = GetAxesPositionsByProcess(i, out DTOAxesModel axis); + if (cmsError.errorCode != 0) + return cmsError; axes.Add(axis); } - return axes; + return cmsError; } - public DTOAxesModel GetAxesPositionsByProcess(ushort processNum) + public CmsError GetAxesPositionsByProcess(ushort processNum, out DTOAxesModel axes) { + + axes = new DTOAxesModel(); - DTOAxesModel axes = new DTOAxesModel(); + CmsError cmsError = numericalControl.AXES_RInterpPosition(processNum, ref axes.interpolated); + if (cmsError.errorCode != 0) + return cmsError; - numericalControl.AXES_RInterpPosition(processNum, ref axes.interpolated); numericalControl.AXES_RMachinePosition(processNum, ref axes.machine); + if (cmsError.errorCode != 0) + return cmsError; + numericalControl.AXES_RProgrPosition(processNum, ref axes.programmePos); + if (cmsError.errorCode != 0) + return cmsError; + numericalControl.AXES_RDistanceToGo(processNum, ref axes.toGo); + if (cmsError.errorCode != 0) + return cmsError; //numericalControl.AXES_RFollowingError(1, ref axes.followingErr); - return axes; + return cmsError; } diff --git a/Step.Tasks/ThreadsFunctions.cs b/Step.Tasks/ThreadsFunctions.cs index e3fb62fb..1f023928 100644 --- a/Step.Tasks/ThreadsFunctions.cs +++ b/Step.Tasks/ThreadsFunctions.cs @@ -1,14 +1,13 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; -using CMS_CORE; using Step.Model.DTOModels; using TeamDev.SDK.MVVM; -using static Step.Utils.Constants; using Step.NC; -using System.Diagnostics; using Step.Core; +using static Step.Utils.Constants; +using static Step.Utils.ExceptionManager; +using static CMS_CORE.Nc; public static class ThreadsFunctions { @@ -26,7 +25,9 @@ public static class ThreadsFunctions if (ncHandler.numericalControl.NC_IsConnected()) { // Get Alarms from NC - DTOAlarmsModel alarms = ncHandler.GetNcAlarms(); + CmsError libraryError = ncHandler.GetNcAlarms(out DTOAlarmsModel alarms); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); // Send through signalR MessageServices.Current.Publish(SEND_ALARMS, null, alarms); } @@ -37,11 +38,6 @@ public static class ThreadsFunctions { ncHandler.Dispose(); } - catch (Exception ex) - { - ncHandler.Dispose(); - TryNcConnection(); - } } public static void ReadNcGenericInfo() @@ -49,16 +45,22 @@ public static class ThreadsFunctions NcHandler ncHandler = new NcHandler(); try { - ncHandler.Connect(); + CmsError libraryError = ncHandler.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + while (true) { if (ncHandler.numericalControl.NC_IsConnected()) { // Get Generic data from NC - DTONcGenericDataModel genericData = ncHandler.GetNcGenericData(); - // Send through signalR - MessageServices.Current.Publish(SEND_GENERIC_DATA, null, genericData); + libraryError = ncHandler.GetNcGenericData(out DTONcGenericDataModel genericData); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); + else + // Send through signalR + MessageServices.Current.Publish(SEND_GENERIC_DATA, null, genericData); } Thread.Sleep(1000); } @@ -67,11 +69,6 @@ public static class ThreadsFunctions { ncHandler.Dispose(); } - catch (Exception ex) - { - ncHandler.Dispose(); - TryNcConnection(); - } } public static void ReadAxes() @@ -79,7 +76,9 @@ public static class ThreadsFunctions NcHandler ncHandler = new NcHandler(); try { - ncHandler.Connect(); + CmsError libraryError = ncHandler.Connect(); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); while (true) { @@ -87,7 +86,9 @@ public static class ThreadsFunctions if (ncHandler.numericalControl.NC_IsConnected()) { // Get the list of the axes - List genericData = ncHandler.GetAxesPositions(); + libraryError = ncHandler.GetAxesPositions(out List genericData); + if (libraryError.errorCode != 0) + ManageLibraryError(libraryError); // Send through signalR MessageServices.Current.Publish(SEND_AXES, null, genericData); } @@ -98,11 +99,6 @@ public static class ThreadsFunctions { ncHandler.Dispose(); } - catch (Exception ex) - { - ncHandler.Dispose(); - TryNcConnection(); - } } private static void WillReconnect() @@ -111,24 +107,24 @@ public static class ThreadsFunctions ThreadsHandler.Stop(); NcHandler ncHandler = new NcHandler(); - + // Run loop until NC is connected while (!ncHandler.numericalControl.NC_IsConnected()) { - // Clear connection - try + // Try reconnection + CmsError cmsError = ncHandler.Connect(); + if (cmsError.errorCode == SIEMENS_ENVIRONMENT_NOT_FOUND || cmsError.errorCode == SIEMENS_HMI_NOT_RUNNING) { - // Try reconnection - ncHandler.Connect(); + ManageLibraryError(cmsError); } - catch (Exception ex) - { + else if ( cmsError.errorCode != OK) ncHandler.Dispose(); - } - // Send through signalR - Thread.Sleep(1000); + + // Send status to UI MessageServices.Current.Publish(NC_STATUS, null, ncHandler.numericalControl.NC_IsConnected()); + + Thread.Sleep(1000); } - // Restart NC threads + // Start/Restart NC threads ThreadsHandler.StartWorkers(); reconnectionIsRunning = false; @@ -148,4 +144,35 @@ public static class ThreadsFunctions t.Start(); } } + + public static void ManageLibraryError(CmsError cmsError) + { + switch (cmsError.errorCode) + { + case NC_PROD_ERROR: + TryNcConnection(); + break; + case NOT_CONNECTED: + TryNcConnection(); // If not connected try reconnection + break; + case PROC_NOT_FOUND: + break; + case FUNCTION_NOT_ALLOWED: + break; + case BIT_NOT_IN_RANGE: + break; + case BYTE_NOT_IN_RANGE: + break; + case INTERNAL_ERROR: + break; + case INCORRECT_PARAMETERS: + break; + case NC_LANGUAGE_ERROR: + break; + case SIEMENS_ENVIRONMENT_NOT_FOUND: + case SIEMENS_HMI_NOT_RUNNING: + Manage(ERROR_LEVEL.FATAL, cmsError.message); + break; + } + } } diff --git a/Step.Utils/Constants.cs b/Step.Utils/Constants.cs index 69fecb76..26f51c7e 100644 --- a/Step.Utils/Constants.cs +++ b/Step.Utils/Constants.cs @@ -31,7 +31,7 @@ namespace Step.Utils // Token fields Keys public const string ROLE_LEVEL_KEY = "roleLevel"; public const string USERNAME_KEY = "username"; - public const string ID_KEY = "id"; + public const string USER_ID_KEY = "id"; // Names in the xml file public const string SERVER_CONFIG_KEY = "serverConfig"; diff --git a/Step/Controllers/WebApi/AuthorizationController.cs b/Step/Controllers/WebApi/AuthorizationController.cs index 976e6a5e..1bca0cc0 100644 --- a/Step/Controllers/WebApi/AuthorizationController.cs +++ b/Step/Controllers/WebApi/AuthorizationController.cs @@ -23,7 +23,6 @@ namespace Step.Controllers.WebApi var userRoleLevel = identity.Claims.Where(c => c.Type == ROLE_LEVEL_KEY).SingleOrDefault(); - List functionsList = functionController.GetFunctionAccess(Convert.ToInt32(userRoleLevel.Value)); if (functionsList == null) diff --git a/Step/Controllers/WebApi/LoginController.cs b/Step/Controllers/WebApi/LoginController.cs deleted file mode 100644 index bd8fa793..00000000 --- a/Step/Controllers/WebApi/LoginController.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Web.Http; -using static Step.Utils.Constants; -using Step.Database.Controllers; -using System; -using Step.Model.DatabaseModels; - -namespace Step.Controllers.WebApi -{ - [RoutePrefix("api/user")] - public class LoginController : ApiController - { - [Route("register"), HttpPost] - public IHttpActionResult CreateUser(UserModel model) - { - UsersController users = new UsersController(); - users.Create(model.Username, model.Password, model.FirstName, model.LastName, model.RoleId, model.Language); - return Ok(); - } - } -} diff --git a/Step/Controllers/WebApi/NcApiController.cs b/Step/Controllers/WebApi/NcApiController.cs index 1a4e8e3e..20ef7512 100644 --- a/Step/Controllers/WebApi/NcApiController.cs +++ b/Step/Controllers/WebApi/NcApiController.cs @@ -8,6 +8,7 @@ using System.Web.Http; using CMS_CORE; using Step.Model.DTOModels; using Step.NC; +using static CMS_CORE.Nc; using static Step.Utils.Constants; namespace Step.Controllers.WebApi @@ -19,7 +20,6 @@ namespace Step.Controllers.WebApi [WebApiAuthorize(FunctionAccess = "ncData", Action = ACTIONS.READ)] public IHttpActionResult GetNcGenericData() { - DTONcGenericDataModel genericData = new DTONcGenericDataModel(); Stopwatch stop = new Stopwatch(); stop.Start(); try @@ -27,16 +27,17 @@ namespace Step.Controllers.WebApi using (NcHandler ncHandler = new NcHandler()) { ncHandler.Connect(); - genericData = ncHandler.GetNcGenericData(); + CmsError libraryError = ncHandler.GetNcGenericData(out DTONcGenericDataModel genericData); + if (libraryError.errorCode != 0) + Console.WriteLine(libraryError.message); + + return Ok(genericData); } } catch (Exception ex) { return InternalServerError(ex); } - - Console.WriteLine("API" + stop.ElapsedMilliseconds); - return Ok(genericData); } } } diff --git a/Step/Controllers/WebApi/UserController.cs b/Step/Controllers/WebApi/UserController.cs new file mode 100644 index 00000000..85505ab7 --- /dev/null +++ b/Step/Controllers/WebApi/UserController.cs @@ -0,0 +1,38 @@ +using System.Web.Http; +using static Step.Utils.Constants; +using Step.Database.Controllers; +using System; +using Step.Model.DatabaseModels; +using System.Security.Claims; +using System.Linq; + +namespace Step.Controllers.WebApi +{ + [RoutePrefix("api/user")] + public class UserController : ApiController + { + [Route("register"), HttpPost] + public IHttpActionResult CreateUser(UserModel model) + { + UsersController users = new UsersController(); + users.Create(model.Username, model.Password, model.FirstName, model.LastName, model.RoleId, model.Language); + return Ok(); + } + + [Route("info"), HttpGet] + [WebApiAuthorize(FunctionAccess = "userData", Action = ACTIONS.READ)] + public IHttpActionResult UserInfo(UserModel userModel) + { + var identity = User.Identity as ClaimsIdentity; + + var userId = identity.Claims.Where(c => c.Type == USER_ID_KEY).SingleOrDefault(); + if (userId == null) + return Unauthorized(); + + using (UsersController user = new UsersController()) + { + return Ok(user.GetUserInfo(Convert.ToInt32(userId.Value))); + } + } + } +} diff --git a/Step/Provider/ApplicationOAuthProvider.cs b/Step/Provider/ApplicationOAuthProvider.cs index e15edc0a..14ac3a3b 100644 --- a/Step/Provider/ApplicationOAuthProvider.cs +++ b/Step/Provider/ApplicationOAuthProvider.cs @@ -23,7 +23,7 @@ namespace Step.Provider try { // Check if credentials are correct - UserModel user = usersController.Find(context.UserName, context.Password); + UserModel user = usersController.FindByUsernameAndPassword(context.UserName, context.Password); // If not if (user == null) { @@ -35,6 +35,7 @@ namespace Step.Provider var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(USERNAME_KEY, user.Username)); identity.AddClaim(new Claim(ROLE_LEVEL_KEY, user.Role.Level.ToString())); + identity.AddClaim(new Claim(USER_ID_KEY, user.UserId.ToString())); // Create Token with identity data context.Validated(identity); diff --git a/Step/Step.csproj b/Step/Step.csproj index 1d76f637..86eda0af 100644 --- a/Step/Step.csproj +++ b/Step/Step.csproj @@ -168,7 +168,7 @@ - + diff --git a/Step/program.cs b/Step/program.cs index 48e92738..6eb707c6 100644 --- a/Step/program.cs +++ b/Step/program.cs @@ -28,14 +28,12 @@ namespace Step DatabaseContext.TestDatabaseConnection(); // Start self host application - string configuredUri = "http://localhost:" + ServerConfig.ServerPort.ToString(); - + string configuredUri = "http://*:" + ServerConfig.ServerPort.ToString(); // Register listener to "close application" messages MessageServices.Current.Subscribe(STOP_SERVER, (a, b) => { StopRequest.Set(); - }); // Start server services