예제 #1
0
        /// <inheritdoc />
        public Task <ButtplugMessage> ParseMessage([NotNull] ButtplugDeviceMessage aMsg)
        {
            return(new Task <ButtplugMessage>(() =>
            {
                if (_isDisconnected)
                {
                    return BpLogger.LogErrorMsg(aMsg.Id, Error.ErrorClass.ERROR_DEVICE,
                                                $"{Name} has disconnected and can no longer process messages.");
                }

                if (!MsgFuncs.ContainsKey(aMsg.GetType()))
                {
                    return BpLogger.LogErrorMsg(aMsg.Id, Error.ErrorClass.ERROR_DEVICE,
                                                $"{Name} cannot handle message of type {aMsg.GetType().Name}");
                }

                // We just checked whether the key exists above, so we're ok.
                // ReSharper disable once PossibleNullReferenceException
                return MsgFuncs[aMsg.GetType()].Function.Invoke(aMsg).Result;
            }));
        }
        /// <summary>
        /// Sends a DeviceMessage (e.g. <see cref="VibrateCmd"/> or <see cref="LinearCmd"/>). Handles
        /// constructing some parts of the message for the user.
        /// </summary>
        /// <param name="aDevice">The device to be controlled by the message.</param>
        /// <param name="aDeviceMsg">The device message (Id and DeviceIndex will be overriden).</param>
        /// <returns>
        /// <see cref="Ok"/> message on success, <see cref="Error"/> message with error info otherwise.
        /// </returns>
        public Task <ButtplugMessage> SendDeviceMessage(ButtplugClientDevice aDevice, ButtplugDeviceMessage aDeviceMsg)
        {
            if (!_devices.TryGetValue(aDevice.Index, out ButtplugClientDevice dev))
            {
                var t = new Task <ButtplugMessage>(() => new Error("Device not available.", Error.ErrorClass.ERROR_DEVICE, ButtplugConsts.SystemMsgId));
                t.Start(TaskScheduler.Default);
                return(t);
            }

            if (!dev.AllowedMessages.ContainsKey(aDeviceMsg.GetType().Name))
            {
                var t = new Task <ButtplugMessage>(() => new Error("Device does not accept message type: " + aDeviceMsg.GetType().Name, Error.ErrorClass.ERROR_DEVICE, ButtplugConsts.SystemMsgId));
                t.Start(TaskScheduler.Default);
                return(t);
            }

            aDeviceMsg.DeviceIndex = aDevice.Index;
            return(SendMessage(aDeviceMsg));
        }