Esempio n. 1
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);
        }
        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);
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
        }
Esempio n. 6
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;
                }
            }
        }
        public override async Task <bool> SetCommandStatus(ExecuteCommandStatus status)
        {
            bool result = false;

            if (ConnectionManager != null && status != null)
            {
                var wsChannelId = GetActiveChannelName(status.ChannelId, status.NodeId);

                if (!string.IsNullOrEmpty(wsChannelId))
                {
                    MsgLogger.WriteLine($"set (WS) command='{status.CommandName}' status='{status.Status}' for device with nodeid={status.NodeId}");

                    if (await ConnectionManager.Send(wsChannelId, _userIdentity, status))
                    {
                        result = true;
                    }
                    else
                    {
                        MsgLogger.WriteError($"{GetType().Name} - SetCommandStatus",
                                             $"set (WS) command='{status.CommandName}' status='{status.Status}' for device with nodeid={status.NodeId} failed");
                    }
                }
            }

            return(result);
        }
Esempio n. 8
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!");
            }
        }
Esempio n. 9
0
        private void OnStatusChanged()
        {
            MsgLogger.WriteLine($"agent status changed to {Status}");

            StatusChanged?.Invoke(this, new AgentStatusEventArgs()
            {
                Status = Status
            });
        }
Esempio n. 10
0
        private async void OnVersionUpdated(object sender, DeviceVersionEventArgs e)
        {
            Status = DeviceStatus.VersionAvailable;

            var msg =
                $"Device version: 0x{e.Version.HardwareVersion:X} 0x{e.Version.SoftwareVersion:X} 0x{e.Version.ApplicationNumber:X} 0x{e.Version.ApplicationVersion:X}";

            MsgLogger.WriteLine(msg);

            await ReadDeviceDescriptionFile();
        }
Esempio n. 11
0
        private async void HandleBrokenConnection(WebSocketError errorCode)
        {
            MsgLogger.WriteError($"{GetType().Name} - HandleBrokenConnection", $"Connection to '{Url}' failed, error code = {errorCode}");

            if (errorCode == WebSocketError.ConnectionClosedPrematurely && Socket.State == WebSocketState.Open)
            {
                MsgLogger.WriteLine("try recover connection ...");

                Initialize();
            }

            await Task.Delay(100);
        }
Esempio n. 12
0
        public bool CanExecute(ExecuteCommand command)
        {
            bool result = false;

            _lock.Wait();

            if (command != null && !string.IsNullOrEmpty(command.CommandId))
            {
                var deviceCommand = command.Command;

                if (!_cache.ContainsKey(command.CommandId))
                {
                    _cache.Add(command.CommandId, new List <ExecuteCommandCacheEntry> {
                        new ExecuteCommandCacheEntry(deviceCommand)
                    });

                    result = true;
                }
                else
                {
                    var entryList = _cache[command.CommandId];

                    if (entryList != null && deviceCommand != null)
                    {
                        result = true;

                        foreach (var entry in entryList)
                        {
                            if (entry.Status == deviceCommand.Status)
                            {
                                result = false;
                                break;
                            }
                        }
                    }
                }

                Cleanup();
            }

            _lock.Release();

            if (!result)
            {
                MsgLogger.WriteLine($"drop command");
            }

            return(result);
        }
Esempio n. 13
0
        protected void OnIdentificationStateChanged(object sender, DeviceIdentificationEventArgs e)
        {
            if (e.State == DeviceIdentificationState.Success)
            {
                Status = DeviceStatus.Identified;

                MsgLogger.WriteLine($"Identified device='{e.Device.Family}' has serial number=0x{e.SerialNumber:X}");

                (Version as EposDeviceVersion)?.Read();
            }
            else if (e.State == DeviceIdentificationState.Failed)
            {
                MsgLogger.WriteLine($"Device: {e.Device.Family} ({(e.Device as EposDevice)?.PortName}) - Identification failed, reason={e.LastErrorCode}");
            }
        }
Esempio n. 14
0
        private bool AddToRegisteredParameters(RegisteredParameter registeredParameter)
        {
            bool result = false;

            if (_registeredParameters != null)
            {
                _registeredParameters.Add(registeredParameter.Key, registeredParameter);

                registeredParameter.RefCount++;

                MsgLogger.WriteLine($"(+)register parameter key='{registeredParameter.Key}'");

                result = true;
            }

            return(result);
        }
Esempio n. 15
0
        public bool Unregister(RegisteredParameter registeredParameter)
        {
            bool result = false;

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

            lock (RegisteredParametersLock)
            {
                if (_registeredParameters.ContainsKey(registeredParameter.Key))
                {
                    var parameter = _registeredParameters[registeredParameter.Key];

                    if (parameter != null)
                    {
                        parameter.RefCount--;

                        if (parameter.RefCount == 0)
                        {
                            result = _registeredParameters.Remove(registeredParameter.Key);

                            MsgLogger.WriteLine($"(-)unregister parameter key='{registeredParameter.Key}', result={result}");
                        }
                        else
                        {
                            MsgLogger.WriteLine($"(-)unregister parameter key='{registeredParameter.Key}', refCount = {parameter.RefCount}");

                            result = true;
                        }
                    }
                    else
                    {
                        MsgLogger.WriteError($"{GetType().Name} - Unregister", $"(-)unregister parameter key='{registeredParameter.Key}' failed, parameter empty!");
                    }
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - Unregister", $"(-)unregister parameter key='{registeredParameter.Key}' failed, parametere not found!");
                }
            }

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

            return(result);
        }
Esempio n. 16
0
        public async Task <ParameterValueHistoryStatistics> GetParameterHistoryStatistics(string callerId, int nodeId, string uniqueId, DateTime from, DateTime to)
        {
            ParameterValueHistoryStatistics result = null;

            try
            {
                MsgLogger.WriteLine($"get parameter history statistics, device node id={nodeId}");

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

                query["callerId"] = callerId;
                query["nodeId"]   = $"{nodeId}";
                query["uniqueId"] = $"{uniqueId}";
                query["from"]     = $"{from}";
                query["to"]       = $"{to}";

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

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

                if (!string.IsNullOrEmpty(json))
                {
                    var historyStatistics = json.TryDeserializeObject <ParameterValueHistoryStatistics>();

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

                        MsgLogger.WriteLine($"get parameter history statistics, device serial number={nodeId} - success");
                    }
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - GetParameterHistoryStatistics", $"get parameter history statistics, device serial number={nodeId} - failed");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - GetParameterHistoryStatistics", e);
            }

            return(result);
        }
Esempio n. 17
0
        public async Task <string> Receive()
        {
            string result = string.Empty;

            try
            {
                var wsMsg = await ReadWsMessage();

                if (wsMsg is WsMessageAck)
                {
                    result = wsMsg.Data;
                }
                else if (wsMsg != null)
                {
                    if (await Send(new UserIdentity(), new WsMessageAck()))
                    {
                        result          = wsMsg.Data;
                        LastCloseStatus = null;
                    }
                }
                else if (IsConnected)
                {
                    MsgLogger.WriteError($"{GetType().Name} - Receive", $"receive ws message failed!");
                }
                else
                {
                    MsgLogger.WriteLine($"receive ws message skipped, socket state = {Socket.State}!");
                }
            }
            catch (WebSocketException e)
            {
                MsgLogger.Exception($"{GetType().Name} - Receive", e);

                HandleBrokenConnection(e.WebSocketErrorCode);
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Receive", e);
            }

            return(result);
        }
Esempio n. 18
0
        static int Main(string[] args)
        {
            int result = 1;

            MsgLogger.LogOutputs = "Console;Debug;";
            MsgLogger.LogLevels  = MsgLogger.SupportedLogLevels;

            MsgLogger.WriteLine("Eltra navigo hash generator, Copyright (c) 2020 Dawid Sienkiewicz!");

            if (args.Length > 0)
            {
                string fileName = args[0];

                var hashGenerator = new HashGenerator()
                {
                    InputFileName = fileName
                };

                if (hashGenerator.Run())
                {
                    FileInfo fi = new FileInfo(fileName);
                    FileInfo fo = new FileInfo(hashGenerator.OutputFileName);

                    MsgLogger.WriteLine($"File '{fi.Name}' hash '{hashGenerator.OutputHashCode}' generation success!");

                    MsgLogger.WriteLine($"File '{fo.Name}' generation success!");
                    MsgLogger.WriteLine($"File output path '{fo.DirectoryName}'");

                    result = 0;
                }
                else
                {
                    MsgLogger.WriteError("Program - Main", $"File '{fileName}' hash generation failed!");
                }
            }
            else
            {
                MsgLogger.WriteError("Program - Main", "No file specified!");
            }

            return(result);
        }
Esempio n. 19
0
        private void QueueParameterChanged(ParameterChangeQueueItem queueItem)
        {
            queueItem.WorkingTask = Task.Run(async() =>
            {
                MsgLogger.WriteLine($"changed: {queueItem.UniqueId}, new value = '{CreateShortLogValue(queueItem.ActualValue)}'");

                bool skipProcessing = _parameterChangeQueue.ShouldSkip(queueItem);

                if (!skipProcessing)
                {
                    await UpdateParameterValue(queueItem.NodeId, queueItem.Index, queueItem.SubIndex, queueItem.ActualValue);
                }
                else
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - QueueParameterChanged", "Skip parameter change processing, queue already has item with higher timestamp");
                }
            });

            _parameterChangeQueue.Add(queueItem);
        }
Esempio n. 20
0
        private bool UpdateParameterRefCount(RegisteredParameter registeredParameter)
        {
            bool result    = false;
            var  parameter = _registeredParameters[registeredParameter.Key];

            if (parameter != null)
            {
                parameter.RefCount++;

                MsgLogger.WriteLine($"(+)register parameter key='{registeredParameter.Key}', refCount = {parameter.RefCount}");

                result = true;
            }
            else
            {
                MsgLogger.WriteError($"{GetType().Name} - Register", $"(+)register parameter key='{registeredParameter.Key}' failed, parameter empty!");
            }

            return(result);
        }
        public override async Task <bool> SetCommandStatus(ExecuteCommandStatus status)
        {
            bool result = false;

            if (ConnectionManager != null && ConnectionManager.IsConnected(CommandExecUuid))
            {
                MsgLogger.WriteLine($"set (WS) command='{status.CommandName}' status='{status.Status}' for device with nodeid={status.NodeId}");

                if (await ConnectionManager.Send(CommandExecUuid, UserIdentity, status))
                {
                    result = true;
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - SetCommandStatus",
                                         $"set (WS) command='{status.CommandName}' status='{status.Status}' for device with nodeid={status.NodeId} failed");
                }
            }

            return(result);
        }
Esempio n. 22
0
        public async Task <bool> RegisterDevice(EltraDevice device)
        {
            bool result = true;

            if (!await IsChannelRegistered())
            {
                if (await RegisterChannel())
                {
                    MsgLogger.WriteLine($"register channel='{Channel.Id}' success");
                }
                else
                {
                    MsgLogger.WriteError($"{GetType().Name} - RegisterDevice", $"register channel='{Channel.Id}' failed!");

                    result = false;
                }
            }

            if (result)
            {
                if (!await IsDeviceRegistered(device))
                {
                    result = await DeviceControllerAdapter.RegisterDevice(device);
                }
                else
                {
                    result = await DeviceControllerAdapter.UpdateDevice(device);
                }
            }

            if (result)
            {
                if (FindDevice(device.NodeId) == null)
                {
                    AddDevice(device);
                }
            }

            return(result);
        }
Esempio n. 23
0
        public async Task <bool> Upload(DeviceDescriptionPayload deviceDescription)
        {
            bool result = false;

            try
            {
                MsgLogger.WriteLine($"upload device description version='{deviceDescription.Version}'");

                var postResult = await Transporter.Post(_identity, Url, "api/description/upload", deviceDescription.ToJson());

                if (postResult.StatusCode == HttpStatusCode.OK)
                {
                    result = true;
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Upload", e);
            }

            return(result);
        }
Esempio n. 24
0
        internal async Task <bool> UploadPayload(DeviceToolPayload payload)
        {
            bool result = false;

            try
            {
                MsgLogger.WriteLine($"upload payload version='{payload.FileName}'");

                var postResult = await Transporter.Post(_identity, Url, "api/description/payload-upload", payload.ToJson());

                if (postResult.StatusCode == HttpStatusCode.OK)
                {
                    result = true;
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Upload", e);
            }

            return(result);
        }
Esempio n. 25
0
        public async Task <T> Receive <T>()
        {
            T result = default;

            try
            {
                var json = await Receive();

                if (IsJson(json))
                {
                    result = JsonConvert.DeserializeObject <T>(json);
                }
                else if (string.IsNullOrEmpty(json) && IsConnected)
                {
                    MsgLogger.WriteLine($"empty string received, close status='{Socket.CloseStatus}'");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - Receive", e);
            }

            return(result);
        }
Esempio n. 26
0
        public async Task <List <ParameterValue> > GetParameterHistory(string callerId, int nodeId, string uniqueId, DateTime from, DateTime to)
        {
            var result = new List <ParameterValue>();

            try
            {
                MsgLogger.WriteLine($"get parameter history, device serial number={nodeId}");

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

                query["callerId"] = callerId;
                query["nodeId"]   = $"{nodeId}";
                query["uniqueId"] = $"{uniqueId}";
                query["from"]     = $"{from}";
                query["to"]       = $"{to}";

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

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

                var parameterValues = json.TryDeserializeObject <ParameterValueList>();

                if (parameterValues != null)
                {
                    result = parameterValues.Items;

                    MsgLogger.WriteLine($"get parameter history, device serial number={nodeId} - success");
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - GetParameterHistory", e);
            }

            return(result);
        }
Esempio n. 27
0
        protected virtual void OnConnectionManagerChanged()
        {
            MsgLogger.WriteLine($"{GetType().Name} - OnConnectionManagerChanged, connection manager set, channel = {WsChannelName}");

            ConnectToChannel();
        }
Esempio n. 28
0
        private Task UpdateAvailableDevicesListAsync(string deviceName)
        {
            MsgLogger.WriteLine($"Update device: {deviceName}");

            return(Task.Run(() => UpdateAvailableDevicesList(_cancelationTokenSource.Token, deviceName)));
        }
Esempio n. 29
0
        public override async Task <bool> Update()
        {
            bool result = false;

            try
            {
                MsgLogger.WriteDebug($"{GetType().Name} - Update", $"Is channel='{Channel.Id}' registered...");

                if (await IsChannelRegistered())
                {
                    MsgLogger.WriteDebug($"{GetType().Name} - Update", $"Is any channel='{Channel.Id}' device not registered...");

                    if (await AnyDeviceUnRegistered())
                    {
                        MsgLogger.WriteLine($"re-register channel='{Channel.Id}' devices");

                        if (!await DeviceControllerAdapter.RegisterDevices())
                        {
                            MsgLogger.WriteError($"{GetType().Name} - Update", $"register channel='{Channel.Id}' devices failed!");
                        }
                    }

                    MsgLogger.Write($"{GetType().Name} - Update", $"Updating channel='{Channel.Id}' status...");

                    result = await SetChannelStatus(ChannelStatus.Online);
                }
                else
                {
                    MsgLogger.WriteLine($"Registering channel='{Channel.Id}' ...");

                    if (await RegisterChannel())
                    {
                        MsgLogger.Write($"{GetType().Name} - Update", $"updating channel='{Channel.Id}' status ...");

                        result = await SetChannelStatus(ChannelStatus.Online);

                        if (result)
                        {
                            MsgLogger.WriteLine($"update channel='{Channel.Id}' status success");
                        }
                        else
                        {
                            MsgLogger.WriteError($"{GetType().Name} - Update", $"update channel='{Channel.Id}' status failed!");
                        }
                    }
                    else
                    {
                        MsgLogger.WriteError($"{GetType().Name} - Update", $"register channel='{Channel.Id}' failed!");
                    }

                    if (result)
                    {
                        MsgLogger.WriteLine($"Registering devices='{Channel.Id}' ...");

                        result = await DeviceControllerAdapter.RegisterDevices();

                        if (result)
                        {
                            MsgLogger.WriteLine($"register channel='{Channel.Id}' devices success");
                        }
                        else
                        {
                            MsgLogger.WriteError($"{GetType().Name} - Update", $"register channel='{Channel.Id}' devices failed!");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MsgLogger.Exception($"{GetType().Name} - AnyDeviceUnRegistered", e);
            }

            return(result);
        }