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);
            }
        }
Esempio n. 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);
            }
        }
Esempio n. 3
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();
            }
        }
Esempio n. 4
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();
            }
        }
        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);
            }
        }
Esempio n. 6
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;
                }
            }
        }
Esempio n. 7
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);
        }
Esempio n. 8
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);
            }
        }
        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);
            }
        }
Esempio n. 10
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();
            }
        }
        private async Task <bool> WriteMessage(IDeviceMessage message)
        {
            return(await Task.Run(() => {
                try {
                    int enquiryCount = 0;
                    _messageResponse = new List <byte>();

                    if (_serialPort == null)
                    {
                        return false;
                    }

                    do
                    {
                        _serialPort.Write(BitConverter.GetBytes((char)ControlCodes.ENQ), 0, 1);

                        if (!_isAcknowledge)
                        {
                            Thread.Sleep(1000);
                            _serialPort.Write(BitConverter.GetBytes((char)ControlCodes.EOT), 0, 1);
                            enquiryCount++;

                            if (enquiryCount.Equals(3))
                            {
                                throw new MessageException("Terminal did not respond in enquiry for three (3) times. Send aborted.");
                            }
                        }
                        else
                        {
                            do
                            {
                                byte[] msg = message.GetSendBuffer();
                                foreach (byte b in msg)
                                {
                                    byte[] _b = new byte[] { b };
                                    _serialPort.Write(_b, 0, 1);
                                }

                                if (_isAcknowledge)
                                {
                                    _serialPort.Write(BitConverter.GetBytes((char)ControlCodes.EOT), 0, 1);
                                    _isAcknowledge = false;
                                    break;
                                }
                            } while (true);

                            do
                            {
                                Thread.Sleep(100);
                                if (_isBroadcast)
                                {
                                    byte[] bMsg = Encoding.ASCII.GetBytes(_bufferReceived);
                                    BroadcastMessage broadcastMsg = new BroadcastMessage(bMsg);
                                    OnBroadcastMessage?.Invoke(broadcastMsg.Code, broadcastMsg.Message);
                                    _isBroadcast = false;
                                }

                                if (_isXML)
                                {
                                    while (!_transComplete)
                                    {
                                        if (_report.ToString().Contains(INGENICO_RESP.ENDXML))
                                        {
                                            string xmlData = _report.ToString().Substring(1, _report.ToString().Length - 3);

                                            if (MessageReceived(xmlData))
                                            {
                                                _serialPort.Write(BitConverter.GetBytes((char)ControlCodes.ACK), 0, 1);
                                                _report = new StringBuilder();
                                                _isXML = false;
                                                _transComplete = true;
                                            }
                                        }
                                        else
                                        {
                                            _report.Append(_bufferReceived);
                                        }

                                        Thread.Sleep(0500);
                                    }
                                    ;
                                }

                                if (_isResult)
                                {
                                    string check = Encoding.UTF8.GetString(message.GetSendBuffer());
                                    string refNumber = check.Substring(0, 2);

                                    if (_bufferReceived.Contains(refNumber))
                                    {
                                        do
                                        {
                                            string responseData = _bufferReceived.Substring(1, _bufferReceived.Length - 3);
                                            string actualReceived = _bufferReceived.Substring(1, _bufferReceived.Length - 3);
                                            bool validateLRC = ValidateResponseLRC(responseData, actualReceived);

                                            if (validateLRC)
                                            {
                                                if (MessageReceived(responseData))
                                                {
                                                    _serialPort.Write(BitConverter.GetBytes((char)ControlCodes.ACK), 0, 1);
                                                    _isResult = false;
                                                    _transComplete = true;
                                                }
                                            }
                                        } while (!_transComplete);
                                    }
                                }
                            } while (!_transComplete);

                            return _transComplete;
                        }
                    } while (true);
                } catch (ApiException e) {
                    throw new ApiException(e.Message);
                }
            }));
        }