using MConnectSDK; using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace TestClient { public partial class MainForm : Form { /// /// Token x cancellazione thread /// private CancellationTokenSource _cts; /// /// Context x sync thread /// private readonly SynchronizationContext synchronizationContext; /// /// Timestamp precedente /// private DateTime previousTime = DateTime.Now; /// /// Istanze classe MaestroConnectClient /// protected MConnectClient MCC; /// /// Risposta BASE della classe di comunicazione /// protected Result reqStatus; /// /// Form principale /// public MainForm() { InitializeComponent(); myInit(); synchronizationContext = SynchronizationContext.Current; } #region metodi accessori protected void myInit() { var clockTask = updateClockAsync(); _cts = new CancellationTokenSource(); fixDisplay(); lblConsole.Text = ""; } private void fixDisplay() { // controllo se visualizzare parametri di testing... bool showTP = chkTestMode.Checked; lblTokRet.Visible = showTP; txtTokenRet.Visible = showTP; btnSetRetVal.Visible = showTP; // salvo token resp... saveTokenResp(); } private async Task updateClockAsync() { await Task.Run(() => { while (true) { Thread.Sleep(50); UpdateUI(); } }); } public void UpdateUI() { var timeNow = DateTime.Now; if ((DateTime.Now - previousTime).Milliseconds <= 250) { return; } synchronizationContext.Post(new SendOrPostCallback(o => { lblClock.Text = timeNow.ToString("ddd dd.MM.yyyy HH:mm:ss"); }), ""); previousTime = timeNow; } private void resetAuthData() { Bitmap bitmap = new Bitmap(200, 200, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using (Graphics graphics = Graphics.FromImage(bitmap)) { using (System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.LightGray)) { graphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 200)); } } // graphics will be disposed at this line pictBox.Image = bitmap; StringBuilder sb = new StringBuilder(); sb.AppendLine("RESET DATA done!"); lblRetData.Text = sb.ToString(); } public void refreshRequestStatus() { // mostro risultato StringBuilder sb = new StringBuilder(); sb.AppendLine("-------------------------"); sb.AppendLine("- Request Status"); sb.AppendLine("-------------------------"); if (reqStatus != null) { sb.AppendLine("isAuth: " + reqStatus.IsAuth); sb.AppendLine("isHmiEnrolled: " + reqStatus.IsHmiEnrolled); sb.AppendLine("cloudConnection: " + reqStatus.CloudStatusOk); sb.AppendLine("localConnection: " + reqStatus.LocalStatusOk); sb.AppendLine("callSuccess: " + reqStatus.CallResultOk); sb.AppendLine(""); sb.AppendLine(string.Format("{0:HH.mm.ss.fff}", DateTime.Now)); sb.AppendLine("-------------------------"); } lblReqStatus.Text = sb.ToString(); sb.AppendLine(""); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | END", DateTime.Now)); sb.AppendLine("--------------------------------------------------"); lblConsole.Text += sb.ToString(); if (reqStatus != null) { // se NON enrolled --> abilita tryAuth... btnTryAuth.Enabled = !reqStatus.IsHmiEnrolled; } } /// /// Mostra info x USER AUTH /// /// private void updateAuthData(ActivationPayload authData) { // aggiorno console... lblConsole.Text = authData.Message; // verifico se sia AUTH (altrimenti NON mostro codice e QR...) if (authData.HasAuth || reqStatus.IsAuth) { var currColor = Color.Orange; // se fosse ANCHE enrolled cambio colore... if (authData.IsEnrolled || reqStatus.IsHmiEnrolled) { currColor = Color.Green; } Bitmap bitmap = new Bitmap(200, 200, System.Drawing.Imaging.PixelFormat.Format24bppRgb); using (Graphics graphics = Graphics.FromImage(bitmap)) { using (SolidBrush myBrush = new SolidBrush(currColor)) { graphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 200)); } } // graphics will be disposed at this line pictBox.Image = bitmap; StringBuilder sb = new StringBuilder(); sb.AppendLine("AUTH DONE!"); if (authData.IsEnrolled || reqStatus.IsHmiEnrolled) { sb.AppendLine("------"); sb.AppendLine("ENROLLED!"); } lblRetData.Text = sb.ToString(); } else { // mostro info SE disponibili... if (authData.UserCode != "") { StringBuilder sb = new StringBuilder(); sb.AppendLine("device_code:"); sb.AppendLine(authData.DeviceCode.ToString()); sb.AppendLine(""); sb.AppendLine("user_code:"); sb.AppendLine(authData.UserCode.ToString()); sb.AppendLine(""); lblRetData.Text = sb.ToString(); Zen.Barcode.CodeQrBarcodeDraw qrcode = Zen.Barcode.BarcodeDrawFactory.CodeQr; pictBox.Image = qrcode.Draw(authData.QrCode, 50); } } } private void saveTokenResp() { try { // verifico sia numero int tokRet = 0; int.TryParse(txtTokenRet.Text.Trim(), out tokRet); if (MCC != null) { // salvo in redis... MCC.tokenRetVal = tokRet; } } catch { } } #endregion #region metodi chiamate TASK / async /// /// Task x INIT da file di conf /// /// /// private async Task doInitAsync(string confFilePath) { await Task.Run(() => { // NUOVA istanza da file di conf... MCC = new MConnectClient(); // init async... var taskResult = MCC.InitSDKAsync(confFilePath, CancellationToken.None); // ora leggo lo status... taskResult = MCC.GetClientStatusAsync(); // salvo il risultato restituito... reqStatus = taskResult.Result; // sistemo retVal saveTokenResp(); synchronizationContext.Post(new SendOrPostCallback(o => { refreshRequestStatus(); }), ""); }); } /// /// Recupero OrgCode /// /// private async Task getOrgCode() { await Task.Run(() => { string orgCode = MCC.organizationCode; synchronizationContext.Post(new SendOrPostCallback(o => { StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine("ORGANIZATION CODE: " + orgCode); sb.AppendLine("--------------------------------------------------"); lblConsole.Text = sb.ToString(); refreshRequestStatus(); }), ""); }); } /// /// Recupero client status /// /// private async Task getClientStatus() { await Task.Run(() => { var taskResult = MCC.GetClientStatusAsync(); // salvo il risultato restituito... reqStatus = taskResult.Result; synchronizationContext.Post(new SendOrPostCallback(o => { refreshRequestStatus(); }), ""); }); } /// /// Recupero UserList /// /// private async Task getUserList() { await Task.Run(() => { var userResult = MCC.getUserListAsync(); List userList = ((UserPayload)userResult.Result.Payload).UserList; synchronizationContext.Post(new SendOrPostCallback(o => { StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine("USERS FOUND: " + userList.Count.ToString()); sb.AppendLine("--------------------------------------------------"); sb.AppendLine("es:"); sb.AppendLine(string.Format("user_id: {0}", userList[0].UserId)); sb.AppendLine(string.Format("isAdmin: {0}", userList[0].IsAdmin)); sb.AppendLine(string.Format("UserName: {0}", userList[0].Username)); sb.AppendLine(string.Format("Email: {0}", userList[0].Email)); sb.AppendLine(string.Format("Cognome: {0}", userList[0].Cognome)); sb.AppendLine(string.Format("Nome: {0}", userList[0].Nome)); sb.AppendLine(string.Format("ImgUrl: {0}", userList[0].ImgUrl)); lblConsole.Text = sb.ToString(); refreshRequestStatus(); }), ""); }); } /// /// Tento login utente /// /// private async Task doUserLogin(string user, string pwd) { StringBuilder sb; await Task.Run(() => { UserData userData = new UserData(); var userResult = MCC.TryUserLogin(user, pwd); List userList = ((UserPayload)userResult.Result.Payload).UserList; // controllo se ho risultato...) if (userList.Count == 1) { userData = userList[0]; } if (userData.Username != "") { sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine("USER AUTH OK"); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(""); sb.AppendLine(string.Format("user_id: {0}", userData.UserId)); sb.AppendLine(string.Format("isAdmin: {0}", userData.IsAdmin)); sb.AppendLine(string.Format("UserName: {0}", userData.Username)); sb.AppendLine(string.Format("Email: {0}", userData.Email)); sb.AppendLine(string.Format("Cognome: {0}", userData.Cognome)); sb.AppendLine(string.Format("Nome: {0}", userData.Nome)); sb.AppendLine(string.Format("ImgUrl: {0}", userData.ImgUrl)); } else { sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine("USER AUTH KO"); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(""); sb.AppendLine("User/Pwd NOT found"); } synchronizationContext.Post(new SendOrPostCallback(o => { lblConsole.Text = sb.ToString(); refreshRequestStatus(); }), ""); }); } #endregion #region metodi chiamate interazione principali con controlli /// /// Reset parametri... /// /// /// private void btnResetParam_Click(object sender, EventArgs e) { chkTestMode.Checked = true; txtConfFile.Text = "mconnect.conf.yaml"; txtTokenRet.Text = "403"; reqStatus = new Result(); lblReqStatus.Text = ""; lblConsole.Text = ""; fixDisplay(); } /// /// Cambio valore checkbox del testing mode /// /// /// private void chkTestMode_Click(object sender, EventArgs e) { fixDisplay(); } /// /// Imposta il valore di return x fare AUTH (in testing) /// /// /// private void btnSetRetVal_Click(object sender, EventArgs e) { saveTokenResp(); } /// /// Simulazione INIT /// /// /// private async void btnInit_Click(object sender, EventArgs e) { // init in modalità Task based... await Task.Run(() => { var initObj = doInitAsync(txtConfFile.Text.Trim()); }); // aggiorno log console StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | START INIT", DateTime.Now)); sb.AppendLine(""); lblConsole.Text = sb.ToString(); // resetto aspetti grafici resetAuthData(); if (_cts != null) { _cts.Cancel(); } } /// /// Simulazione auth (SE non abilitato) /// /// /// private async void btnTryAuth_Click(object sender, EventArgs e) { // init variabili accessorie x chiamata StringBuilder sb = new StringBuilder(); // elimino eventuali cancel presenti... if (_cts.IsCancellationRequested) { _cts = new CancellationTokenSource(); } CancellationToken token = _cts.Token; // gestione progress... var progressHandler = new Progress(value => { // aggiorno richeista live... reqStatus = value; refreshRequestStatus(); // mostro i dati SPECIFICI x AUTH... updateAuthData((ActivationPayload)value.Payload); }); var progress = progressHandler as IProgress; try { // init in modalità Task based AUTH... await Task.Run(() => { var initObj = MCC.TryActivationAsync(token, progress); // ora processo attivazione initObj = MCC.EnrollMachineAsync(token, progress); // recupero dati e aggiorno display... var taskResult = MCC.GetClientStatusAsync(); // salvo il risultato restituito... reqStatus = taskResult.Result; // aggiorno display synchronizationContext.Post(new SendOrPostCallback(o => { refreshRequestStatus(); }), ""); }); } catch (OperationCanceledException) { sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | CANCELLED OAuth process", DateTime.Now)); sb.AppendLine("--------------------------------------------------"); lblConsole.Text = sb.ToString(); } catch (Exception ex) { //label2.Text = ex.GetType().Name + ": " + ex.Message; } // aggiorno log console sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | STARTING OAuth process", DateTime.Now)); sb.AppendLine("--------------------------------------------------"); lblConsole.Text = sb.ToString(); } /// /// recupera codice organizzazione /// /// /// private async void btnGetOrgCode_Click(object sender, EventArgs e) { // init in modalità Task based... await Task.Run(() => { var retObj = getOrgCode(); }); // aggiorno log console StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | OrgCode requested", DateTime.Now)); sb.AppendLine(""); lblConsole.Text = sb.ToString(); } /// /// chiamata recupero elenco utenti /// /// /// private async void btnGetUserList_Click(object sender, EventArgs e) { // init in modalità Task based... await Task.Run(() => { var retObj = getUserList(); }); // aggiorno log console StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | UserList requested", DateTime.Now)); sb.AppendLine(""); lblConsole.Text = sb.ToString(); } /// /// chiamata x login utente /// /// /// private async void btnTryUserLogin_Click(object sender, EventArgs e) { // init in modalità Task based... await Task.Run(() => { var retObj = doUserLogin(txtUser.Text.Trim(), txtPwd.Text.Trim()); }); // aggiorno log console StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | UserLogin requested", DateTime.Now)); sb.AppendLine(""); lblConsole.Text = sb.ToString(); } #endregion private async void btnGetClientStatus_Click(object sender, EventArgs e) { // init in modalità Task based... await Task.Run(() => { var retObj = getClientStatus(); }); // aggiorno log console StringBuilder sb = new StringBuilder(); sb.AppendLine("--------------------------------------------------"); sb.AppendLine(string.Format("{0:HH.mm.ss.fff} | ClientStatus requested", DateTime.Now)); sb.AppendLine(""); lblConsole.Text = sb.ToString(); } } }