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); }
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); }
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); }
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); }
internal async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> segment, CancellationToken token) { WebSocketReceiveResult result = null; try { await _receiveLock.WaitAsync(); result = await _socket.ReceiveAsync(segment, token); } catch (WebSocketException e) { MsgLogger.Exception($"{GetType().Name} - ReceiveAsync - error code = {e.WebSocketErrorCode}", e); await HandleWebSocketException(e, token); } catch (Exception e) { if (e.GetType() != typeof(TaskCanceledException)) { MsgLogger.Exception($"{GetType().Name} - ReceiveAsync", e); } else { MsgLogger.WriteDebug($"{GetType().Name} - ReceiveAsync", "close requested"); } } finally { _receiveLock.Release(); } 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); }
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!"); } }
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); }
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); }
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; } }
public async Task <bool> Disconnect() { bool result = false; try { if (IsConnected) { if (!_disconnectTokenSource.IsCancellationRequested) { _disconnectTokenSource.Cancel(); } if (Socket.State == WebSocketState.Open) { await Socket.CloseAsync(WebSocketCloseStatus.Empty, "", _cancellationTokenSource.Token); } else if (Socket.State == WebSocketState.Closed) { MsgLogger.WriteDebug($"{GetType().Name} - Disconnect", $"Disconnect, state = {Socket.State}"); } if (Socket.State == WebSocketState.Closed) { result = true; } } else { MsgLogger.WriteDebug($"{GetType().Name} - Disconnect", $"Disconnect, state = {Socket.State}"); } } catch (WebSocketException e) { MsgLogger.Exception($"{GetType().Name} - Disconnect", e); HandleBrokenConnection(e.WebSocketErrorCode); } catch (Exception e) { unchecked { if (e.HResult == (int)0x80131620) { MsgLogger.WriteError($"{GetType().Name} - Disconnect", "connection failed, reconnect"); Initialize(); } else { MsgLogger.Exception($"{GetType().Name} - Disconnect", e); } } } return(result); }
/// <summary> /// RegisterParameterUpdate /// </summary> /// <param name="device"></param> /// <param name="uniqueId"></param> /// <param name="priority"></param> /// <param name="waitForResult"></param> public bool RegisterParameterUpdate(EltraDevice device, string uniqueId, ParameterUpdatePriority priority = ParameterUpdatePriority.Low, bool waitForResult = false) { #pragma warning disable 4014 if (!string.IsNullOrEmpty(uniqueId) && device != null && device.SearchParameter(uniqueId) is XddParameter parameterEntry) { bool result = false; if (!ParameterRegistrationCache.IsParameterRegistered(uniqueId, parameterEntry.Index, parameterEntry.SubIndex, out var instanceCount)) { Task.Run(async() => { var command = await GetDeviceCommand(device, "RegisterParameterUpdate"); if (command != null) { command.SetParameterValue("Index", parameterEntry.Index); command.SetParameterValue("SubIndex", parameterEntry.SubIndex); command.SetParameterValue("Priority", (int)priority); result = await ExecuteCommandAsync(command); if (!result) { instanceCount = ParameterRegistrationCache.RemoveParameter(uniqueId); MsgLogger.WriteError($"{GetType().Name} - RegisterParameterUpdate", $"parameter could't be registered - '{uniqueId}'"); } else { MsgLogger.WriteDebug($"{GetType().Name} - RegisterParameterUpdate", $"registered parameter '{uniqueId}', instance count = {instanceCount}"); } } }).ConfigureAwait(waitForResult); } else { if (ParameterRegistrationCache.IncreaseCounter(uniqueId, out var registeredParameter)) { MsgLogger.WriteDebug($"{GetType().Name} - RegisterParameterUpdate", $"register parameter '{uniqueId}', instance count = {registeredParameter.InstanceCount}"); } else { MsgLogger.WriteError($"{GetType().Name} - RegisterParameterUpdate", $"register parameter '{uniqueId}', instance count = {instanceCount}"); } } } else { MsgLogger.WriteError($"{GetType().Name} - RegisterParameterUpdate", $"parameter '{uniqueId}' not found"); } #pragma warning restore 4014 return(true); }
protected virtual void OnCommandExecuted(object sender, ExecuteCommanderEventArgs e) { if (e.Command != null) { MsgLogger.WriteDebug($"{GetType().Name} - OnCommandExecuted", $"Command executed uuid='{e.CommandUuid}', status = {e.Status}"); AddCommandToExecuted(e.Command); } else { MsgLogger.WriteDebug($"{GetType().Name} - OnCommandExecuted", $"Command not found in pending list uuid='{e.CommandUuid}', status = {e.Status}"); } }
/// <summary> /// UnregisterParameterUpdate /// </summary> /// <param name="device"></param> /// <param name="uniqueId"></param> /// <param name="priority"></param> /// <param name="waitForResult"></param> public bool UnregisterParameterUpdate(EltraDevice device, string uniqueId, ParameterUpdatePriority priority = ParameterUpdatePriority.Low, bool waitForResult = false) { if (device != null && !string.IsNullOrEmpty(uniqueId) && device.SearchParameter(uniqueId) is Parameter parameterEntry) { bool result = false; if (ParameterRegistrationCache.CanUnregister(uniqueId, out var registeredParameter)) { var t = Task.Run(async() => { var command = await GetDeviceCommand(device, "UnregisterParameterUpdate"); if (command != null) { command.SetParameterValue("Index", parameterEntry.Index); command.SetParameterValue("SubIndex", parameterEntry.SubIndex); command.SetParameterValue("Priority", (int)priority); result = await ExecuteCommandAsync(command); if (!result) { ParameterRegistrationCache.AddParameter(registeredParameter); MsgLogger.WriteError($"{GetType().Name} - UnregisterParameterUpdate", $"parameter could't be unregistered - '{uniqueId}'"); } else { MsgLogger.WriteDebug($"{GetType().Name} - UnregisterParameterUpdate", $"unregistered parameter '{uniqueId}'"); } } }).ConfigureAwait(waitForResult); } else { registeredParameter?.Release(); MsgLogger.WriteDebug($"{GetType().Name} - UnregisterParameterUpdate", $"unregister parameter '{uniqueId}', instance count = {registeredParameter?.InstanceCount}"); result = true; } } else { MsgLogger.WriteError($"{GetType().Name} - UnregisterParameterUpdate", $"unregister: cannot find registered parameter '{uniqueId}'"); } return(true); }
private async Task <List <MotionControllerDevice> > GetDevices(string familyName) { var result = new List <MotionControllerDevice>(); var protocolStackNames = GetProtocolStackNames(familyName); var scanningSettings = _settings.Scanning; foreach (var protocolStackName in protocolStackNames) { if (scanningSettings.Skip.SkipProtocolStack(protocolStackName)) { MsgLogger.WriteDebug($"{GetType().Name} - method", $"skip protocol stack name: {protocolStackName}"); continue; } var interfaceNames = GetProtocolInterfaceNames(familyName, protocolStackName); foreach (var interfaceName in interfaceNames) { if (scanningSettings.Skip.SkipInterface(interfaceName)) { MsgLogger.WriteDebug($"{GetType().Name} - method", $"skip interface name: {interfaceName}"); continue; } var portNames = await GetPortNamesAsync(familyName, protocolStackName, interfaceName); foreach (var portName in portNames) { var device = new MotionControllerDevice(familyName, "" /*TODO*/, 1) { ProtocolStackName = protocolStackName, InterfaceName = interfaceName, Family = familyName, PortName = portName }; if (FindScannerDevice(result.ToArray(), device) == null) { result.Add(device); } } } } return(result); }
private async Task <bool> UpdateParameterValue(int nodeId, ushort index, byte subIndex, ParameterValue actualValue) { bool result = false; try { var parameterUpdate = new ParameterValueUpdate { ChannelId = Channel.Id, NodeId = nodeId, ParameterValue = actualValue, Index = index, SubIndex = subIndex }; var path = $"api/parameter/value"; var json = parameterUpdate.ToJson(); var response = await Transporter.Put(_identity, Url, path, json); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { MsgLogger.WriteDebug($"{GetType().Name} - UpdateParameterValue", $"Device Node id = {nodeId}, Parameter Index = 0x{index:X4}, Subindex = 0x{subIndex} value successfully written"); result = true; } else { MsgLogger.WriteError($"{GetType().Name} - UpdateParameterValue", $"Device Node id = {nodeId}, Parameter Index = 0x{index:X4}, Subindex = 0x{subIndex} value write failed, status code = {response.StatusCode}!"); } } else { MsgLogger.WriteError($"{GetType().Name} - UpdateParameterValue", $"Device Node id = {nodeId}, Parameter Index = 0x{index:X4}, Subindex = 0x{subIndex} value write failed!"); } } catch (Exception) { result = false; } return(result); }
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); }
private async Task UpdateAvailableDevicesList(CancellationToken token, string deviceName) { const int deviceUpdateWaitTime = 1000; do { var devices = await GetDevices(deviceName); foreach (var device in devices) { var existingDevice = FindScannerDevice(SafeDeviceArray, device); if (existingDevice == null || existingDevice.Status == DeviceStatus.Undefined || existingDevice.Status == DeviceStatus.Disconnected || existingDevice.Status == DeviceStatus.Unregistered) { MsgLogger.WriteDebug($"{GetType().Name} - method", $"create device name='{device.Family}', protocol='{device.ProtocolStackName}', intf='{device.InterfaceName}', port='{device.PortName}'"); var eposDevice = EposDeviceFactory.CreateDevice(device.Family, device.InterfaceName, device.ProtocolStackName, device.PortName, _settings.UpdateInterval, _settings.Timeout, device.NodeId); eposDevice.Status = DeviceStatus.Detected; lock (this) { if (existingDevice == null) { _devices.Add(eposDevice); } } OnDeviceDetected(new ScannerDeviceStatusChangedEventArgs { Device = eposDevice }); } } Thread.Sleep(deviceUpdateWaitTime); } while (!token.IsCancellationRequested); }
public bool ReadParameter(Parameter parameter) { bool result = false; var communication = _device?.Communication; MsgLogger.WriteDebug($"{GetType().Name} - ReadParameter", $"Read Parameter '{parameter.UniqueId}'"); lock (ParameterReadLock) { if (parameter != null) { if (parameter.Flags.Access != AccessMode.WriteOnly) { if (parameter.DataType != null) { var data = new byte[parameter.DataType.SizeInBytes]; MsgLogger.WriteDebug($"{GetType().Name} - ReadParameter", $"Get Object '0x{parameter.Index:X4} 0x{parameter.SubIndex:X4}', data size={parameter.DataType.SizeInBytes}"); if (communication.GetObject(parameter.Index, parameter.SubIndex, ref data)) { result = parameter.SetValue(data); } } else { MsgLogger.WriteError($"{GetType().Name} - ReadParameter", $"Parameter '{parameter.UniqueId}' Data Type not defined!"); } } else { MsgLogger.WriteError($"{GetType().Name} - ReadParameter", $"Parameter '{parameter.UniqueId}' cannot be read, access flag {parameter.Flags.Access}!"); result = false; } } } MsgLogger.WriteDebug($"{GetType().Name} - ReadParameter", $"Read Parameter '{parameter.UniqueId}' - result = '{result}'"); return(result); }
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); }
public bool IsConnected() { bool result = false; try { if (Mutex.TryOpenExisting(LockingObjectName, out _)) { result = true; } } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - method", e); } MsgLogger.WriteDebug($"{GetType().Name} - method", $"Is device {_device.Family} connected = {result}"); return(result); }
private void ProcessWsMessage(string json) { if (WsConnection.IsJson(json)) { var parameterChangedTask = Task.Run(() => { var parameterSet = json.TryDeserializeObject <ParameterValueUpdateList>(); if (parameterSet != null && parameterSet.Count > 0) { foreach (var parameterEntry in parameterSet.Items) { OnParameterValueChanged(new ParameterValueChangedEventArgs(parameterEntry.NodeId, parameterEntry.Index, parameterEntry.SubIndex, parameterEntry.ParameterValue)); } } else { var parameterEntry = json.TryDeserializeObject <ParameterValueUpdate>(); if (parameterEntry != null) { OnParameterValueChanged(new ParameterValueChangedEventArgs(parameterEntry.NodeId, parameterEntry.Index, parameterEntry.SubIndex, parameterEntry.ParameterValue)); } } }); lock (this) { _parameterChangedTasks.Add(parameterChangedTask); } } else { MsgLogger.WriteDebug($"{GetType().Name} - Execute", $"unknown message '{json}' received"); } }
public async Task <bool> SignIn(UserIdentity identity) { bool result = false; try { if (identity != null) { _identity = identity; var path = "api/user/sign-in"; if (string.IsNullOrEmpty(identity.Role)) { identity.Role = string.Empty; } var json = identity.ToJson(); var response = await Transporter.Post(identity, Url, path, json); if (response.StatusCode == HttpStatusCode.OK) { MsgLogger.WriteDebug($"{GetType().Name} - SignIn", $"Sign-in for user {identity.Login} successful!"); result = true; } else { MsgLogger.WriteError($"{GetType().Name} - SignIn", $"Sign-in for user {identity.Login} failed! status code = {response.StatusCode}"); } } } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - SignIn", e); } return(result); }
internal async Task <bool> SendAsync(ArraySegment <byte> arraySegments, WebSocketMessageType messageType, bool endOfMessage, CancellationToken token) { bool result = false; try { await _sendLock.WaitAsync(); await _socket.SendAsync(arraySegments, messageType, endOfMessage, token); result = true; } catch (WebSocketException e) { MsgLogger.Exception($"{GetType().Name} - SendAsync, error code = {e.WebSocketErrorCode}", e); await HandleWebSocketException(e, token); } catch (Exception e) { if (e.GetType() != typeof(TaskCanceledException)) { MsgLogger.Exception($"{GetType().Name} - SendAsync", e); } else { MsgLogger.WriteDebug($"{GetType().Name} - SendAsync", "close requested"); } } finally { _sendLock.Release(); } return(result); }
internal async Task <bool> ConnectAsync(Uri uri, CancellationToken token) { bool result = false; try { await _socket.ConnectAsync(uri, token); result = true; } catch (Exception e) { if (e.GetType() != typeof(OperationCanceledException)) { MsgLogger.Exception($"{GetType().Name} - ConnectAsync", e); } else { MsgLogger.WriteDebug($"{GetType().Name} - ConnectAsync", "close requested"); } } return(result); }
private bool UpdatePluginCache(string assemblyPath, DeviceToolPayload payload) { bool result = false; try { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"load assembly - path = {assemblyPath}"); var theAssembly = Assembly.LoadFrom(assemblyPath); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", "load assembly - get types"); Type[] types = theAssembly.GetTypes(); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"load assembly - get types - count = {types.Length}"); foreach (Type t in types) { try { var type = t.GetInterface("EltraXamCommon.Plugins.IEltraNavigoPlugin"); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"type full name = {t.FullName}"); if (type != null && !string.IsNullOrEmpty(t.FullName)) { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"create instance $ {t.FullName}"); var assemblyInstace = theAssembly.CreateInstance(t.FullName, false); if (assemblyInstace is IEltraNavigoPlugin pluginInterface) { pluginInterface.DialogService = _dialogService; MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"find payload {payload.FileName}"); if (FindPluginInCache(payload) == null) { var pluginCacheItem = new EltraPluginCacheItem() { FullPath = assemblyPath, HashCode = payload.HashCode, PayloadId = payload.Id, Plugin = pluginInterface }; PluginCache.Add(pluginCacheItem); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"add payload {payload.FileName} cache item"); } else { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"payload {payload.FileName} already added"); } result = true; break; } else { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"error: create instance $ {t.FullName} failed!"); } } } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - UpdatePluginCache [1]", e); } } } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - UpdatePluginCache [2]", e); } return(result); }
public bool Connect() { bool result = false; MsgLogger.WriteDebug($"{GetType().Name} - method", "Connect ..."); if (!Connected) { lock (this) { try { uint lastErrorCode = 0; var device = Device as EposDevice; lock (SyncObject) { MsgLogger.WriteDebug($"{GetType().Name} - method", $"VcsOpenDevice - device name='{device.Family}', interface='{device.InterfaceName}', port='{device.PortName}'"); KeyHandle = VcsWrapper.Device.VcsOpenDevice(device.Family, device.ProtocolStackName, device.InterfaceName, device.PortName, ref lastErrorCode); var deviceName = new StringBuilder(255); if (VcsWrapper.Device.VcsGetDeviceName(KeyHandle, deviceName, 255, ref lastErrorCode) > 0) { device.Name = deviceName.ToString(); } } var status = KeyHandle != 0 ? EposCommunicationStatus.Connected : EposCommunicationStatus.Failed; result = status == EposCommunicationStatus.Connected; if (status == EposCommunicationStatus.Connected) { _statusManager.SetConnected(); } MsgLogger.WriteDebug($"{GetType().Name} - method", $"Connect - send new status = {status}"); OnStatusChanged(new EposCommunicationEventArgs { Device = device, LastErrorCode = lastErrorCode, Status = status }); } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - method", e); } } } else { result = true; } MsgLogger.WriteDebug($"{GetType().Name} - method", $"Connect - result = {result}"); return(result); }
private async Task <bool> ExecuteCommand(EltraDevice device, ExecuteCommand executeCommand) { bool result = false; try { if (executeCommand != null && _executeCommandCache.CanExecute(executeCommand)) { var s = MsgLogger.BeginTimeMeasure(); var sourceChannelId = executeCommand.SourceChannelId; var commandName = executeCommand.Command?.Name; var deviceCommand = device.FindCommand(commandName); if (deviceCommand != null) { if (await DeviceControllerAdapter.SetCommandStatus(executeCommand, ExecCommandStatus.Executing)) { try { MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Clone Command '{commandName}'"); var clonedDeviceCommand = deviceCommand.Clone(); if (clonedDeviceCommand != null) { MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Sync Command '{commandName}'"); clonedDeviceCommand.Sync(executeCommand.Command); MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Execute Command '{commandName}', channel '{executeCommand.SourceChannelId}'"); try { var start = MsgLogger.BeginTimeMeasure(); result = clonedDeviceCommand.Execute(executeCommand.SourceChannelId, executeCommand.SourceLoginName); MsgLogger.EndTimeMeasure($"{GetType().Name} - ExecuteCommand", start, $"command '{executeCommand.Command.Name}' executed, result = {result}"); } catch (Exception e) { MsgLogger.Exception($"{GetType().Name} - ExecuteCommand", e); } if (result) { var start = MsgLogger.BeginTimeMeasure(); MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Sync Response Command '{commandName}'"); executeCommand.Command?.Sync(clonedDeviceCommand); MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Push Response for Command '{commandName}'"); executeCommand.SourceChannelId = Channel.Id; executeCommand.TargetChannelId = sourceChannelId; result = await DeviceControllerAdapter.PushCommand(executeCommand, ExecCommandStatus.Executed); if (result) { MsgLogger.WriteDebug($"{GetType().Name} - ExecuteCommand", $"Command '{commandName}' successfully processed!"); } else { MsgLogger.WriteError($"{GetType().Name} - ExecuteCommand", $"Set command '{commandName}' status to exectuted failed!"); } MsgLogger.EndTimeMeasure($"{GetType().Name} - ExecuteCommand", start, $"command '{executeCommand.Command.Name}' state synchronized, result = {result}"); } else { var command = executeCommand.Command; MsgLogger.WriteError($"{GetType().Name} - ExecuteCommand", command != null ? $"Command '{command.Name}' uuid '{executeCommand.CommandId}' execution failed!" : $"Command '?' uuid '{executeCommand.CommandId}' execution failed!"); executeCommand.SourceChannelId = Channel.Id; executeCommand.TargetChannelId = sourceChannelId; await DeviceControllerAdapter.SetCommandStatus(executeCommand, ExecCommandStatus.Failed); } } else { await DeviceControllerAdapter.SetCommandStatus(executeCommand, ExecCommandStatus.Failed); MsgLogger.WriteError($"{GetType().Name} - ExecuteCommand", $"Command '{commandName}' cloning failed!"); } } catch (Exception e) { await DeviceControllerAdapter.SetCommandStatus(executeCommand, ExecCommandStatus.Failed); MsgLogger.Exception($"{GetType().Name} - ExecuteCommand", e); } } else { MsgLogger.WriteError($"{GetType().Name} - ExecuteCommand", $"Set Command '{commandName}' status to executing failed!"); } } else { MsgLogger.WriteError($"{GetType().Name} - ExecuteCommand", $"Command '{commandName}' not found!"); } MsgLogger.EndTimeMeasure($"{GetType().Name} - ExecuteCommand", s, $"command '{executeCommand.Command?.Name}' executed, result = {result}"); } } catch (Exception e) { result = false; MsgLogger.Exception($"{GetType().Name} - ExecuteCommand", e); } return(result); }
private bool UpdatePluginCache(string assemblyPath, DeviceToolPayload payload) { bool result = false; try { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"load assembly - path = {assemblyPath}"); var payloadPath = PluginStore.GetAssemblyFile(payload.Id); if (!string.IsNullOrEmpty(payloadPath)) { assemblyPath = payloadPath; } if (!string.IsNullOrEmpty(assemblyPath)) { var pluginAssembly = Assembly.LoadFrom(assemblyPath); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", "load assembly - get types"); Type[] types = pluginAssembly.GetTypes(); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"load assembly - get types - count = {types.Length}"); foreach (Type t in types) { try { var type = t.GetInterface("EltraXamCommon.Plugins.IEltraNavigoPluginService"); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"type full name = {t.FullName}"); if (type != null && !string.IsNullOrEmpty(t.FullName)) { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"create instance $ {t.FullName}"); var assemblyInstace = pluginAssembly.CreateInstance(t.FullName, false); string name = pluginAssembly.GetName().Name; string version = pluginAssembly.GetName().Version.ToString(); if (assemblyInstace is IEltraNavigoPluginService pluginService) { pluginService.DialogRequested += OnPluginInterfaceDialogRequested; MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"find payload {payload.FileName}"); if (FindPluginInCache(payload) == null) { var pluginCacheItem = new EltraPluginCacheItem() { Name = name, FullPath = assemblyPath, HashCode = payload.HashCode, PayloadId = payload.Id, PluginService = pluginService, Version = version }; PluginCache.Add(pluginCacheItem); MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"add payload {payload.FileName} cache item"); } else { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"payload {payload.FileName} already added"); } result = true; break; } else { MsgLogger.WriteDebug($"{GetType().Name} - UpdatePluginCache", $"error: create instance $ {t.FullName} failed!"); } } } catch (Exception e) { GC.Collect(); GC.WaitForPendingFinalizers(); MsgLogger.Exception($"{GetType().Name} - UpdatePluginCache [1]", e); } } } else { MsgLogger.WriteError($"{GetType().Name} - UpdatePluginCache", "assembly store returns empty element"); } } catch (Exception e) { GC.Collect(); GC.WaitForPendingFinalizers(); MsgLogger.Exception($"{GetType().Name} - UpdatePluginCache [2]", e); } return(result); }
private bool ParametersUpdate() { bool result = true; lock (RegisteredParametersLock) { if (_registeredParameters.Count > 0) { //MsgLogger.WriteDebug($"{GetType().Name} - ParametersUpdate", $"Parameters to update count = {_registeredParameters.Count}"); foreach (var registeredParameter in _registeredParameters.Values) { if (!ShouldRun()) { break; } if (registeredParameter.ElapsedTime >= _device.GetUpdateInterval(registeredParameter.Priority)) { var parameter = registeredParameter.Parameter; if (parameter is Parameter parameterEntry) { MsgLogger.WriteDebug($"{GetType().Name} - ParametersUpdate", $"Update Parameter '{parameterEntry.UniqueId}'"); result = ReadParameter(parameterEntry); if (!result) { MsgLogger.WriteError($"{GetType().Name} - ParametersUpdate", $"Read Parameter '{parameterEntry.UniqueId}' failed!"); } } else if (parameter is StructuredParameter structuredParameter) { var subParameters = structuredParameter.Parameters; if (subParameters != null) { foreach (var subParameter in subParameters) { if (!ShouldRun()) { break; } if (subParameter is Parameter subParameterEntry) { result = ReadParameter(subParameterEntry); if (!result) { MsgLogger.WriteError($"{GetType().Name} - ParametersUpdate", $"Read Parameter '{subParameterEntry.UniqueId}' failed!"); } } } } } registeredParameter.Restart(); } } } } return(result); }