async void BtnPair_Click(object sender, RoutedEventArgs e) { try { _settings.Username = txtUsername.Text; _settings.Password = txtPassword.Text; _settings.PairingCode = txtPairingCode.Text; //var uri = $"{baseAuthApiUri}/pairing/cloudpos"; //var request = new HttpRequestMessage(HttpMethod.Post, uri) //{ // Content = new StringContent(JsonConvert.SerializeObject(new { username = _settings.Username, password = _settings.Password, paircode = _settings.PairingCode, posName, posVersion, posId }), System.Text.Encoding.UTF8, "application/json") //}; // //var httpResponse = await client.SendAsync(request); //httpResponse.EnsureSuccessStatusCode(); // //var pairingResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<PairingResponse>(await httpResponse.Content.ReadAsStringAsync()); var enableCloud = _settings.EnableCloud; int tmpPortVar = 0; var addr = _settings.EFTClientAddress.Split(new char[] { ':' }); if (addr.Length < 2 || int.TryParse(addr[1], out tmpPortVar) == false) { ShowNotification("INVALID ADDRESS", "", "", NotificationType.Error, true); } bool connected = false; try { connected = await _eft.ConnectAsync(addr[0], tmpPortVar, enableCloud, enableCloud); } catch (Exception) { connected = false; } var waiting = await _eft.WriteRequestAsync(new EFTCloudPairRequest { ClientID = _settings.Username, Password = _settings.Password, PairingCode = _settings.PairingCode }); while (waiting) { var eftResponse = await _eft.ReadResponseAsync(new CancellationTokenSource(45000).Token); if (eftResponse is EFTCloudPairResponse) { var cloudLogonResponse = eftResponse as EFTCloudPairResponse; if (!cloudLogonResponse.Success) { connected = false; } else { _settings.Token = cloudLogonResponse.Token; } waiting = false; } } _settings.Save(); // Update UI txtToken.Text = _settings.Token; //DO A simple logon when pairing??? if (await ConnectAsync()) { NavigateToMainPage(); } else { NavigateToSettingsPage(); } } catch (Exception ex) { ShowNotification("PAIRING FAILURE", "", ex.Message, NotificationType.Error, true); } }
private async Task <bool> SendRequest <T>(EFTRequest request, bool autoApproveDialogs = false) { bool result = false; if (_requestInProgress) { _data.Log($"Unable to process {request.ToString()}. There is already a request in progress"); return(false); } if (!_eft.IsConnected || _data.ConnectedState == ConnectedStatus.Disconnected) { await _eft.ConnectAsync("127.0.0.1", 2011, false); _data.ConnectedState = ConnectedStatus.Connected; } try { await _eft.WriteRequestAsync(request); _requestInProgress = true; do { var timeoutToken = new CancellationTokenSource(new TimeSpan(0, 5, 0)).Token; // 5 minute timeout if (request.GetType().Equals(typeof(EFTSlaveRequest))) { _requestInProgress = false; } var r = await _eft.ReadResponseAsync(timeoutToken); if (r == null) // stream is busy { _data.Log($"Unable to process {request.ToString()}. Stream is busy."); } else if (r is EFTDisplayResponse) { if (_data.Settings.DemoDialogOption != DemoDialogMode.Hide) { EFTDisplayResponse res = r as EFTDisplayResponse; _data.DisplayDetails = res; _data.DisplayDialog(true); } if (autoApproveDialogs && (r as EFTDisplayResponse).OKKeyFlag) { await _eft.WriteRequestAsync(new EFTSendKeyRequest() { Key = EFTPOSKey.OkCancel }); } } else if (r is EFTReceiptResponse || r is EFTReprintReceiptResponse) { // Hacked in some preprint and print response timeouts. It ain't pretty and it may not work, but it's my code. #region PrintResponse Timeout if (_data.IsPrePrintTimeOut) { if ((r as EFTReceiptResponse).IsPrePrint) { Thread.Sleep(59000); } } else if (_data.IsPrintTimeOut) { if (!(r as EFTReceiptResponse).IsPrePrint) { Thread.Sleep(59000); } } #endregion string[] receiptText = (r is EFTReceiptResponse) ? (r as EFTReceiptResponse).ReceiptText : (r as EFTReprintReceiptResponse).ReceiptText; StringBuilder receipt = new StringBuilder(); foreach (var s in receiptText) { if (s.Length > 0) { receipt.AppendLine(s); } } if (!string.IsNullOrEmpty(receipt.ToString())) { _data.Receipt = receipt.ToString(); } if (request is EFTReceiptRequest || (request is EFTReprintReceiptRequest && request.GetPairedResponseType() == r.GetType())) { _requestInProgress = false; _eft.Dispose(); } } else if (r is EFTQueryCardResponse) { _data.LastTxnResult = DictionaryFromType(r); var x = (EFTQueryCardResponse)r; _data.SelectedTrack2 = x.Track2; _data.DisplayDialog(false); _requestInProgress = false; _eft.Dispose(); } else if (r is EFTClientListResponse) { int index = 1; var x = (EFTClientListResponse)r; Dictionary <string, string> ClientList = new Dictionary <string, string>(); foreach (var clnt in x.EFTClients) { ClientList.Add("Client " + index.ToString() + " " + nameof(clnt.Name), clnt.Name); ClientList.Add("Client " + index.ToString() + " " + nameof(clnt.IPAddress), clnt.IPAddress); ClientList.Add("Client " + index.ToString() + " " + nameof(clnt.Port), clnt.Port.ToString()); ClientList.Add("Client " + index.ToString() + " " + nameof(clnt.State), clnt.State.ToString()); index++; } _data.LastTxnResult = ClientList; _data.DisplayDialog(false); _requestInProgress = false; _eft.Dispose(); } else { _data.LastTxnResult = DictionaryFromType(r); string output = string.Empty; _data.LastTxnResult.TryGetValue("Success", out output); result = (output.Equals("True")); _data.DisplayDialog(false); _requestInProgress = false; _eft.Dispose(); } }while (_requestInProgress); if (!_requestInProgress) { _data.Log($"Request: {request.ToString()} done!"); } } catch (TaskCanceledException) { _data.ConnectedState = ConnectedStatus.Disconnected; ShowError("EFT-Client Timeout", ""); } catch (ConnectionException cx) { _data.ConnectedState = ConnectedStatus.Disconnected; ShowError(cx.HResult.ToString(), cx.Message); } catch (Exception ex) { ShowError(ex.HResult.ToString(), ex.Message); } _requestInProgress = false; return(result); }
async Task <bool> ConnectAsync() { var enableCloud = _settings.EnableCloud; var addr = _settings.EFTClientAddress.Split(new char[] { ':' }); if (addr.Length < 2 || int.TryParse(addr[1], out int tmpPort) == false) { ShowNotification("INVALID ADDRESS", "", "", NotificationType.Error, true); return(false); } ShowNotification("CONTACTING EFT-CLIENT, PLEASE WAIT...", "", "", NotificationType.Normal, false); bool connected = false; try { connected = await _eft.ConnectAsync(addr[0], tmpPort, enableCloud, enableCloud); } catch (Exception) { connected = false; } var notifyText = ""; if (connected && enableCloud) { // Cloud login if in cloud mode if (enableCloud) { var waiting = await _eft.WriteRequestAsync(new EFTCloudLogonRequest() { ClientID = _settings.Username, Password = _settings.Password, PairingCode = _settings.PairingCode }); while (waiting) { var eftResponse = await _eft.ReadResponseAsync(new CancellationTokenSource(45000).Token); if (eftResponse is EFTCloudLogonResponse) { var cloudLogonResponse = eftResponse as EFTCloudLogonResponse; if (!cloudLogonResponse.Success) { connected = false; notifyText = $"{cloudLogonResponse.ResponseCode} {cloudLogonResponse.ResponseText}"; } waiting = false; } } } } if (connected) { _isServerVerified = true; HideNotification(); UpdateSettingsPageUI(); // This is only required if we aren't using the PC-EFTPOS dialog await _eft.WriteRequestAsync(new SetDialogRequest() { DialogType = DialogType.Hidden }); await _eft.ReadResponseAsync <SetDialogResponse>(new CancellationTokenSource(new TimeSpan(0, 5, 0)).Token); // } else { _isServerVerified = false; UpdateSettingsPageUI(); ShowNotification("ERROR CONTACTING EFT-CLIENT", "", notifyText, NotificationType.Error, true); } return(_isServerVerified); }
private async Task ProcessRequest() { do { _logger.Log("Awaiting message..."); var r = await eft.ReadResponseAsync(); if (r == null) // stream is busy { _logger.Log("Received null response. Waiting 3 secs..."); await Task.Delay(3000); // wait 3 sec? continue; } _logger.Log($"Message received! {r}"); if (r is EFTPayAtTableResponse) { try { var response = (EFTPayAtTableResponse)r; var msg = new POSAPIMsg(); msg.ParseFromString(response); _logger.Log(new LogData(msg.ToString(), $"RX (Handling message): {msg.ToString()}")); switch (msg.Header.RequestMethod) { case RequestMethod.Settings: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Settings = _settingsRepository.GetSettings(Data.Options) }); } break; case RequestMethod.Tables: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Tables = _tablesRepository.GetTables() }); } break; case RequestMethod.TablesWithOrders: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Tables = _tablesRepository.GetTablesWithOrders() }); } break; case RequestMethod.TableOrders: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Orders = _ordersRepository.GetOrdersFromTable(msg.Header.TableId) }); } break; case RequestMethod.Order: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Order = _ordersRepository.GetOrder(msg.Header.OrderId) }); } break; case RequestMethod.OrderReceipt: if (msg.Header.RequestType == RequestType.GET) { await HandleRequest(msg, () => new PATResponse() { Receipt = _ordersRepository.GetCustomerReceiptFromOrderId(msg.Header.OrderId, msg.Header.ReceiptOptionId) }); } break; case RequestMethod.Tender: if (msg.Header.RequestType == RequestType.POST) { await HandleCreateTender(msg); } else if (msg.Header.RequestType == RequestType.PUT) { await HandleUpdateTender(msg); } break; case RequestMethod.EFTPOSCommand: if (msg.Header.RequestType == RequestType.POST) //looks like there are 3 of them to handle { await HandleEFTPOSCommand(msg); } break; } } catch (Exception ex) { _logger.Log(ex.Message, LogType.ERROR); } } else if (r is EFTStatusResponse) { var response = (EFTStatusResponse)r; _logger.Log($"Status response. {response.ResponseCode} {response.ResponseText}", (response.Success ? LogType.INFO : LogType.ERROR)); _logger.Log($"Pinpad online: {response.Success}"); } }while (true); }