Inheritance: PrivateSingletonBehaviour
        private DeviceEvent FillingChanged(float oldValue, float newValue, EventSender sender)
        {
            if (newValue != 0.0 && newValue != 1.0)
                return null;

            var result = new DeviceEvent
            {
                DeviceId = Id,
                Time = DateTime.Now,
                Sender = sender,
                Arguments = null
            };

            if (newValue == 0.0)
            {
                result.Type = DeviceEventType.TankEmpty;
                result.Notification = EventNotification.Warning;
            }
            else if (newValue == 1.0)
            {
                result.Type = DeviceEventType.TankFull;
                result.Notification = EventNotification.Success;
            }
            return result;
        }
        private void initAllDevComp()
        {
            fpc = new FunctionParameterCollection();
            //devCap = new DeviceCapabilities();

            dev        = new Device();
            AllDevices = new DeviceCollection();

            devevent = new DeviceEvent();
            devFunc  = new DeviceFunction();
            devProp  = new DeviceProperty();

            WorkflowActions = new WorkflowActionCollection();
        }
        private static IDeviceEventReceiver CreateDeviceEventReceiverFake(DeviceEvent deviceEvent)
        {
            var deviceEventReceiverFake = new Mock <IDeviceEventReceiver>();

            deviceEventReceiverFake.Setup(x => x.ConnectAsync(It.IsNotNull <CancellationToken>())).
            Returns(Task.CompletedTask);
            deviceEventReceiverFake.Setup(x => x.ReceiveAsync(It.IsNotNull <CancellationToken>())).
            Returns(Task.CompletedTask).
            Raises(x => x.EventReceived += null, deviceEventReceiverFake, deviceEvent);
            deviceEventReceiverFake.Setup(x => x.ConnectionParameters).
            Returns(CreateConnectionParametersFake());

            return(deviceEventReceiverFake.Object);
        }
Exemple #4
0
        private void initAllDevComp()
        {
            fpc    = new FunctionParameterCollection();
            devCap = new DeviceCapabilities();

            dev          = new Device();
            devcol       = new DeviceCollection();
            devEventColl = new DeviceEventCollection();
            devfuncColl  = new DeviceFunctionCollection();
            devPropColl  = new DevicePropertyCollection();
            devevent     = new DeviceEvent();
            devFunc      = new DeviceFunction();
            devProp      = new DeviceProperty();
        }
Exemple #5
0
        public async Task RunAsync(CancellationToken token)
        {
            while (token.IsCancellationRequested == false)
            {
                EventSummary summary = await _queue.DequeueAsync(token);

                try
                {
                    using (var session = da.SessionFactory.OpenStatelessSession())
                        using (var txn = session.BeginTransaction())
                        {
                            foreach (ushort Code in summary.RecoverEvents)
                            {
                                await RecoverEventAsync(session, summary, Code, token);
                            }


                            foreach (ushort Code in summary.NewEvents)
                            {
                                EventMap map = await session.GetAsync <EventMap>(Code, token);

                                if (map == null)
                                {
                                    _logger.Warn($"DB상에 존재하지 않는 이벤트 코드입니다. 이벤트 코드:{Code}");
                                    continue;
                                }

                                DeviceEvent ae = new DeviceEvent();

                                byte[] descBuffer = Encoding.UTF8.GetBytes(map.Description);
                                ae.DeviceName     = summary.DeviceName;
                                ae.EventId        = CreateEventId(session, summary, Code);
                                ae.EventCode      = Code;
                                ae.OccurTimestamp = summary.GetTimestamp();
                                ae.siteId         = summary.SiteId;
                                await session.InsertAsync(ae, token);
                            }


                            await txn.CommitAsync(token);
                        }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex);
                }
            }
            _logger.Info("Abort RunAsync");
        }
Exemple #6
0
 /// <summary>
 /// Get device.
 /// </summary>
 /// <param name="deviceEvent">Device event.</param>
 /// <returns>device.</returns>
 internal static Device GetDevice(this DeviceEvent deviceEvent)
 {
     if (keyEvents.Contains(deviceEvent))
     {
         return(Device.Keyboard);
     }
     else if (mouseEvents.Contains(deviceEvent))
     {
         return(Device.Mouse);
     }
     else
     {
         return(Device.Nothing);
     }
 }
Exemple #7
0
 public DeviceCommandAckMessage(MessageCode code, byte[] message, out byte[] innerMessage)
     : base(code)
 {
     EventCode = (DeviceEvent)message[0];
     if (message.Length > 1)
     {
         byte[] msg = new byte[message.Length - 1];
         Array.Copy(message, 1, msg, 0, msg.Length);
         innerMessage = msg;
     }
     else
     {
         innerMessage = new byte[] { };
     }
 }
Exemple #8
0
        public void EventHandling_DeviceEventFromModel_EventAddedToEventsCollection()
        {
            var deviceEvent         = new DeviceEvent("test");
            var mainWindowModelMock = new Mock <IMainWindowModel>();

            mainWindowModelMock.Setup(x => x.Start(It.IsNotNull <ConnectionParameters>()))
            .Raises(x => x.EventReceived += null, this, deviceEvent);

            var mainWindowViewModel = new MainWindowViewModel(mainWindowModelMock.Object);

            mainWindowViewModel.StartClickCommand.Execute(null);

            Assert.AreEqual(1, mainWindowViewModel.Events.Count);
            Assert.AreSame(deviceEvent, mainWindowViewModel.Events[0]);
        }
Exemple #9
0
        private void AddDeviceEvent(DeviceEvent deviceEvent)
        {
            ExecuteOnDispatcher(() =>
            {
                if (!string.IsNullOrWhiteSpace(deviceEvent.BVideoName))
                {
                    EventVideos.Insert(0, new EventVideo(deviceEvent));
                }

                if (!string.IsNullOrWhiteSpace(deviceEvent.ImageName))
                {
                    EventImages.Insert(0, new EventImage(deviceEvent));
                }
            });
        }
        /// <summary>
        /// 上报固件版本信息
        /// </summary>
        /// <param name="version">固件版本</param>
        public void ReportVersion(string version)
        {
            Dictionary <string, object> node = new Dictionary <string, object>();

            node.Add("fw_version", version);
            node.Add("sw_version", version);

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "version_report";
            deviceEvent.paras     = node;
            deviceEvent.serviceId = "$ota";
            deviceEvent.eventTime = IotUtil.GetEventTime();

            iotDevice.GetClient().ReportEvent(deviceEvent);
        }
Exemple #11
0
        /// <summary>
        /// 向平台请求同步子设备信息
        /// </summary>
        protected void SyncSubDevices()
        {
            Log.Info("start to syncSubDevices, local version is " + subDevicesPersistence.GetVersion());

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "sub_device_sync_request";
            deviceEvent.serviceId = "sub_device_manager";
            deviceEvent.eventTime = IotUtil.GetTimeStamp();

            Dictionary <string, object> para = new Dictionary <string, object>();

            para.Add("version", subDevicesPersistence.GetVersion());
            deviceEvent.paras = para;
            GetClient().ReportEvent(deviceEvent);
        }
        private void OnDeviceEvent(DeviceEvent deviceEvent)
        {
            var device = deviceEvent.device;

            switch (deviceEvent.type)
            {
            case DeviceEvent.EType.NewData: // TODO [email protected]: This may not be needed
            case DeviceEvent.EType.NameChanged:
                UpdateLabels();
                break;

            case DeviceEvent.EType.ConnectionChange:
                UpdateActivityViews();
                break;
            }
        }
        protected override IDeviceEvent CreateDeviceEvent()
        {
            var state = GetValue();

            if (state == true)
            {
                return(DeviceEvent.PoweredOn(Device, null));
            }

            if (state == false)
            {
                return(DeviceEvent.PoweredOff(Device, null));
            }

            return(DeviceEvent.PowerChanged(Device, null));
        }
 /// <summary>
 /// Called when a device is deleted from the device manager.
 /// </summary>
 /// <param name="deviceEvent">Device event.</param>
 private void OnDeviceEvent(DeviceEvent deviceEvent)
 {
     // TODO [email protected]: Right now when a device is deleted from the application and the workbench
     // goes to reflect the change, the workbench will do a cascade delete that may leave the application in
     // a weird position. It may be worth it to pop-up a dialog that will inform the user that the app is about
     // to experiece a huge change as the device is removed from all sources.
     switch (deviceEvent.type)
     {
     case DeviceEvent.EType.Deleted:
         if (ContainsDevice(deviceEvent.device))
         {
             RemoveUsesOfDevice(deviceEvent.device);
         }
         break;
     }
 }
        public void RequestTimeSync()
        {
            Dictionary <string, object> node = new Dictionary <string, object>();

            node.Add("device_send_time", IotUtil.GetTimeStamp());

            DeviceEvent deviceEvent = new DeviceEvent();

            deviceEvent.eventType = "time_sync_request";
            deviceEvent.paras     = node;
            deviceEvent.serviceId = "$time_sync";
            deviceEvent.eventTime = IotUtil.GetEventTime();

            iotDevice.GetClient().messagePublishListener = this;
            iotDevice.GetClient().ReportEvent(deviceEvent);
        }
        public override void OnEvent(DeviceEvent deviceEvent)
        {
            if (listener == null)
            {
                return;
            }

            if (deviceEvent.eventType == "time_sync_response")
            {
                Dictionary <string, object> node = deviceEvent.paras;
                long device_send_time            = Convert.ToInt64(node["device_send_time"]);
                long server_recv_time            = Convert.ToInt64(node["server_recv_time"]);
                long server_send_time            = Convert.ToInt64(node["server_send_time"]);

                listener.OnTimeSyncResponse(device_send_time, server_recv_time, server_send_time);
            }
        }
Exemple #17
0
 /// <summary>
 /// Calls the WriteEvent method of the data sources.
 /// </summary>
 public void WriteEvent(DeviceEvent deviceEvent)
 {
     foreach (DataSourceLogic dataSourceLogic in dataSources)
     {
         try
         {
             if (dataSourceLogic.IsReady)
             {
                 dataSourceLogic.WriteEvent(deviceEvent);
             }
         }
         catch (Exception ex)
         {
             log.WriteException(ex, CommPhrases.ErrorInDataSource, nameof(WriteEvent), dataSourceLogic.Code);
         }
     }
 }
Exemple #18
0
        private async Task LoadDeviceEventThumbnail(DeviceEvent deviceEvent)
        {
            var imageFileName = deviceEvent.ImageName.Replace("_L", "_T").Replace("_X", "_T");

            if (!await _imageCache.ContainsAsync(imageFileName))
            {
                _logger.Verbose($"Cache does not contain [{imageFileName}] retrieving from device");

                using (var imageStream = await _transport.GetFileAsync(imageFileName))
                {
                    await _imageCache.CacheAsync(imageFileName, imageStream);
                }
            }

            deviceEvent.ImageThumbnailStream = await _imageCache.GetThumbnailStreamAsync(imageFileName);

            deviceEvent.VideoThumbnailStream = await _imageCache.GetThumbnailStreamAsync(imageFileName);
        }
        public async Task IgnoreOldEvent()
        {
            MockApplicationLifetime  appLifetime  = new MockApplicationLifetime();
            MockReliableStateManager stateManager = new MockReliableStateManager();

            IReliableDictionary <string, DeviceEvent> store =
                await stateManager.GetOrAddAsync <IReliableDictionary <string, DeviceEvent> >(DataService.EventDictionaryName);

            IReliableQueue <DeviceEventSeries> queue =
                await stateManager.GetOrAddAsync <IReliableQueue <DeviceEventSeries> >(DataService.EventQueueName);

            string           expectedDeviceId    = "some-device";
            DeviceEvent      expectedDeviceEvent = new DeviceEvent(new DateTimeOffset(100, TimeSpan.Zero));
            EventsController target = new EventsController(stateManager, statefulServiceContext, appLifetime);
            IActionResult    result = await target.Post(expectedDeviceId, new[] { expectedDeviceEvent });

            Assert.True(result is OkResult);

            using (ITransaction tx = stateManager.CreateTransaction())
            {
                ConditionalValue <DeviceEvent> actualStoredEvent = await store.TryGetValueAsync(tx, expectedDeviceId);

                Assert.True(actualStoredEvent.HasValue);
                Assert.Equal(expectedDeviceEvent.Timestamp, actualStoredEvent.Value.Timestamp);

                await tx.CommitAsync();
            }

            DeviceEvent oldEvent = new DeviceEvent(new DateTimeOffset(10, TimeSpan.Zero));

            result = await target.Post(expectedDeviceId, new[] { oldEvent });

            Assert.True(result is OkResult);

            using (ITransaction tx = stateManager.CreateTransaction())
            {
                ConditionalValue <DeviceEvent> actualStoredEvent = await store.TryGetValueAsync(tx, expectedDeviceId);

                Assert.True(actualStoredEvent.HasValue);
                Assert.Equal(expectedDeviceEvent.Timestamp, actualStoredEvent.Value.Timestamp);

                await tx.CommitAsync();
            }
        }
        public async Task AddMostRecentEvent()
        {
            MockApplicationLifetime  appLifetime  = new MockApplicationLifetime();
            MockReliableStateManager stateManager = new MockReliableStateManager();

            IReliableDictionary <string, DeviceEvent> store =
                await stateManager.GetOrAddAsync <IReliableDictionary <string, DeviceEvent> >(DataService.EventDictionaryName);

            IReliableQueue <DeviceEventSeries> queue =
                await stateManager.GetOrAddAsync <IReliableQueue <DeviceEventSeries> >(DataService.EventQueueName);

            string expectedDeviceId = "some-device";

            List <DeviceEvent> expectedDeviceList  = new List <DeviceEvent>();
            DeviceEvent        expectedDeviceEvent = new DeviceEvent(new DateTimeOffset(100, TimeSpan.Zero));

            for (int i = 0; i < 10; ++i)
            {
                expectedDeviceList.Add(new DeviceEvent(new DateTimeOffset(i, TimeSpan.Zero)));
            }
            expectedDeviceList.Insert(4, expectedDeviceEvent);

            EventsController target = new EventsController(stateManager, statefulServiceContext, appLifetime);

            IActionResult result = await target.Post(expectedDeviceId, expectedDeviceList);

            Assert.True(result is OkResult);

            using (ITransaction tx = stateManager.CreateTransaction())
            {
                ConditionalValue <DeviceEvent> actualStoredEvent = await store.TryGetValueAsync(tx, expectedDeviceId);

                ConditionalValue <DeviceEventSeries> actualQueuedEvent = await queue.TryDequeueAsync(tx);

                Assert.True(actualStoredEvent.HasValue);
                Assert.Equal(expectedDeviceEvent.Timestamp, actualStoredEvent.Value.Timestamp);

                Assert.True(actualQueuedEvent.HasValue);
                Assert.True(actualQueuedEvent.Value.Events.Select(x => x.Timestamp).SequenceEqual(expectedDeviceList.Select(x => x.Timestamp)));

                await tx.CommitAsync();
            }
        }
        public async Task <Device> UnregisterDeviceAsync(string id)
        {
            var status = DeviceStatus.Unregistered;
            var device = await this.GetDeviceAsync(id).ConfigureAwait(false);

            device.Status = status;

            var deviceEvent = new DeviceEvent()
            {
                DeviceId  = device.Id,
                Name      = device.FriendlyName,
                Status    = status,
                Timestamp = DateTimeOffset.UtcNow
            };

            this.deviceEventService.AddEvent(deviceEvent);

            return(device);
        }
        private void SetCallbacks()
        {
            _thermostat.ThermostatSetpointChanged += (sender, args) =>
            {
                var controlThinkSetpointType = args.ThermostatSetpointType;
                var controlThinkTemperature  = args.Temperature;
                var roomieSetpointType       = controlThinkSetpointType.ToRoomieType();
                var roomieTemperature        = controlThinkTemperature.ToRoomieType();

                if (roomieSetpointType.HasValue)
                {
                    Update(roomieSetpointType.Value, roomieTemperature);
                }

                IEventSource source = null;
                var          @event = DeviceEvent.ThermostatSetpointsChanged(_device, source);
                _device.AddEvent(@event);
            };
        }
        private DeviceEvent TemperatureChanged(int oldValue, int newValue, EventSender sender)
        {
            var result = new DeviceEvent
            {
                DeviceId = Id,
                Time = DateTime.Now,
                Sender = sender,
                Arguments = new [] { oldValue.ToString(), newValue.ToString() }
            };

            result.Type = (newValue > oldValue) ?
                DeviceEventType.TemperatureIncreased :
                DeviceEventType.TemperatureDecreased;

            result.Notification = (sender == EventSender.System) ?
                EventNotification.Warning :
                EventNotification.Information;

            return result;
        }
        public void Start_ConnectionEstablishedAndEventIsReceived_EventReceivedHandlerInvoked()
        {
            var patternEvent = new DeviceEvent("test");
            IDeviceEventReceiver        eventReceiverFake        = CreateDeviceEventReceiverFake(patternEvent);
            IDeviceEventReceiverFactory eventReceiverFactoryFake = CreateDeviceEventReceiverFactoryFake(eventReceiverFake);

            var         autoResetEvent = new AutoResetEvent(false);
            DeviceEvent currentEvent   = null;
            var         model          = new MainWindowModel(eventReceiverFactoryFake);

            model.EventReceived += (sender, @event) =>
            {
                currentEvent = @event;
                autoResetEvent.Set();
            };
            model.Start(CreateConnectionParametersFake());

            Assert.IsTrue(autoResetEvent.WaitOne(TestWaitTimeoutMs));
            Assert.AreSame(patternEvent, currentEvent);
        }
        private DeviceEvent MailPresentChanged(bool oldValue, bool newValue, EventSender sender)
        {
            var result = new DeviceEvent
            {
                DeviceId = Id,
                Time = DateTime.Now,
                Sender = sender,
                Arguments = null
            };

            result.Type = newValue ?
                DeviceEventType.NewMail :
                DeviceEventType.MailBoxEmpty;

            result.Notification = newValue ?
                EventNotification.Information :
                EventNotification.Hidden;

            return result;
        }
Exemple #26
0
        private void RemoveDeviceFromContextMenu(DeviceEvent @event)
        {
            var result = false;

            switch (@event.device.Type)
            {
            case AudioDeviceType.Playback:
                result = _availablePlaybackDevices.Remove(@event.device);
                break;

            case AudioDeviceType.Recording:
                result = _availableRecordingDevices.Remove(@event.device);
                break;
            }
            if (result)
            {
                _deviceListChanged = true;
                AppLogger.Log.Info("Removed device from list: ", @event.device);
            }
        }
Exemple #27
0
        public DeviceStatusDto GetDeviceStatus([FromBody] string deviceToken)
        {
            // TODO SECURITY ISSUE: Make sure the user for the device and the currently logged in user are the same.
            User user = this._context.Users.Include(u => u.DeviceTokens).FirstOrDefault(u => u.Id == Misc.GetIdFromClaimsPrincipal(User));

            if (user.Email == "*****@*****.**")
            {
                return(new DeviceStatusDto
                {
                    deviceToken = "7onpybsPelfV3Q==",
                    isOnline = true,
                    changeOfStatus = DateTime.Now
                });
            }

            DeviceToken device = user.DeviceTokens.FirstOrDefault((dv) => { return(dv.Token == deviceToken); });

            if (device != null)
            {
                bool        isOnline           = device.IsDeviceOnline ?? false;
                DeviceEvent lastChangeOfStatus = device.DeviceEvents.LastOrDefault();
                DateTime?   changeOfStatus;
                if (lastChangeOfStatus == null)
                {
                    changeOfStatus = null;
                }
                else
                {
                    changeOfStatus = lastChangeOfStatus.EventDate;
                }
                return(new DeviceStatusDto
                {
                    deviceToken = device.Token,
                    isOnline = isOnline,
                    changeOfStatus = changeOfStatus
                });
            }

            this._logger.LogError("DeviceStatus_NoDevice", "User: {0}, device Token: {1}", user.Id, device.Token);
            throw new Exception("No device with this deviceId found for user");
        }
Exemple #28
0
        public Task FireTriggersFromDevice(Device device, DeviceEvent deviceEvent)
        {
            // ignore events that are not known
            if (deviceEvent == DeviceEvent.Unknown)
            {
                return(Task.CompletedTask);
            }

            var triggers = memoryEntitiesService.StateTriggers.Where(st => st.Events.Contains(deviceEvent) && st.Devices.Contains(device.ID));

            if (triggers != null && triggers.Any())
            {
                logger.LogInformation($"Triggers.FireAll :: {string.Join(',', triggers.Select(x => x.ID))} :: Device:{device.ID}, Event:{deviceEvent}");
                return(ExecuteTriggerActions(triggers, device));
            }
            else
            {
                logger.LogInformation($"Triggers.FireAll :: None :: Device:{device.ID}, Event:{deviceEvent}");
                return(Task.CompletedTask);
            }
        }
Exemple #29
0
        private void DoWork()
        {
            var randomizer = new Random(DateTime.Now.Millisecond);

            while (_keepRunningWorkerThread)
            {
                var deviceEvent = new DeviceEvent()
                {
                    deviceId  = Guid.NewGuid().ToString(),
                    eventName = "randomName " + randomizer.Next(),
                    dateTime  = DateTime.UtcNow,
                    content   = "some random content " + randomizer.Next()
                };

                Publish(deviceEvent);

                LogingHelps.LogMessage(deviceEvent, _moduleName, LogingHelps.PublishedAction);

                Thread.Sleep(_configuration.threadInternalMiliseconds);
            }
        }
Exemple #30
0
        void PIEDataHandler.HandlePIEHidData(byte[] data, PIEDevice sourceDevice)
        {
            if (sourceDevice != _device.BackingObject)
            {
                return;
            }


            while (0 == sourceDevice.ReadData(ref data))
            {
                var state   = BinaryConversions.ConvertKeypad(data);
                var changes = state.Buttons.Changes(_history.Last.Value.Buttons);
                _history.AddLast(state);

                Buttons = state.Buttons;

                var @event = DeviceEvent.KeypadStateChanged(_device, null);

                _device.AddEvent(@event);
            }
        }
        public Task <Device> RegisterDeviceAsync(Device device)
        {
            if (device != null)
            {
                var status = DeviceStatus.Registered;
                device.Id = count.ToString();
                count++;
                device.Status = status;
                DeviceService.DataStore.Add(device.Id, device);

                var deviceEvent = new DeviceEvent()
                {
                    DeviceId  = device.Id,
                    Name      = device.FriendlyName,
                    Status    = status,
                    Timestamp = DateTimeOffset.UtcNow
                };
                this.deviceEventService.AddEvent(deviceEvent);
            }

            return(Task.FromResult(device));
        }
Exemple #32
0
        /// <summary>
        /// Get flags for key event.
        /// </summary>
        /// <param name="deviceEvent">Device event.</param>
        /// <param name="key">Key.</param>
        /// <returns>Flags.</returns>
        public static uint GetFlags(this DeviceEvent deviceEvent, Keys key)
        {
            switch (deviceEvent)
            {
            case DeviceEvent.KeyDown:
                switch (key)
                {
                case Keys.LButton: return(Event.MouseLButtonDown);

                case Keys.MButton: return(Event.MouseMButtonDown);

                case Keys.RButton: return(Event.MouseRButtonDown);

                case Keys.XButton1: return(Event.MouseXButtonDown);

                case Keys.XButton2: return(Event.MouseXButtonDown);

                default: return(key.IsExtendedKey() ? Event.KeyboardKeyDownExtended : Event.KeyboardKeyDown);
                }

            case DeviceEvent.KeyUp:
                switch (key)
                {
                case Keys.LButton: return(Event.MouseLButtonUp);

                case Keys.MButton: return(Event.MouseMButtonUp);

                case Keys.RButton: return(Event.MouseRButtonUp);

                case Keys.XButton1: return(Event.MouseXButtonUp);

                case Keys.XButton2: return(Event.MouseXButtonUp);

                default: return(key.IsExtendedKey() ? Event.KeyboardKeyUpExtended : Event.KeyboardKeyUp);
                }
            }

            throw new ArgumentException($"No flags for {deviceEvent}");
        }
Exemple #33
0
            /// <summary>
            /// Define a keyboard input.
            /// </summary>
            /// <param name="key">Key.</param>
            /// <param name="deviceEvent">Device event.</param>
            public Input(Keys key, DeviceEvent deviceEvent)
            {
                ushort virtualKey = (ushort)key;
                uint   flags      = deviceEvent.GetFlags(key);

                Hardware = new Hardware();

                if (key.IsMouseKey())
                {
                    // Mouse
                    Type     = (uint)Device.Mouse;
                    Keyboard = new Keyboard();
                    Mouse    = new Mouse(x: 0, y: 0, data: key.GetMouseData(), flags: flags);
                }
                else
                {
                    // Keyboard
                    Type     = (uint)Device.Keyboard;
                    Mouse    = new Mouse();
                    Keyboard = new Keyboard(virtualKey, (ushort)WinAPI.MapVirtualKeyEx(virtualKey, 0, keyboardLayout), flags);
                }
            }
Exemple #34
0
        private void OnDeviceInterfaceChanged(DeviceEvent eventType, Message message, DEV_BROADCAST_HDR broadcastHeader)
        {
            int stringSize = Convert.ToInt32((broadcastHeader.dbch_size - 32) / 2);

            var deviceInterface = new DEV_BROADCAST_DEVICEINTERFACE();
            Array.Resize(ref deviceInterface.dbcc_name, stringSize);
            Marshal.PtrToStructure(message.LParam, deviceInterface);
            var classId = new Guid(deviceInterface.dbcc_classguid);
            var deviceName = new string(deviceInterface.dbcc_name, 0, stringSize);
            Debug.Print("Hardware.OnDeviceInterfaceChanged(): {0} {2} {1}", eventType, deviceName, classId);

            var eh = DeviceInterfaceChanged;
            if (eh != null) {
                eh(this, new DeviceInterfaceChangedArgs(eventType, classId, deviceName));
            }
        }
Exemple #35
0
        private void OnVolumeChanged(DeviceEvent eventType, Message message)
        {
            var volume = new DEV_BROADCAST_VOLUME();
            Marshal.PtrToStructure(message.LParam, volume);
            var flags = (VolumeFlags)volume.dbcc_flags;

            char driveLetter = 'A';
            int bitMask = 1;
            while (driveLetter <= 'Z') {
                if ((volume.dbcc_unitmask & bitMask) != 0) {
                    OnVolumeChanged(eventType, driveLetter, flags);
                }
                bitMask = bitMask << 1;
                driveLetter++;
            }
        }
Exemple #36
0
 private void OnVolumeChanged(DeviceEvent eventType, char driveLetter, VolumeFlags flags)
 {
     Debug.Print("Hardware.OnVolumeChanged(): {0} {1}: {2}", eventType, driveLetter, flags);
     var eh = VolumeChanged;
     if (eh != null) {
         var changeType = (eventType == DeviceEvent.DeviceArrival) ?
             VolumeChangedArgs.ChangeType.Added : VolumeChangedArgs.ChangeType.Removed;
         var args = new VolumeChangedArgs(driveLetter, changeType);
         eh(this, args);
     }
 }
Exemple #37
0
 private void RemoveDeviceFromContextMenu(DeviceEvent @event)
 {
     var result = false;
     switch (@event.device.Type)
     {
         case AudioDeviceType.Playback:
             result = _availablePlaybackDevices.Remove(@event.device);
             break;
         case AudioDeviceType.Recording:
             result = _availableRecordingDevices.Remove(@event.device);
             break;
     }
     if (result)
     {
         _deviceListChanged = true;
         AppLogger.Log.Info("Removed device from list: ", @event.device);
     }
 }
Exemple #38
0
 private void AddDeviceToContextMenu(DeviceEvent @event)
 {
     var result = false;
     switch (@event.device.Type)
     {
         case AudioDeviceType.Playback:
             if (AppModel.Instance.SelectedPlaybackDevicesList.Contains(@event.device.FriendlyName))
             {
                 _availablePlaybackDevices.Add(@event.device);
                 result = true;
             }
             break;
         case AudioDeviceType.Recording:
             if (AppModel.Instance.SelectedRecordingDevicesList.Contains(@event.device.FriendlyName))
             {
                 _availableRecordingDevices.Add(@event.device);
                 result = true;
             }
             break;
     }
     if (result)
     {
         _deviceListChanged = true;
         AppLogger.Log.Info("Added device in list: ", @event.device);
     }
 }