Пример #1
0
        private void ButtonStartDiscover_Click(object sender, RoutedEventArgs e)
        {
            if (ListDevices.Items != null)
            {
                ListDevices.Items.Clear();
            }
            CheckListDevices();
            string selector = CustomDevice.GetDeviceSelector(new Guid("53f56308-b6bf-11d0-94f2-00a0c91efb8b"));
            IEnumerable <string> additionalProperties = new string[] { "System.Devices.DeviceInstanceId" };

            if (cdReaderManager != null)
            {
                cdReaderManager.StopDiscovery();
                cdReaderManager.CDReaderDeviceAdded   -= CDReaderDevice_Added;
                cdReaderManager.CDReaderDeviceRemoved -= CDReaderDevice_Removed;
                cdReaderManager = null;
            }
            cdReaderManager = new CDReaderManager();
            cdReaderManager.CDReaderDeviceAdded   += CDReaderDevice_Added;
            cdReaderManager.CDReaderDeviceRemoved += CDReaderDevice_Removed;
            cdReaderManager.StartDiscovery();
            ButtonStartDiscover.Visibility = Visibility.Collapsed;
            ButtonStopDiscover.Visibility  = Visibility.Visible;
            ListDevices.IsEnabled          = true;
        }
        private async void deviceEventsGet_Click_1(object sender, RoutedEventArgs e)
        {
            CustomDevice fx2Device = DeviceList.Current.GetSelectedDevice();

            bool[] switchStateArray = new bool[8];

            if (fx2Device == null)
            {
                rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
                return;
            }

            try
            {
                var output = new byte[1];

                await fx2Device.SendIOControlAsync(Fx2Driver.ReadSwitches,
                                                   null,
                                                   output.AsBuffer());

                switchStateArray = CreateSwitchStateArray(output);
            }
            catch (Exception exception)
            {
                rootPage.NotifyUser(exception.ToString(), NotifyType.ErrorMessage);
                return;
            }

            UpdateSwitchStateTable(switchStateArray);
        }
 // When one of our custom devices is removed, we want to make sure that if
 // it is the '.current' device, we null out '.current'.
 protected override void OnRemoved()
 {
     base.OnRemoved();
     if (current == this)
     {
         current = null;
     }
 }
Пример #4
0
        private async void ShadowDriverDeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            System.Diagnostics.Debug.WriteLine(args.Id);
            sender.Stop();
            _shadowDevice = await CustomDevice.FromIdAsync(args.Id, DeviceAccessMode.ReadWrite, DeviceSharingMode.Shared);

            IsFilterReady = true;
            FilterReady?.Invoke();
        }
 public void SetSelectedDevice(string Id, CustomDevice Device)
 {
     if ((m_Fx2Device != null) && (this.DeviceClosing != null)) 
     {
         this.DeviceClosing(this, new EventArgs());
     }
     m_Fx2Device = Device;
     m_Fx2DeviceId = Id;
 }
Пример #6
0
 public void SetSelectedDevice(string Id, CustomDevice Device)
 {
     if ((m_Fx2Device != null) && (this.DeviceClosing != null))
     {
         this.DeviceClosing(this, new EventArgs());
     }
     m_Fx2Device   = Device;
     m_Fx2DeviceId = Id;
 }
        /// <summary>
        /// Update an existing Custom Device.
        /// </summary>
        /// <param name="accessToken">The OAuth2 access token</param>
        /// <param name="customDevice">Custom Device object with all the data</param>
        /// <returns></returns>
        public static async Task <bool> UpdateCustomDeviceAsync(string accessToken, CustomDevice customDevice)
        {
            if (customDevice.Id == null && customDevice.Id.CompareTo(new Guid()) == 0)
            {
                throw new ArgumentException("The Id cannot be empty to update an existing Custom Device");
            }

            using (var restApi = new SmartMeApiClient(accessToken))
            {
                return(await restApi.PostAsync <CustomDevice>("CustomDevice", customDevice));
            }
        }
Пример #8
0
        private async void ShadowDriverDeviceWatcher_Added(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation args)
        {
            ShadowDriverDevice = await CustomDevice.FromIdAsync(args.Id, DeviceAccessMode.ReadWrite, DeviceSharingMode.Exclusive);

            if (ShadowDriverDevice != null)
            {
                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    ViewModel.DeviceConnectStatus = "Connected";
                });
            }
        }
Пример #9
0
        public void StartFilterWatcher()
        {
            var selector = CustomDevice.GetDeviceSelector(DriverRelatedInformation.InterfaceGuid);
            var shadowDriverDeviceWatcher = DeviceInformation.CreateWatcher(
                selector,
                new string[] { "System.Devices.DeviceInstanceId" }
                );

            shadowDriverDeviceWatcher.Added   += ShadowDriverDeviceWatcher_Added;
            shadowDriverDeviceWatcher.Removed += ShadowDriverDeviceWatcher_Removed;;
            shadowDriverDeviceWatcher.Start();
        }
Пример #10
0
        void InitDeviceWatcher()
        {
            // Define the selector to enumerate all of the fx2 device interface class instances
            var selector = CustomDevice.GetDeviceSelector(Fx2Driver.DeviceInterfaceGuid);

            // Create a device watcher to look for instances of the fx2 device interface
            m_Fx2Watcher = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(
                selector,
                new string[] { "System.Devices.DeviceInstanceId" }
                );

            m_Fx2Watcher.Added   += OnFx2Added;
            m_Fx2Watcher.Removed += OnFx2Removed;
            m_Fx2Watcher.EnumerationCompleted += OnFx2EnumerationComplete;
        }
        /// <summary>
        /// Creates a new Custom Device.
        /// A Custom Device can be any device that like to add some measurement values to the smart-me Cloud.
        /// Only use a custom device for all non meters.
        /// </summary>
        /// <param name="accessToken">The OAuth2 access token</param>
        /// <param name="customDevice">Custom Device object with all the data</param>
        /// <param name="resultHandler">The result handler</param>
        /// <returns>The added CustomDevice</returns>
        public static async Task <IActionResult> AddCustomDeviceAsync(
            string accessToken,
            CustomDevice customDevice,
            ResultHandler <CustomDevice> resultHandler)
        {
            if (customDevice.Id != null && customDevice.Id.CompareTo(new Guid()) != 0)
            {
                throw new ArgumentException("The Id must be empty to create a new Custom Device");
            }

            using (var restApi = new SmartMeApiClient(accessToken))
            {
                return(await restApi.PostAddAsync <CustomDevice>("CustomDevice", customDevice, resultHandler));
            }
        }
 public AddCustomDeviceModel()
 {
     CustomDevice = new CustomDevice
     {
         Values = new List <CustomDeviceValue>
         {
             new CustomDeviceValue {
                 Name = "", Value = 0
             },
             new CustomDeviceValue {
                 Name = "", Value = 0
             }
         }
     };
 }
        private async Task OpenFx2DeviceAsync(string Id)
        {
            System.Diagnostics.Debug.Assert(DeviceList.Current.GetSelectedDevice() == null);

            try
            {
                var device = await CustomDevice.FromIdAsync(Id, DeviceAccessMode.ReadWrite, DeviceSharingMode.Exclusive);

                DeviceList.Current.SetSelectedDevice(Id, device);
            }
            catch (Exception e)
            {
                rootPage.NotifyUser($"Error opening Fx2 device @{Id}: {e.Message}", NotifyType.ErrorMessage);
                return;
            }
            rootPage.NotifyUser($"Fx2 {Id} opened", NotifyType.StatusMessage);
            return;
        }
        public async Task <IActionResult> OnPostAsync(CustomDevice customDevice)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var tokenData = await SmartMeOAuthConfiguration.GetAccessToken(HttpContext);

            return(await DevicesApi.AddCustomDeviceAsync(tokenData.AccessToken, customDevice, new ResultHandler <CustomDevice>
            {
                OnSuccess = (newCustomDevice) =>
                {
                    return Redirect("/Devices/AddCustomDeviceResult?id=" + newCustomDevice.Id);
                },

                OnError = DefaultErrorHandler.Handle
            }));
        }
Пример #15
0
        public async Task <IActionResult> OnPostAsync(CustomDevice customDevice)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            return(await DevicesApi.AddCustomDeviceAsync(accessToken, customDevice, new ResultHandler <CustomDevice>
            {
                OnSuccess = (newCustomDevice) =>
                {
                    return Redirect("/Devices/AddCustomDeviceResult?id=" + newCustomDevice.Id);
                },

                OnError = DefaultErrorHandler.Handle
            }));
        }
Пример #16
0
 private async System.Threading.Tasks.Task <bool> SetCDDeviceAsync()
 {
     try
     {
         if (CDReaderDevice == null)
         {
             CDReaderDevice = await CustomDevice.FromIdAsync(DeviceID, DeviceAccessMode.Read, DeviceSharingMode.Exclusive);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Exception while getting CDREaderDevice: " + ex.Message);
     }
     if (CDReaderDevice != null)
     {
         return(true);
     }
     return(false);
 }
        public async Task <IActionResult> OnGetAsync(Guid id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var accessToken = await HttpContext.GetTokenAsync("access_token");

            return(await DevicesApi.GetCustomDeviceAsync(accessToken, id, new ResultHandler <CustomDevice>
            {
                OnSuccess = (customDevice) =>
                {
                    CustomDevice = customDevice;
                    return Page();
                },

                OnError = DefaultErrorHandler.Handle
            }));
        }
        public async Task <IActionResult> OnPostAsync(CustomDevice customDevice)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var tokenData = await SmartMeOAuthConfiguration.GetAccessToken(HttpContext);

            return(await DevicesApi.UpdateCustomDeviceAsync(tokenData.AccessToken, customDevice, new ResultHandler <CustomDevice>
            {
                OnSuccess = (empty) =>
                {
                    // Trigger another GET to show the updated custom device
                    return Redirect("/Devices/UpdateCustomDevice");
                },

                OnError = DefaultErrorHandler.Handle
            }));
        }
        public async Task <IActionResult> OnGetAsync()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var tokenData = await SmartMeOAuthConfiguration.GetAccessToken(HttpContext);

            return(await DevicesApi.GetCustomDeviceAsync(tokenData.AccessToken, Id, new ResultHandler <CustomDevice>
            {
                OnSuccess = (customDevice) =>
                {
                    CustomDevice = customDevice;
                    return Page();
                },

                OnError = DefaultErrorHandler.Handle
            }));
        }
Пример #20
0
        public bool StartDiscovery()
        {
            bool   result   = false;
            string selector = CustomDevice.GetDeviceSelector(new Guid("53f56308-b6bf-11d0-94f2-00a0c91efb8b"));
            IEnumerable <string> additionalProperties = new string[] { "System.Devices.DeviceInstanceId" };

            if (deviceWatcher != null)
            {
                StopDiscovery();
            }
            ListDeviceInformation.Clear();
            deviceWatcher = DeviceInformation.CreateWatcher(selector, additionalProperties);
            if (deviceWatcher != null)
            {
                deviceWatcher.Added   += deviceWatcher_Added;
                deviceWatcher.Removed += deviceWatcher_Removed;
                deviceWatcher.EnumerationCompleted += deviceWatcher_EnumerationCompleted;
                deviceWatcher.Start();
            }
            return(result);
        }
Пример #21
0
        private async void deviceEventsGet_Click(object sender, RoutedEventArgs e)
        {
            CustomDevice fx2Device = DeviceList.Current.GetSelectedDevice();

            bool[] switchStateArray = new bool[8];

            if (fx2Device == null)
            {
                rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
                return;
            }

            var button = (Button)sender;

            button.IsEnabled = false;

            var output = new byte[1];

            try
            {
                uint bytesRead = await fx2Device.SendIOControlAsync(Fx2Driver.ReadSwitches, null, output.AsBuffer());

                if (bytesRead == 0)
                {
                    rootPage.NotifyUser("Fx2 device returned 0 byte interrupt message.  Stopping", NotifyType.ErrorMessage);
                }
                else
                {
                    switchStateArray = CreateSwitchStateArray(output);
                    UpdateSwitchStateTable(switchStateArray);
                }
            }
            catch (Exception exception)
            {
                rootPage.NotifyUser(exception.ToString(), NotifyType.ErrorMessage);
            }
            button.IsEnabled = true;
        }
Пример #22
0
 private void ShadowDriverDeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
 {
     _shadowDevice = null;
 }
Пример #23
0
        private void ConnectDevices()
        {
            if (_connectionInProgress)
            {
                return;
            }
            _connectionInProgress = true;
            if (PortableDeviceCollection.Instance == null)
            {
                PortableDeviceCollection.CreateInstance(AppName, AppMajorVersionNumber, AppMinorVersionNumber);
                PortableDeviceCollection.Instance.AutoConnectToPortableDevice = false;
            }
            _deviceEnumerator.RemoveDisconnected();

            Log.Debug("Connection device start");
            try
            {
                var devices = PortableDeviceCollection.Instance.Devices;
                foreach (PortableDevice portableDevice in devices)
                {
                    Log.Debug("Connection device " + portableDevice.DeviceId);
                    //TODO: avoid to load some mass storage in my computer need to find a general solution
                    if (!portableDevice.DeviceId.StartsWith("\\\\?\\usb") &&
                        !portableDevice.DeviceId.StartsWith("\\\\?\\comp"))
                    {
                        continue;
                    }
                    // ignore some Canon cameras
                    if (!SupportedCanonCamera(portableDevice.DeviceId))
                    {
                        continue;
                    }
                    portableDevice.ConnectToDevice(AppName, AppMajorVersionNumber, AppMinorVersionNumber);

                    if (_deviceEnumerator.GetByWpdId(portableDevice.DeviceId) == null &&
                        GetNativeDriver(portableDevice.Model) != null)
                    {
                        ICameraDevice    cameraDevice;
                        DeviceDescriptor descriptor = new DeviceDescriptor {
                            WpdId = portableDevice.DeviceId
                        };
                        cameraDevice = (ICameraDevice)Activator.CreateInstance(GetNativeDriver(portableDevice.Model));
                        MtpProtocol device = new MtpProtocol(descriptor.WpdId);
                        device.ConnectToDevice(AppName, AppMajorVersionNumber, AppMinorVersionNumber);

                        descriptor.StillImageDevice = device;

                        cameraDevice.SerialNumber = StaticHelper.GetSerial(portableDevice.DeviceId);
                        cameraDevice.Init(descriptor);

                        if (string.IsNullOrWhiteSpace(cameraDevice.SerialNumber))
                        {
                            cameraDevice.SerialNumber = StaticHelper.GetSerial(portableDevice.DeviceId);
                        }

                        ConnectedDevices.Add(cameraDevice);
                        NewCameraConnected(cameraDevice);

                        descriptor.CameraDevice = cameraDevice;
                        _deviceEnumerator.Add(descriptor);
                    }

                    if (_deviceEnumerator.GetByWpdId(portableDevice.DeviceId) == null &&
                        GetNativeDriver(portableDevice.Model) == null)
                    {
                        var description = getDeviceDescription(portableDevice.Model);
                        if (description != null)
                        {
                            CustomDevice     cameraDevice = new CustomDevice();
                            DeviceDescriptor descriptor   = new DeviceDescriptor {
                                WpdId = portableDevice.DeviceId
                            };
                            MtpProtocol device = new MtpProtocol(descriptor.WpdId);
                            device.ConnectToDevice(AppName, AppMajorVersionNumber, AppMinorVersionNumber);

                            descriptor.StillImageDevice = device;

                            cameraDevice.SerialNumber = StaticHelper.GetSerial(portableDevice.DeviceId);
                            cameraDevice.Init(descriptor, description);

                            ConnectedDevices.Add(cameraDevice);
                            NewCameraConnected(cameraDevice);

                            descriptor.CameraDevice = cameraDevice;
                            _deviceEnumerator.Add(descriptor);
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("Unable to connect to cameras ", exception);
            }

            _connectionInProgress = false;
        }
Пример #24
0
 private void ShadowDriverDeviceWatcher_Removed(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformationUpdate args)
 {
     ShadowDriverDevice            = null;
     ViewModel.DeviceConnectStatus = "Disconnected";
 }
Пример #25
0
        public static async Task CustomDevicesAsync(UserPassword credentials)
        {
            // Add Custom Device
            {
                Helpers.WriteConsoleTitle("Add a custom device");

                await DevicesApi.AddCustomDeviceAsync(credentials, new CustomDevice
                {
                    Id        = new Guid(),
                    Name      = "CustomDeviceTest",
                    Serial    = 0,
                    ValueDate = DateTime.UtcNow,
                    Values    = new List <CustomDeviceValue>
                    {
                        new CustomDeviceValue {
                            Name = "SomeVoltageValue", Value = 5.6
                        },
                        new CustomDeviceValue {
                            Name = "SomeTemperatureValue", Value = 12.1
                        }
                    }
                });
            }

            CustomDevice sampleDevice;

            // Get Custom Devices
            {
                Helpers.WriteConsoleTitle("Get custom devices");

                List <CustomDevice> customDevices = await DevicesApi.GetCustomDevicesAsync(credentials);

                foreach (CustomDevice customDevice in customDevices)
                {
                    if (customDevice != null)
                    {
                        Console.WriteLine($"Id: {customDevice.Id}, Name: {customDevice.Name}");
                    }
                }

                sampleDevice = customDevices.First();
            }

            // Update Custom Device
            {
                Helpers.WriteConsoleTitle("Update a custom device");

                List <CustomDevice> customDevices = await DevicesApi.GetCustomDevicesAsync(credentials);

                foreach (CustomDevice customDevice in customDevices)
                {
                    if (customDevice != null)
                    {
                        customDevice.Name = "UpdatedCustomDeviceTest";
                        await DevicesApi.UpdateCustomDeviceAsync(credentials, customDevice);

                        break;
                    }
                }
            }

            // Get Custom Device by Id
            {
                Helpers.WriteConsoleTitle("Get custom device by id");

                CustomDevice customDevice = await DevicesApi.GetCustomDeviceAsync(credentials, sampleDevice.Id);

                Console.WriteLine($"Id: {customDevice.Id}, Name: {customDevice.Name}");
            }
        }
 public override void MakeCurrent()
 {
     base.MakeCurrent();
     current = this;
 }
        /// <summary>
        /// Creates a new Custom Device.
        /// A Custom Device can be any device that like to add some measurement values to the smart-me Cloud.
        /// Only use a custom device for all non meters.
        /// </summary>
        /// <param name="usernamePassword">The Username and Password for Basic Authentication</param>
        /// <param name="customDevice">Custom Device object with all the data</param>
        /// <returns>The added CustomDevice</returns>
        public static async Task <CustomDevice> AddCustomDeviceAsync(UserPassword usernamePassword, CustomDevice customDevice)
        {
            if (customDevice.Id != null && customDevice.Id.CompareTo(new Guid()) != 0)
            {
                throw new ArgumentException("The Id must be empty to create a new Custom Device");
            }

            using (var restApi = new SmartMeApiClient(usernamePassword))
            {
                return(await restApi.PostAddAsync <CustomDevice>("CustomDevice", customDevice));
            }
        }