private void DeviceAddedHandler(object aObj, DeviceAddedEventArgs aEvent) { // Devices can be turned off by the time they get to this point, at which point they end up null. Make sure the device isn't null. if (aEvent.Device == null) { return; } var duplicates = from x in _devices where x.Value.Identifier == aEvent.Device.Identifier select x; if (duplicates.Any() && (duplicates.Count() > 1 || duplicates.First().Value.IsConnected)) { _bpLogger.Debug($"Already have device {aEvent.Device.Name} in Devices list"); return; } // If we get to 4 billion devices connected, this may be a problem. var deviceIndex = duplicates.Any() ? duplicates.First().Key : (uint)Interlocked.Increment(ref _deviceIndexCounter); _bpLogger.Info((duplicates.Any() ? "Re-" : string.Empty) + $"Adding Device {aEvent.Device.Name} at index {deviceIndex}"); _devices[deviceIndex] = aEvent.Device; aEvent.Device.DeviceRemoved += DeviceRemovedHandler; var msg = new DeviceAdded(deviceIndex, aEvent.Device.Name, GetAllowedMessageTypesAsStrings(aEvent.Device).ToArray()); DeviceMessageReceived?.Invoke(this, new MessageReceivedEventArgs(msg)); }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugJsonMessageParser"/> class. /// </summary> /// <param name="aLogManager">Log manager</param> public ButtplugJsonMessageParser(IButtplugLogManager aLogManager = null) { _bpLogger = aLogManager.GetLogger(GetType()); _bpLogger?.Info($"Setting up {GetType().Name}"); IEnumerable <Type> allTypes; // Some classes in the library may not load on certain platforms due to missing symbols. // If this is the case, we should still find messages even though an exception was thrown. try { allTypes = Assembly.GetAssembly(typeof(ButtplugMessage)).GetTypes(); } catch (ReflectionTypeLoadException e) { allTypes = e.Types; } var messageClasses = allTypes.Where(t => t != null && t.IsClass && t.Namespace == "Buttplug4Net35.Messages" && typeof(ButtplugMessage).IsAssignableFrom(t)); var enumerable = messageClasses as Type[] ?? messageClasses.ToArray(); _bpLogger?.Debug($"Message type count: {enumerable.Length}"); _messageTypes = new Dictionary <string, Type>(); enumerable.ToList().ForEach(aMessageType => { _bpLogger?.Debug($"- {aMessageType.Name}"); _messageTypes.Add(aMessageType.Name, aMessageType); }); }
public ButtplugServer(ButtplugServerOptions aOptions) { ButtplugUtils.ArgumentNotNull(aOptions, nameof(aOptions)); _clientName = null; _serverName = aOptions.ServerName; _maxPingTime = aOptions.MaxPingTime; _pingTimedOut = false; if (_maxPingTime != 0) { // Create a new timer that wont fire any events just yet _pingTimer = new Timer(PingTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite); } BpLogManager = new ButtplugLogManager(); _bpLogger = BpLogManager.GetLogger(GetType()); _bpLogger.Debug("Setting up ButtplugServer"); _parser = new ButtplugJsonMessageParser(BpLogManager); _deviceManager = aOptions.DeviceManager ?? new DeviceManager(BpLogManager, aOptions.SubtypeManagerSearchPaths); _bpLogger.Info("Finished setting up ButtplugServer"); _deviceManager.DeviceMessageReceived += DeviceMessageReceivedHandler; _deviceManager.ScanningFinished += ScanningFinishedHandler; if (!DeviceConfigurationManager.HasManager) { DeviceConfigurationManager.LoadBaseConfigurationFromResource(); } }
private void DeviceRemovedHandler(object aObj, EventArgs aEvent) { if ((aObj as ButtplugDevice) == null) { _bpLogger.Error("Got DeviceRemoved message from an object that is not a ButtplugDevice."); return; } var device = (ButtplugDevice)aObj; // The device itself will fire the remove event, so look it up in the dictionary and translate that for clients. var entry = (from x in _devices where x.Value.Identifier == device.Identifier select x).ToList(); if (!entry.Any()) { _bpLogger.Error("Got DeviceRemoved Event from object that is not in devices dictionary"); } if (entry.Count > 1) { _bpLogger.Error("Device being removed has multiple entries in device dictionary."); } foreach (var pair in entry.ToList()) { pair.Value.DeviceRemoved -= DeviceRemovedHandler; _bpLogger.Info($"Device removed: {pair.Key} - {pair.Value.Name}"); _devices.Remove(pair.Key); DeviceMessageReceived?.Invoke(this, new MessageReceivedEventArgs(new DeviceRemoved(pair.Key))); } }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugJsonMessageParser"/> class. /// </summary> /// <param name="aLogManager">Log manager, passed from the parser owner.</param> public ButtplugJsonMessageParser([NotNull] IButtplugLogManager aLogManager) { // Set up logging. if (aLogManager == null) { throw new ArgumentNullException(nameof(aLogManager)); } _bpLogger = aLogManager.GetLogger(GetType()); _bpLogger?.Info($"Setting up {GetType().Name}"); _serializer = new JsonSerializer { MissingMemberHandling = MissingMemberHandling.Error }; _messageTypes = new Dictionary <string, Type>(); foreach (var aMessageType in ButtplugUtils.GetAllMessageTypes()) { _bpLogger?.Debug($"- {aMessageType.Name}"); _messageTypes.Add(aMessageType.Name, aMessageType); } // If we can't find any message types in our assembly, the system is basically useless. if (!_messageTypes.Any()) { throw new ButtplugMessageException(_bpLogger, "No message types available."); } // Load the schema for validation. Schema file is an embedded resource in the library. var jsonSchemaString = ButtplugUtils.GetStringFromFileResource("B******g.b******g-schema.json"); _schema = JsonSchema.FromJsonAsync(jsonSchemaString)?.GetAwaiter().GetResult() ?? throw new InvalidOperationException(); }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugJsonMessageParser"/> class. /// </summary> /// <param name="aLogManager">Log manager</param> public ButtplugJsonMessageParser(IButtplugLogManager aLogManager = null) { _bpLogger = aLogManager.GetLogger(GetType()); _bpLogger?.Info($"Setting up {GetType().Name}"); _serializer = new JsonSerializer { MissingMemberHandling = MissingMemberHandling.Error }; IEnumerable <Type> allTypes; // Some classes in the library may not load on certain platforms due to missing symbols. // If this is the case, we should still find messages even though an exception was thrown. try { allTypes = Assembly.GetAssembly(typeof(ButtplugMessage)).GetTypes(); } catch (ReflectionTypeLoadException e) { allTypes = e.Types; } var messageClasses = allTypes.Where(t => t != null && t.IsClass && t.Namespace == "B******g.Core.Messages" && typeof(ButtplugMessage).IsAssignableFrom(t)); var enumerable = messageClasses as Type[] ?? messageClasses.ToArray(); _bpLogger?.Debug($"Message type count: {enumerable.Length}"); _messageTypes = new Dictionary <string, Type>(); enumerable.ToList().ForEach(aMessageType => { _bpLogger?.Debug($"- {aMessageType.Name}"); _messageTypes.Add(aMessageType.Name, aMessageType); }); // Load the schema for validation var assembly = Assembly.GetExecutingAssembly(); const string resourceName = "B******g.Core.b******g-schema.json"; Stream stream = null; try { stream = assembly.GetManifestResourceStream(resourceName); using (var reader = new StreamReader(stream)) { stream = null; var result = reader.ReadToEnd(); _schema = JsonSchema4.FromJsonAsync(result).GetAwaiter().GetResult(); } } catch (Exception e) { _bpLogger.LogException(e); throw e; } finally { stream?.Dispose(); } }
public ButtplugWSClient(string aClientName) { _clientName = aClientName; _bpLogManager = new ButtplugLogManager(); _bpLogger = _bpLogManager.GetLogger(GetType()); _parser = new ButtplugJsonMessageParser(_bpLogManager); _bpLogger.Info("Finished setting up ButtplugClient"); _owningDispatcher = Dispatcher.CurrentDispatcher; _tokenSource = new CancellationTokenSource(); }
public DeviceManager(IButtplugLogManager aLogManager) { _bpLogManager = aLogManager; _bpLogger = _bpLogManager.GetLogger(GetType()); _bpLogger.Info("Setting up DeviceManager"); _sentFinished = true; _devices = new Dictionary <uint, IButtplugDevice>(); _deviceIndexCounter = 0; _managers = new List <IDeviceSubtypeManager>(); }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugWSClient"/> class. /// </summary> /// <param name="aClientName">The name of the client (used by the server for UI and permissions).</param> public ButtplugWSClient(string aClientName) { _clientName = aClientName; IButtplugLogManager bpLogManager = new ButtplugLogManager(); _bpLogger = bpLogManager.GetLogger(GetType()); _parser = new ButtplugJsonMessageParser(bpLogManager); _bpLogger.Info("Finished setting up ButtplugClient"); _owningDispatcher = SynchronizationContext.Current ?? new SynchronizationContext(); _tokenSource = new CancellationTokenSource(); _counter = 0; }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugClient"/> class. /// </summary> /// <param name="aClientName">The name of the client (used by the server for UI and permissions).</param> /// <param name="aConnector">Connector for the client.</param> public ButtplugClient([NotNull] string aClientName, [NotNull] IButtplugClientConnector aConnector) { ButtplugUtils.ArgumentNotNull(aConnector, nameof(aConnector)); Name = aClientName; _connector = aConnector; _connector.Disconnected += (aObj, aEventArgs) => { ServerDisconnect?.Invoke(aObj, aEventArgs); }; _connector.InvalidMessageReceived += ConnectorErrorHandler; _bpLogManager = new ButtplugLogManager(); _connector.LogManager = _bpLogManager; _bpLogger = _bpLogManager.GetLogger(GetType()); _bpLogger.Info("Finished setting up ButtplugClient"); }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugJsonMessageParser"/> class. /// </summary> /// <param name="aLogManager">Log manager, passed from the parser owner.</param> public ButtplugJsonMessageParser([NotNull] IButtplugLogManager aLogManager) { // Set up logging. if (aLogManager == null) { throw new ArgumentNullException(nameof(aLogManager)); } _bpLogger = aLogManager.GetLogger(GetType()); _bpLogger?.Info($"Setting up {GetType().Name}"); _serializer = new JsonSerializer { MissingMemberHandling = MissingMemberHandling.Error }; _messageTypes = new Dictionary <string, Type>(); foreach (var aMessageType in ButtplugUtils.GetAllMessageTypes()) { _bpLogger?.Debug($"- {aMessageType.Name}"); _messageTypes.Add(aMessageType.Name, aMessageType); } // If we can't find any message types in our assembly, the system is basically useless. if (!_messageTypes.Any()) { throw new ButtplugMessageException(_bpLogger, "No message types available."); } // Load the schema for validation. Schema file is an embedded resource in the library. var assembly = Assembly.GetExecutingAssembly(); const string resourceName = "B******g.b******g-schema.json"; var stream = assembly.GetManifestResourceStream(resourceName); try { using (var reader = new StreamReader(stream ?? throw new InvalidOperationException())) { stream = null; var result = reader.ReadToEnd(); _schema = JsonSchema4.FromJsonAsync(result)?.GetAwaiter().GetResult() ?? throw new InvalidOperationException(); } } finally { // Always make sure we dispose of the resource stream, even if we throw. All // exceptions should be rethrown though. stream?.Dispose(); } }
public DeviceManager(IButtplugLogManager aLogManager, List <string> aSearchDirs = null) { ButtplugUtils.ArgumentNotNull(aLogManager, nameof(aLogManager)); _bpLogManager = aLogManager; _bpLogger = _bpLogManager.GetLogger(GetType()); _bpLogger.Info("Setting up DeviceManager"); _sentFinished = true; Devices = new Dictionary <uint, IButtplugDevice>(); DeviceIds = new Dictionary <string, uint>(); _deviceIndexCounter = 0; _isScanning = false; _managerSearchDirs = aSearchDirs ?? new List <string> { Directory.GetCurrentDirectory() }; _managers = new List <IDeviceSubtypeManager>(); }
public ButtplugServer([NotNull] string aServerName, uint aMaxPingTime, DeviceManager aDeviceManager = null) { _serverName = aServerName; _maxPingTime = aMaxPingTime; _pingTimedOut = false; if (aMaxPingTime != 0) { // Create a new timer that wont fire any events just yet _pingTimer = new Timer(PingTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite); } BpLogManager = new ButtplugLogManager(); _bpLogger = BpLogManager.GetLogger(GetType()); _bpLogger.Debug("Setting up ButtplugServer"); _parser = new ButtplugJsonMessageParser(BpLogManager); _deviceManager = aDeviceManager ?? new DeviceManager(BpLogManager); _bpLogger.Info("Finished setting up ButtplugServer"); _deviceManager.DeviceMessageReceived += DeviceMessageReceivedHandler; _deviceManager.ScanningFinished += ScanningFinishedHandler; BpLogManager.LogMessageReceived += LogMessageReceivedHandler; }