예제 #1
0
        public byte[] Send(IDeviceMessage message)
        {
            byte[] buffer = message.GetSendBuffer();

            Connect();
            try {
                for (int i = 0; i < 3; i++)
                {
                    _stream.WriteAsync(buffer, 0, buffer.Length).Wait();

                    var rvalue = _stream.GetTerminalResponseAsync();
                    if (rvalue != null)
                    {
                        byte lrc = rvalue[rvalue.Length - 1]; // Should be the LRC
                        if (lrc != TerminalUtilities.CalculateLRC(rvalue))
                        {
                            SendControlCode(ControlCodes.NAK);
                        }
                        else
                        {
                            SendControlCode(ControlCodes.ACK);
                            return(rvalue);
                        }
                    }
                }
                throw new MessageException("Terminal did not respond in the given timeout.");
            }
            catch (Exception exc) {
                throw new MessageException(exc.Message, exc);
            }
            finally {
                OnMessageSent?.Invoke(message.ToString());
                Disconnect();
            }
        }
예제 #2
0
        public byte[] Send(IDeviceMessage message)
        {
            OnMessageSent?.Invoke(message.ToString());

            try {
                string payload = Convert.ToBase64String(message.GetSendBuffer());

                return(Task.Run(async() => {
                    _client = HttpWebRequest.Create(string.Format("http://{0}:{1}?{2}", _settings.IpAddress, _settings.Port, payload));

                    var response = await _client.GetResponseAsync();

                    var buffer = new List <byte>();
                    using (var sr = new StreamReader(response.GetResponseStream())) {
                        var rec_buffer = await sr.ReadToEndAsync();
                        foreach (char c in rec_buffer)
                        {
                            buffer.Add((byte)c);
                        }
                    }
                    return buffer.ToArray();
                }).Result);
            }
            catch (Exception exc) {
                throw new MessageException("Failed to send message. Check inner exception for more details.", exc);
            }
        }
예제 #3
0
 async public Task Display(IDeviceMessage sensor)
 {
     await AzureIoTHub.SendDeviceToCloudMessageAsync(sensor.MachineID, JsonConvert.SerializeObject(sensor, new JsonSerializerSettings()
     {
         NullValueHandling = NullValueHandling.Ignore
     }));
 }
예제 #4
0
        public byte[] Send(IDeviceMessage message)
        {
            if (OnMessageSent != null)
            {
                OnMessageSent(message.ToString());
            }

            try {
                string payload = Convert.ToBase64String(message.GetSendBuffer());

                _client = HttpWebRequest.Create(string.Format("http://{0}:{1}?{2}", _settings.IpAddress, _settings.Port, payload));
                var response = (HttpWebResponse)_client.GetResponse();
                var buffer   = new List <byte>();
                using (var sr = new StreamReader(response.GetResponseStream())) {
                    var rec_buffer = sr.ReadToEnd();
                    foreach (char c in rec_buffer)
                    {
                        buffer.Add((byte)c);
                    }
                }
                return(buffer.ToArray());
            }
            catch (Exception exc) {
                throw new HpsMessageException("Failed to send message. Check inner exception for more details.", exc);
            }
        }
예제 #5
0
        public byte[] Send(IDeviceMessage message)
        {
            Connect();

            var str_message = message.ToString();

            message_queue = new List <byte>();
            try {
                byte[] buffer = message.GetSendBuffer();
                OnMessageSent?.Invoke(message.ToString().Substring(2));

                if (_stream != null)
                {
                    _stream.Write(buffer, 0, buffer.Length);
                    _stream.Flush();

                    var task = BeginReceiveTask();
                    if (!task.Wait(_settings.Timeout))
                    {
                        throw new MessageException("Device did not respond within the timeout.");
                    }

                    return(message_queue.ToArray());
                }
                else
                {
                    throw new MessageException("Device not connected.");
                }
            }
            finally {
                Disconnect();
            }
        }
예제 #6
0
        internal override ITerminalResponse ProcessTransaction(TerminalAuthBuilder builder)
        {
            IDeviceMessage message  = BuildProcessTransaction(builder);
            var            response = _connector.Send(message);

            throw new NotImplementedException();
        }
        public byte[] Send(IDeviceMessage message)
        {
            try {
                if (_serialPort != null)
                {
                    _transComplete = false;
                    _exit          = false;

                    string bufferSend = Encoding.ASCII.GetString(message.GetSendBuffer());
                    OnMessageSent?.Invoke(bufferSend.Substring(1, bufferSend.Length - 3));

                    Task <bool> task = WriteMessage(message);
                    lock (_lock) {
                        while (!_transComplete)
                        {
                            if (!Monitor.Wait(_lock, _settings.Timeout))
                            {
                                _exit          = true;
                                _transComplete = true;
                                throw new ApiException("Terminal did not respond within timeout.");
                            }
                        }
                    }

                    return(_messageResponse.ToArray());
                }
                else
                {
                    throw new ConfigurationException("Terminal not connected.");
                }
            } catch (ApiException e) {
                throw new ApiException(e.Message);
            }
        }
예제 #8
0
        internal byte[] Send(IDeviceMessage message)
        {
            byte[] buffer   = message.GetSendBuffer();
            bool   timedOut = false;

            Connect(PrimaryEndpoint, PrimaryPort);
            try {
                for (int i = 0; i < 2; i++)
                {
                    DateTime requestSent = DateTime.UtcNow;
                    if (client != null && client.Connected && sslStream.IsAuthenticated)
                    {
                        sslStream.Write(buffer, 0, buffer.Length);
                        sslStream.Flush();
                    }
                    byte[] rvalue = GetGatewayResponse();
                    if (rvalue != null && !ForceGatewayTimeout)
                    {
                        return(rvalue);
                    }
                    // did not get a response, switch endpoints and try again
                    timedOut = true;
                    if (!currentEndpoint.Equals("secondary") && !string.IsNullOrEmpty(SecondaryEndpoint) && i < 1)
                    {
                        Disconnect();
                        Connect(SecondaryEndpoint, SecondaryPort);
                    }
                }
                throw new GatewayTimeoutException();
            }
            catch (GatewayTimeoutException exc) {
                exc.GatewayEvents = events;
                throw exc;
            }
            catch (Exception exc) {
                if (timedOut)
                {
                    GatewayTimeoutException gatewayException = new GatewayTimeoutException(exc)
                    {
                        GatewayEvents = events
                    };
                    throw gatewayException;
                }
                else
                {
                    GatewayException gatewayException = new GatewayException("Failed to connect to primary or secondary processing endpoints.", exc);
                    throw gatewayException;
                }
            }
            finally {
                Disconnect();
                // remove the force timeout
                if (ForceGatewayTimeout)
                {
                    ForceGatewayTimeout = false;
                }
            }
        }
예제 #9
0
        public Task Display(IDeviceMessage sensor)
        {
            string deserializedObject =
                JsonConvert.SerializeObject(sensor, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            Console.WriteLine(deserializedObject);
            return(Task.FromResult(true));
        }
        internal override ITerminalResponse ManageTransaction(TerminalManageBuilder builder)
        {
            IDeviceMessage request = BuildManageTransaction(builder);

            if (builder.TransactionType == TransactionType.Reversal)
            {
                return(DoReverseRequest(request));
            }
            else
            {
                return(DoRequest(request));
            }
        }
예제 #11
0
        public byte[] Send(IDeviceMessage message)
        {
            byte[] buffer = message.GetSendBuffer();

            ControlCodes?code = null;

            OnControlCodeReceived += (rec_code) => {
                code = rec_code;
                _await.Set();
            };

            byte[] rvalue = null;
            OnMessageReceived += (rec_buffer) => {
                rvalue = rec_buffer;
                _await.Set();
            };

            for (int i = 0; i < 3; i++)
            {
                _stream.Write(buffer, 0, buffer.Length);
                if (OnMessageSent != null)
                {
                    OnMessageSent(message.ToString());
                }
                _await.WaitOne(1000);

                if (!code.HasValue)
                {
                    throw new HpsMessageException("Terminal did not respond in the given timeout.");
                }

                if (code == ControlCodes.NAK)
                {
                    continue;
                }
                else if (code == ControlCodes.EOT)
                {
                    throw new HpsMessageException("Terminal returned EOT for the current message.");
                }
                else if (code == ControlCodes.ACK)
                {
                    _await.WaitOne(_settings.TimeOut);
                    break;
                }
                else
                {
                    throw new HpsMessageException(string.Format("Unknown message received: {0}", code));
                }
            }
            return(rvalue);
        }
예제 #12
0
        internal IDeviceMessage BuildReportTransaction(TerminalReportBuilder builder)
        {
            string messageId = MapReportType(builder.ReportType);

            IDeviceMessage request = null;

            switch (builder.ReportType)
            {
            case TerminalReportType.LocalDetailReport: {
                var criteria = builder.SearchBuilder;

                // additional data
                var additionalData = new ExtDataSubGroup();
                if (criteria.MerchantId.HasValue)
                {
                    additionalData[EXT_DATA.MERCHANT_ID] = criteria.MerchantId.ToString();
                }
                if (!string.IsNullOrEmpty(criteria.MerchantName))
                {
                    additionalData[EXT_DATA.MERCHANT_NAME] = criteria.MerchantName;
                }

                request = TerminalUtilities.BuildRequest(
                    messageId,
                    "00",          // EDC TYPE SET TO ALL
                    ControlCodes.FS,
                    criteria.TransactionType.HasValue ? ((int)criteria.TransactionType.Value).ToString().PadLeft(2, '0') : string.Empty,
                    ControlCodes.FS,
                    criteria.CardType.HasValue ? ((int)criteria.CardType.Value).ToString().PadLeft(2, '0') : string.Empty,
                    ControlCodes.FS,
                    criteria.RecordNumber.HasValue ? criteria.RecordNumber.ToString() : string.Empty,
                    ControlCodes.FS,
                    criteria.TerminalReferenceNumber.HasValue ? criteria.TerminalReferenceNumber.ToString() : string.Empty,
                    ControlCodes.FS,
                    criteria.AuthCode ?? string.Empty,
                    ControlCodes.FS,
                    criteria.ReferenceNumber ?? string.Empty,
                    ControlCodes.FS,
                    additionalData
                    );
            }
            break;

            default: {
                throw new UnsupportedTransactionException(string.Format("Unsupported report type: {0}", builder.ReportType.ToString()));
            };
            }

            return(request);
        }
예제 #13
0
        internal TransactionResponse DoTransaction(IDeviceMessage request)
        {
            request.AwaitResponse = true;
            var response = _connector.Send(request);

            if (response == null)
            {
                return(null);
            }

            string jsonObject = Encoding.UTF8.GetString(response);
            var    jsonParse  = JsonDoc.Parse(jsonObject);

            return(new TransactionResponse(jsonParse));
        }
예제 #14
0
        internal T SendMessage <T>(string message, bool keepAlive, bool awaitResponse, params string[] messageIds)
        {
            IDeviceMessage deviceMessage = TerminalUtilities.BuildRequest(message, Format);

            deviceMessage.KeepAlive     = keepAlive;
            deviceMessage.AwaitResponse = awaitResponse;

            var response = _connector.Send(deviceMessage);

            if (awaitResponse)
            {
                return((T)Activator.CreateInstance(typeof(T), response, messageIds));
            }
            else
            {
                return(default(T));
            }
        }
예제 #15
0
        private async Task <GatewayResponse> StageTransactionAsync(IDeviceMessage message)
        {
            try {
                string payload = Encoding.UTF8.GetString(message.GetSendBuffer());

                string url = ServiceEndpoints.GENIUS_TERMINAL_TEST;
                if (_gatewayConfig.Environment.Equals(Entities.Environment.PRODUCTION))
                {
                    url = ServiceEndpoints.GENIUS_TERMINAL_PRODUCTION;
                }

                HttpClient httpClient = new HttpClient {
                    Timeout = TimeSpan.FromMilliseconds(_settings.Timeout)
                };

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Headers.Add("SOAPAction", "http://transport.merchantware.net/v4/CreateTransaction");

                HttpResponseMessage response = null;
                try {
                    request.Content = new StringContent(payload, Encoding.UTF8, "text/xml");
                    response        = await httpClient.SendAsync(request);

                    return(new GatewayResponse {
                        StatusCode = response.StatusCode,
                        RequestUrl = response.RequestMessage.RequestUri.ToString(),
                        RawResponse = response.Content.ReadAsStringAsync().Result
                    });
                }
                catch (Exception exc) {
                    throw new GatewayException("Error occurred while communicating with gateway.", exc);
                }
            }
            catch (Exception exc) {
                throw new MessageException("Failed to send message. Check inner exception for more details.", exc);
            }
        }
예제 #16
0
        public byte[] Send(IDeviceMessage message)
        {
            OnMessageSent?.Invoke(message.ToString());

            try {
                return(Task.Run(async() => {
                    GatewayResponse serviceResponse = await StageTransactionAsync(message);
                    if (serviceResponse.StatusCode == HttpStatusCode.OK)
                    {
                        var root = ElementTree.Parse(serviceResponse.RawResponse).Get("CreateTransactionResponse");

                        var errors = root.GetAll("Message");
                        if (errors.Length > 0)
                        {
                            var sb = new StringBuilder();
                            foreach (var error in root.GetAll("Message"))
                            {
                                sb.AppendLine(error.GetValue <string>("Information"));
                            }
                            throw new MessageException(sb.ToString());
                        }

                        string transportKey = root.GetValue <string>("TransportKey");
                        string validationKey = root.GetValue <string>("ValidationKey");

                        return await InitializeTransactionAsync(transportKey);
                    }
                    else
                    {
                        throw new MessageException(serviceResponse.StatusCode.ToString());
                    }
                }).Result);
            }
            catch (Exception exc) {
                throw new MessageException("Failed to send message. Check inner exception for more details.", exc);
            }
        }
        public byte[] Send(IDeviceMessage message)
        {
            byte[] buffer = message.GetSendBuffer();
            _termResponse     = null;
            _bufferSend       = false;
            _isResponseNeeded = true;

            try {
                // Validate if server is starting
                if (!_listener.Active)
                {
                    throw new ConfigurationException("Server is not running.");
                }

                // Validate keep alive for setting of timeout during Transaction
                _stream.ReadTimeout = _settings.Timeout;

                if (_ipAddresses.Count > 0 || _client.Connected)
                {
                    _stream.WriteAsync(buffer, 0, buffer.Length).Wait();
                    _bufferSend = true;

                    if (_settings.ConnectionMode.Equals(ConnectionModes.PAY_AT_TABLE))
                    {
                        string data = Encoding.UTF8.GetString(buffer);
                        OnMessageSent?.Invoke(data.Substring(1, data.Length - 3));

                        return(null);
                    }

                    OnMessageSent?.Invoke(Encoding.UTF8.GetString(RemoveHeader(buffer)));
                    while (_termResponse == null)
                    {
                        Thread.Sleep(100);
                        if (_receivingException != null)
                        {
                            Exception ex = _receivingException;
                            _receivingException = null;
                            throw ex;
                        }

                        if (_termResponse != null)
                        {
                            // Remove timeout for stream  read
                            if (!_isKeepAlive)
                            {
                                _stream.ReadTimeout = -1;
                            }

                            _isResponseNeeded   = false;
                            _receivingException = null;
                        }
                    }

                    return(_termResponse);
                }
                else
                {
                    throw new ConfigurationException("No terminal connected to server.");
                }
            } catch (Exception ex) {
                throw new ApiException(ex.Message);
            }
        }
예제 #18
0
        internal CheckSubResponse DoCheck(IDeviceMessage request)
        {
            var response = _connector.Send(request);

            return(new CheckSubResponse(response));
        }
예제 #19
0
        internal CashResponse DoCash(IDeviceMessage request)
        {
            var response = _connector.Send(request);

            return(new CashResponse(response));
        }
예제 #20
0
        internal GiftResponse DoGift(IDeviceMessage request)
        {
            var response = _connector.Send(request);

            return(new GiftResponse(response));
        }
예제 #21
0
        internal EbtResponse DoEBT(IDeviceMessage request)
        {
            var response = _connector.Send(request);

            return(new EbtResponse(response));
        }
예제 #22
0
        internal DebitResponse DoDebit(IDeviceMessage request)
        {
            var response = _connector.Send(request);

            return(new DebitResponse(response));
        }
 private CancelResponse DoCancelRequest(IDeviceMessage request)
 {
     byte[] response = Send(request);
     return(new CancelResponse(response));
 }
예제 #24
0
 public byte[] Send(IDeviceMessage message)
 {
     return(_interface?.Send(message));
 }
예제 #25
0
        public byte[] Send(IDeviceMessage message)
        {
            byte[] buffer = message.GetSendBuffer();

            var readyReceived = false;

            byte[] responseMessage = null;

            Connect();
            try {
                var task = _stream.WriteAsync(buffer, 0, buffer.Length);

                if (!task.Wait(_settings.Timeout))
                {
                    throw new MessageException("Terminal did not respond in the given timeout.");
                }

                do
                {
                    var rvalue = _stream.GetTerminalResponseAsync();
                    if (rvalue != null)
                    {
                        var msgValue = GetResponseMessageType(rvalue);

                        switch (msgValue)
                        {
                        case UpaMessageType.Ack:
                            break;

                        case UpaMessageType.Nak:
                            break;

                        case UpaMessageType.Ready:
                            readyReceived = true;
                            break;

                        case UpaMessageType.Busy:
                            break;

                        case UpaMessageType.TimeOut:
                            break;

                        case UpaMessageType.Msg:
                            responseMessage = TrimResponse(rvalue);
                            if (IsNonReadyResponse(responseMessage))
                            {
                                readyReceived = true;     // since reboot doesn't return READY
                            }
                            SendAckMessageToDevice();
                            break;

                        default:
                            throw new Exception("Message field value is unknown in API response.");
                        }
                    }
                    else
                    {
                        // Reset the connection before the next attempt
                        Disconnect();
                        Connect();
                    }
                } while (!readyReceived);

                return(responseMessage);
            }
            catch (Exception exc) {
                throw new MessageException(exc.Message, exc);
            }
            finally {
                OnMessageSent?.Invoke(message.ToString());
                Disconnect();
            }
        }
 internal ReportResponse ReportRequest(IDeviceMessage request)
 {
     byte[] send = Send(request);
     return(new ReportResponse(send));
 }
예제 #27
0
 public byte[] Send(IDeviceMessage message)
 {
     message.AwaitResponse = true;
     return(_connector?.Send(message));
 }
        internal override ITerminalResponse ProcessTransaction(TerminalAuthBuilder builder)
        {
            IDeviceMessage request = BuildProcessTransaction(builder);

            return(DoRequest(request));
        }
 private IngenicoTerminalResponse DoReverseRequest(IDeviceMessage request)
 {
     byte[] response = Send(request);
     return(new IngenicoTerminalResponse(response));
 }
예제 #30
0
 public byte[] Send(IDeviceMessage message)
 {
     return(_connector?.Send(message));
 }