internal async Task <bool> CloseAsync(WebSocketCloseStatus status, string description, CancellationToken token)
        {
            bool result = false;

            try
            {
                await _sendLock.WaitAsync();

                await _socket.CloseAsync(status, description, token);

                result = true;
            }
            catch (Exception e)
            {
                if (e.GetType() != typeof(TaskCanceledException))
                {
                    MsgLogger.Exception($"{GetType().Name} - CloseAsync", e);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - CloseAsync", "close requested");
                }
            }
            finally
            {
                _sendLock.Release();
            }

            return(result);
        }
        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);
        }
        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);
        }
Example #4
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);
        }
Example #5
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);
        }
Example #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);
        }
Example #7
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);
        }
Example #8
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);
        }
Example #9
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);
        }
        public override async Task <bool> PushCommand(ExecuteCommand execCommand)
        {
            bool result = false;

            try
            {
                var device = execCommand?.Command?.Device;

                if (device != null)
                {
                    var wsChannelId = GetActiveChannelName(execCommand.SourceChannelId, device.NodeId);

                    if (!string.IsNullOrEmpty(wsChannelId))
                    {
                        var start = MsgLogger.BeginTimeMeasure();

                        if (ConnectionManager != null && ConnectionManager.IsConnected(wsChannelId))
                        {
                            if (await ConnectionManager.Send(wsChannelId, _userIdentity, execCommand))
                            {
                                result = true;
                            }
                        }

                        MsgLogger.EndTimeMeasure($"{GetType().Name} - PushCommand", start, $"push command='{execCommand.Command.Name}' to device='{device.Family}':0x{device.NodeId}");
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - PushCommand", e);
            }

            return(result);
        }
Example #11
0
        public async Task <ParameterValue> GetParameterValue(string channelId, int nodeId, ushort index, byte subIndex)
        {
            ParameterValue result = null;

            try
            {
                MsgLogger.WriteLine($"get parameter, index=0x{index:X4}, subindex=0x{subIndex:X4}, device node id={nodeId}");

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

                query["callerId"] = channelId;
                query["nodeId"]   = $"{nodeId}";
                query["index"]    = $"{index}";
                query["subIndex"] = $"{subIndex}";

                var url = UrlHelper.BuildUrl(Url, "api/parameter/value", query);

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

                var parameterValue = json.TryDeserializeObject <ParameterValue>();

                if (parameterValue != null)
                {
                    result = parameterValue;

                    MsgLogger.WriteLine($"get parameter, index=0x{index:X4}, subindex=0x{subIndex:X4}, device node id={nodeId} - success");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - GetParameterValue", e);
            }

            return(result);
        }
Example #12
0
        public bool Register(RegisteredParameter registeredParameter)
        {
            bool result = false;

            MsgLogger.WriteFlow($"{GetType().Name} - Register", $"Register parameter source = '{registeredParameter.Key}', index = {registeredParameter.Parameter.Index:X4}, subindex = {(registeredParameter.Parameter as XddParameter).SubIndex:X4}");

            try
            {
                lock (RegisteredParametersLock)
                {
                    if (!_registeredParameters.ContainsKey(registeredParameter.Key))
                    {
                        result = AddToRegisteredParameters(registeredParameter);
                    }
                    else
                    {
                        result = UpdateParameterRefCount(registeredParameter);
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Register", e);
            }

            MsgLogger.WriteDebug($"{GetType().Name} - Register", $"Register Parameter '{registeredParameter.Key}' - OK");

            return(result);
        }
Example #13
0
        public async Task <bool> ExecuteCommands()
        {
            bool result = true;

            try
            {
                foreach (var deviceNode in SafeDevicesArray)
                {
                    var executeCommands = await DeviceControllerAdapter.PopCommands(deviceNode, ExecCommandStatus.Waiting);

                    foreach (var executeCommand in executeCommands)
                    {
                        if (!await ExecuteCommand(deviceNode, executeCommand))
                        {
                            result = false;
                        }
                    }

                    if (result)
                    {
                        result = DeviceControllerAdapter.Good;
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - ExecuteCommands", e);
                result = false;
            }

            return(result);
        }
        private Task SetMuteAsync(bool muteValue)
        {
            var result = Task.Run(() =>
            {
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    try
                    {
                        string muteString = muteValue ? "mute" : "unmute";

                        string args = $"-D pulse sset Master {muteString}";

                        var startInfo = new ProcessStartInfo("amixer");

                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.Arguments   = args;

                        SetExecutionStatus(StatusWordEnums.PendingExecution);

                        var startResult = Process.Start(startInfo);

                        MsgLogger.WriteFlow($"{GetType().Name} - SetMuteAsync", $"Mute request: {muteString}, result = {startResult!=null}");

                        SetExecutionStatus(startResult != null ? StatusWordEnums.ExecutedSuccessfully : StatusWordEnums.ExecutionFailed);
                    }
                    catch (Exception e)
                    {
                        MsgLogger.Exception($"{GetType().Name} - SetMuteAsync", e);
                    }
                }
            });

            return(result);
        }
Example #15
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);
        }
Example #16
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);
        }
Example #17
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);
        }
Example #18
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);
        }
Example #19
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);
        }
Example #20
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);
        }
Example #21
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);
        }
Example #22
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);
        }
Example #23
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);
        }
        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);
        }
Example #25
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);
        }
        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}");
        }
        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);
        }
Example #28
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);
        }
        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);
        }
        internal async Task <bool> CloseOutputAsync(WebSocketCloseStatus status, string description, CancellationToken token)
        {
            bool result = false;

            try
            {
                if (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.CloseSent)
                {
                    await _socket.CloseOutputAsync(status, description, token);

                    result = true;
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - CloseOutputAsync", $"wrong socket state = {_socket.State}");
                }
            }
            catch (Exception e)
            {
                if (e.GetType() != typeof(TaskCanceledException))
                {
                    MsgLogger.Exception($"{GetType().Name} - CloseOutputAsync", e);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - CloseOutputAsync", "close requested");
                }
            }

            return(result);
        }