예제 #1
0
        public async Task <UdpReceiveResult> Receive()
        {
            UdpReceiveResult result;

            try
            {
                _activityCounter++;

                result = await ReceiveAsync().WithCancellation(_tokenSource.Token);
            }
            catch (Exception e)
            {
                if (e.GetType() != typeof(OperationCanceledException))
                {
                    MsgLogger.Exception($"{GetType().Name} - Receive", e);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - Receive", "close requested");
                }
            }
            finally
            {
                _activityCounter--;
            }

            return(result);
        }
예제 #2
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Abort();

                try
                {
                    if (Client.Connected)
                    {
                        Client.Disconnect(false);
                    }
                }
                catch (Exception e)
                {
                    MsgLogger.Exception($"{GetType().Name} - Dispose", e);
                }

                int minWaitTime = 10;
                int maxWaitTime = 3000;

                var sw = new Stopwatch();
                sw.Start();

                while (_activityCounter > 0 && sw.ElapsedMilliseconds < maxWaitTime)
                {
                    Thread.Sleep(minWaitTime);
                }
            }

            base.Dispose(disposing);
        }
예제 #3
0
        private List <string> GetPortNames(string deviceName, string protocolStackName, string interfaceName)
        {
            var    result           = new List <string>();
            uint   errorCode        = 0;
            int    endOfSelection   = 0;
            int    startOfSelection = 1;
            string portName         = string.Empty;
            int    selectionResult  = 1;

            try
            {
                MsgLogger.WriteDebug($"{GetType().Name} - method", $"VcsGetPortNameSelection - enter - device = {deviceName}, protocol = {protocolStackName}, interface = {interfaceName}");

                while (endOfSelection == 0 && selectionResult > 0)
                {
                    selectionResult = VcsWrapper.Device.VcsGetPortNameSelection(deviceName, protocolStackName, interfaceName, startOfSelection, ref portName, ref endOfSelection, ref errorCode);

                    if (selectionResult > 0)
                    {
                        result.Add(portName);
                    }

                    startOfSelection = 0;
                }

                MsgLogger.WriteDebug($"{GetType().Name} - method", "VcsGetPortNameSelection - leave");
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - method", e);
            }

            return(result);
        }
예제 #4
0
        private List <string> GetProtocolInterfaceNames(string deviceName, string protocolStackName)
        {
            var result = new List <string>();

            uint   errorCode        = 0;
            int    endOfSelection   = 0;
            int    startOfSelection = 1;
            string interfaceName    = string.Empty;
            int    selectionResult  = 1;

            try
            {
                while (endOfSelection == 0 && selectionResult > 0)
                {
                    selectionResult = VcsWrapper.Device.VcsGetInterfaceNameSelection(deviceName, protocolStackName, startOfSelection, ref interfaceName, ref endOfSelection, ref errorCode);

                    if (selectionResult > 0)
                    {
                        result.Add(interfaceName);
                    }

                    startOfSelection = 0;
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - method", e);
            }

            return(result);
        }
예제 #5
0
        public async new Task <int> Send(byte[] datagram, int bytes)
        {
            int result = 0;

            try
            {
                _activityCounter++;

                result = await SendAsync(datagram, bytes).WithCancellation(_tokenSource.Token);
            }
            catch (Exception e)
            {
                if (e.GetType() != typeof(OperationCanceledException))
                {
                    MsgLogger.Exception($"{GetType().Name} - Send", e);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - Send", "close requested");
                }
            }
            finally
            {
                _activityCounter--;
            }

            return(result);
        }
예제 #6
0
        public double ToDouble()
        {
            double result = double.NaN;

            try
            {
                var byteArray = Convert.FromBase64String(Value);

                if (DataType != null)
                {
                    if (TypeCode.Double == DataType.Type)
                    {
                        result = BitConverter.ToInt32(byteArray, 0);
                    }
                    else
                    {
                        MsgLogger.WriteError($"{GetType().Name} - ToDouble", $"Cannot convert base64 value = {Value}, to data type {DataType.Type}!");
                    }
                }
                else
                {
                    MsgLogger.WriteWarning($"{GetType().Name} - ToDouble", $"Cannot convert base64 value = {Value}, unknown data type!");

                    result = BitConverter.ToInt32(byteArray, 0);
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - ToDouble", e);
            }

            return(result);
        }
예제 #7
0
        internal async Task <string> GetChannelId()
        {
            string result = string.Empty;

            try
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                var url = UrlHelper.BuildUrl(Url, "api/channel/id", query);

                var json = await Transporter.Get(_identity, url);

                if (!string.IsNullOrEmpty(json))
                {
                    var channelIdentification = json.TryDeserializeObject <ChannelIdentification>();

                    if (channelIdentification != null)
                    {
                        result = channelIdentification.Id;
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - GetChannelId", e);
            }

            return(result);
        }
예제 #8
0
        private string GetRsdxXmlDownloadName(string rsdxXmlContent)
        {
            string result = string.Empty;

            try
            {
                var rsdxXmlDoc = new XmlDocument();

                rsdxXmlDoc.LoadXml(rsdxXmlContent);

                var downloadNameNode = rsdxXmlDoc.SelectSingleNode("RadioSure/Stations/BaseFile/DownloadName");

                if (downloadNameNode != null && !string.IsNullOrEmpty(downloadNameNode.InnerXml))
                {
                    result = downloadNameNode.InnerXml;
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - GetRsdxXmlDownloadName", "download name node not found!");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - GetRsdxXmlDownloadName", e);
            }

            return(result);
        }
예제 #9
0
        /// <summary>
        /// Receive
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="shouldRunFunc"></param>
        /// <returns></returns>
        public async Task <string> Receive(string uniqueId, Func <bool> shouldRunFunc)
        {
            const int executeIntervalWs = 1;

            string result = string.Empty;

            try
            {
                string msg = string.Empty;

                do
                {
                    msg = await Receive(uniqueId);

                    if (shouldRunFunc())
                    {
                        await Task.Delay(executeIntervalWs);
                    }
                }while ((msg == "KEEPALIVE" || msg == "ACK") && shouldRunFunc());

                result = msg;
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Receive", e);
            }

            return(result);
        }
예제 #10
0
        /// <summary>
        /// Receive
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public async Task <T> Receive <T>(string uniqueId)
        {
            T   result      = default;
            var connections = FindConnections(uniqueId);

            foreach (var connection in connections)
            {
                if (connection.ReceiveSupported)
                {
                    try
                    {
                        var receiveResult = await connection.Receive <T>();

                        if (receiveResult != null)
                        {
                            result = receiveResult;
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        MsgLogger.Exception($"{GetType().Name} - Receive", e);
                    }
                }
            }

            return(result);
        }
예제 #11
0
        internal async Task <UserIdentity> CreateAlias(string role)
        {
            UserIdentity result = null;

            try
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["role"] = role;

                var url = UrlHelper.BuildUrl(Url, "api/user/create-alias", query);

                var json = await Transporter.Get(_identity, url);

                if (!string.IsNullOrEmpty(json))
                {
                    result = json.TryDeserializeObject <UserIdentity>();
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - CreateAlias", e);
            }

            return(result);
        }
예제 #12
0
        public async Task <bool> DownloadTool(UserIdentity identity, EltraDevice device)
        {
            bool result = false;

            var deviceToolSet = device?.ToolSet;

            if (PurgeToolStorage)
            {
                if (!PurgeToolFileSystem(device))
                {
                    MsgLogger.WriteError($"{GetType().Name} - DownloadTool", "purge file system failed!");
                }
            }

            if (deviceToolSet != null)
            {
                foreach (var tool in deviceToolSet.Tools)
                {
                    if (tool.Status == DeviceToolStatus.Enabled)
                    {
                        result = await UpdateTool(identity, tool);

                        if (!result)
                        {
                            break;
                        }
                    }
                }
            }

            return(result);
        }
예제 #13
0
        private async void OnDeviceStatusChanged(object sender, EventArgs e)
        {
            if (sender is EposDevice device)
            {
                switch (device.Status)
                {
                case DeviceStatus.Connected:
                {
                    MsgLogger.WriteLine($"Connected: device='{device.Family}', serial number=0x{device.Identification.SerialNumber:X}");

                    if (string.IsNullOrEmpty(device.Name))
                    {
                        device.Name = device.Identification.Name;
                    }

                    await CloudAgent.RegisterDevice(device);
                } break;

                case DeviceStatus.Disconnected:
                {
                    MsgLogger.WriteLine($"Disconnected: device = {device.Family} - Unregister");

                    await CloudAgent.UnregisterDevice(device);

                    device.Status = DeviceStatus.Unregistered;
                } break;
                }
            }
        }
        private bool GetHashCodeFromFile(string filePath, out string hashCode)
        {
            bool result = false;

            hashCode = string.Empty;

            try
            {
                var bytes = File.ReadAllBytes(filePath);

                if (bytes != null && bytes.Length > 0)
                {
                    var encodedBytes = Convert.ToBase64String(bytes);

                    hashCode = CryptHelpers.ToMD5(encodedBytes);

                    result = true;
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name}", e);
            }

            return(result);
        }
예제 #15
0
        public async Task <DeviceDescriptionPayload> Download(string channelId, DeviceVersion deviceVersion)
        {
            DeviceDescriptionPayload result = null;

            try
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["callerId"]           = channelId;
                query["hardwareVersion"]    = $"{deviceVersion.HardwareVersion}";
                query["softwareVersion"]    = $"{deviceVersion.SoftwareVersion}";
                query["applicationNumber"]  = $"{deviceVersion.ApplicationNumber}";
                query["applicationVersion"] = $"{deviceVersion.ApplicationVersion}";

                var url = UrlHelper.BuildUrl(Url, "api/description/download", query);

                var json = await Transporter.Get(_identity, url);

                if (!string.IsNullOrEmpty(json))
                {
                    result = json.TryDeserializeObject <DeviceDescriptionPayload>();

                    if (result != null)
                    {
                        result.Version = deviceVersion;
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Download", e);
            }

            return(result);
        }
예제 #16
0
        public static string GetLocalIpAddress()
        {
            const string host = "8.8.8.8";

            string result = string.Empty;

            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
                {
                    socket.Connect(host, 65530);

                    var endPoint = socket.LocalEndPoint as IPEndPoint;

                    if (endPoint != null)
                    {
                        result = endPoint.Address.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"IpHelper - GetLocalIpAddress", e);
            }

            return(result);
        }
예제 #17
0
        internal async Task <bool> PayloadExists(DeviceToolPayload payload)
        {
            bool result = false;

            try
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["callerId"] = payload.ChannelId;
                query["nodeId"]   = $"{payload.NodeId}";
                query["uniqueId"] = payload.Id;
                query["hashCode"] = payload.HashCode;
                query["mode"]     = $"{payload.Mode}";
                query["type"]     = $"{payload.Type}";

                var url = UrlHelper.BuildUrl(Url, "api/description/payload-exists", query);

                result = await Transporter.Get(_identity, url, CancellationToken.None);
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - PayloadExists", e);
            }

            return(result);
        }
예제 #18
0
        public async Task <bool> Exists(DeviceDescriptionPayload deviceDescription)
        {
            bool result = false;

            try
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["callerId"] = deviceDescription.ChannelId;
                query["nodeId"]   = $"{deviceDescription.NodeId}";
                query["hashCode"] = deviceDescription.HashCode;

                var url = UrlHelper.BuildUrl(Url, "api/description/exists", query);

                var json = await Transporter.Get(_identity, url);

                if (!string.IsNullOrEmpty(json))
                {
                    var requestResult = json.TryDeserializeObject <RequestResult>();

                    if (requestResult != null)
                    {
                        result = requestResult.Result;
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Exists", e);
            }

            return(result);
        }
        public void SetDisconnected()
        {
            bool result = false;

            if (Mutex.TryOpenExisting(LockingObjectName, out var lockingObject))
            {
                try
                {
                    if (lockingObject.WaitOne(0))
                    {
                        lockingObject.ReleaseMutex();
                    }

                    lockingObject.Close();

                    _lockingObject.Dispose();
                }
                catch (AbandonedMutexException e)
                {
                    MsgLogger.Exception($"{GetType().Name} - method", e);
                }
                catch (Exception e)
                {
                    MsgLogger.Exception($"{GetType().Name} - method", e);
                }

                _lockingObject = null;

                result = true;
            }

            MsgLogger.WriteLine($"Set device {_device.Family} disconnected = {result}");
        }
        public bool SetConnected()
        {
            bool result = false;

            try
            {
                if (Mutex.TryOpenExisting(LockingObjectName, out var lockingObject))
                {
                    result = lockingObject.WaitOne(0);
                }
                else
                {
                    _lockingObject = new Mutex(true, LockingObjectName);

                    result = _lockingObject != null;
                }
            }
            catch (AbandonedMutexException e)
            {
                MsgLogger.Exception($"{GetType().Name} - method", e);
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - method", e);
            }

            MsgLogger.WriteLine($"Set device {_device.Family} connected = {result}");

            return(result);
        }
예제 #21
0
        private void OnCommunicationStatusChanged(object sender, DeviceCommunicationEventArgs e)
        {
            var device        = e.Device as EposDevice;
            var eposEventArgs = e as EposCommunicationEventArgs;
            var status        = eposEventArgs?.Status;

            MsgLogger.WriteDebug($"{GetType().Name} - method", $"Device: {device.Family} ({device.PortName}) - state = {status}");

            switch (status)
            {
            case EposCommunicationStatus.Connected:
            {
                if (_statusManager.CheckState())     //detect fake connect
                {
                    Identification.Read();

                    Status = DeviceStatus.Connected;
                }
                else
                {
                    (Communication as Epos4DeviceCommunication).Disconnect();     // fake connection -> disconnect
                }
            } break;

            case EposCommunicationStatus.Disconnected:
            {
                Status = DeviceStatus.Disconnected;
            } break;

            case EposCommunicationStatus.Failed:
            {
                Status = DeviceStatus.Undefined;
            } break;
            }
        }
예제 #22
0
        private async Task <string> DownloadRsdxXml()
        {
            string result = string.Empty;

            try
            {
                var client = new HttpClient();

                var rsdxXmlContent = await client.GetStringAsync(RsdxUrl);

                if (!string.IsNullOrEmpty(rsdxXmlContent))
                {
                    result = rsdxXmlContent;
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - DownloadRsdxXml", "download content is empty!");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - DownloadRsdxXml", e);
            }

            return(result);
        }
예제 #23
0
        public override bool GetObject(ushort objectIndex, byte objectSubindex, ref byte[] data)
        {
            bool result;
            uint lastErrorCode     = 0;
            uint numberOfBytesRead = 0;

            lock (SyncObject)
            {
                var numberOfBytesToRead = (uint)data.Length;

                MsgLogger.WriteDebug($"{GetType().Name} - method", $"VcsGetObject - 0x{objectIndex:X4}, 0x{objectSubindex}, length = {numberOfBytesToRead}");

                result = VcsWrapper.Device.VcsGetObject(KeyHandle, NodeId, objectIndex, objectSubindex, data,
                                                        numberOfBytesToRead, ref numberOfBytesRead, ref lastErrorCode) > 0;

                if (numberOfBytesToRead != numberOfBytesRead)
                {
                    result = false;
                }
            }

            LastErrorCode = lastErrorCode;

            return(result);
        }
예제 #24
0
        protected bool ConnectToChannel()
        {
            bool result = false;

            var t = Task.Run(async() =>
            {
                if (ConnectionManager != null)
                {
                    MsgLogger.WriteLine($"{GetType().Name} - ConnectToChannel, connect to channel = {WsChannelName}");

                    if (await ConnectionManager.Connect(WsChannelId, WsChannelName))
                    {
                        if (!await SendChannelIdentyficationRequest())
                        {
                            MsgLogger.WriteError($"{GetType().Name} - ConnectToChannel", $"send ident request failed, channel = {WsChannelName}");
                        }
                        else
                        {
                            result = true;
                        }
                    }
                }
            });

            t.Wait();

            return(result);
        }
예제 #25
0
        public bool Run()
        {
            bool result = false;

            try
            {
                if (File.Exists(InputFileName))
                {
                    MsgLogger.WriteLine($"Read input file '{InputFileName}'");

                    if (ReadInput(out var base64EncodedInput))
                    {
                        result = GenerateOutput(base64EncodedInput);
                    }
                    else
                    {
                        MsgLogger.WriteError($"{GetType().Name} - Run", $"Reading file '{InputFileName}' failed!");
                    }
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - Run", $"Specified file '{InputFileName}' doesn't exist!");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Run", e);
            }

            return(result);
        }
예제 #26
0
        private async void OnDeviceDetected(object sender, ScannerDeviceStatusChangedEventArgs e)
        {
            var device = e.Device;

            if (device is EposDevice eposDevice)
            {
                AddDevice(device);

                RegisterDeviceEvents(eposDevice);

                MsgLogger.WriteDebug($"{GetType().Name} - method", $"try to connect to device {eposDevice.Family}");

                if (!await ConnectDevice(eposDevice))
                {
                    MsgLogger.WriteError($"{GetType().Name} - OnDeviceDetected", $"connect to device {eposDevice.Family} failed!");

                    UnregisterDeviceEvents(eposDevice);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - method", $"connect to device {eposDevice.Family} successful");
                }
            }
            else
            {
                MsgLogger.WriteLine($"device: {device.Family} not supported!");
            }
        }
예제 #27
0
        private bool GenerateOutput(string base64EncodedInput)
        {
            bool result = false;

            if (FileHelper.ChangeFileNameExtension(InputFileName, "md5", out var md5Path))
            {
                try
                {
                    string hashCode = CryptHelpers.ToMD5(base64EncodedInput);

                    OutputHashCode = hashCode;

                    File.WriteAllText(md5Path, hashCode);

                    OutputFileName = md5Path;
                }
                catch (Exception e)
                {
                    MsgLogger.Exception($"{GetType().Name} - GenerateOutput", e);
                }

                result = true;
            }
            else
            {
                MsgLogger.WriteError($"{GetType().Name} - Run", $"Cannot change file '{InputFileName}' extension!");
            }

            return(result);
        }
        private EltraPluginCacheItem FindPluginInFileSystem(DeviceToolPayload payload)
        {
            EltraPluginCacheItem result = null;
            var pluginFilePath          = GetPluginFilePath(GetPluginFileName(payload.Id));

            try
            {
                if (File.Exists(pluginFilePath))
                {
                    if (payload.Mode == DeviceToolPayloadMode.Development)
                    {
                        result = UpdateCache(payload, pluginFilePath);
                    }
                    else
                    {
                        if (GetHashCodeFromFile(pluginFilePath, out var hashCode) && hashCode == payload.HashCode)
                        {
                            result = UpdateCache(payload, pluginFilePath);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - FindPluginInFileSystem", e);
            }

            return(result);
        }
예제 #29
0
        /// <summary>
        /// Receive
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public async Task <string> Receive(string uniqueId)
        {
            string result      = string.Empty;
            var    connections = FindConnections(uniqueId);

            foreach (var connection in connections)
            {
                try
                {
                    var receiveResult = await connection.Receive();

                    if (!string.IsNullOrEmpty(receiveResult))
                    {
                        result = receiveResult;
                        break;
                    }
                }
                catch (Exception e)
                {
                    MsgLogger.Exception($"{GetType().Name} - Receive", e);
                }
            }

            return(result);
        }
예제 #30
0
    private void TestRoles(ClientAuthTokenReceived obj)
    {
        MsgLogger.LogMsg("TestRoles!!");
        var apiInstance = new UsersApi("https://auth.angusmf.com");

        apiInstance.Configuration.AddDefaultHeader("Authorization", string.Format("Bearer {0}", obj.token));


        try
        {
            var response = apiInstance.GetAllWithHttpInfo();
            if (response.StatusCode == 200)
            {
                MsgLogger.LogMsg(string.Format("user count = {0}", response.Data.Count));

                return;
            }
            else
            {
                MsgLogger.LogMsgError(string.Format("Error: Received response code {0} during GetAllWithHttpInfo", response.StatusCode));
            }
        }
        catch (Exception e)
        {
            MsgLogger.LogMsgError("Exception when calling apiInstance.GetAllWithHttpInfo: " + e.Message);
        }
    }
예제 #31
0
		/// <summary> Registers the MsgLogger 'ml' as the logging facility of the
		/// thread 't'. If any other logging facility was registered with
		/// the thread 't' it is overriden by 'ml'. If 't' is null then
		/// 'ml' is taken as the default message logger that is used for
		/// threads that have no MsgLogger registered.
		/// 
		/// </summary>
		/// <param name="t">The thread to associate with 'ml'
		/// 
		/// </param>
		/// <param name="ml">The MsgLogger to associate with therad ml
		/// 
		/// </param>
		internal static void  registerMsgLogger(SupportClass.ThreadClass t, MsgLogger ml)
		{
			if (ml == null)
			{
				throw new System.NullReferenceException();
			}
			if (t == null)
			{
				defMsgLogger = ml;
			}
			else
			{
				loggerList[t] = ml;
			}
		}