Ejemplo n.º 1
0
        public async void Initialize(byte address = 0x40, I2cBusSpeed speed = I2cBusSpeed.StandardMode)
        {
            //MainPage rootPage = MainPage.Current;

            DeviceInformationCollection devices = null;

            Address = address;
            Speed   = speed;

            //await rootPage.uart.SendText("I2C Device at Address " + address.ToString() + " Initializing\n\r");

            var settings = new I2cConnectionSettings(Address)
            {
                BusSpeed = Speed
            };

            settings.SharingMode = I2cSharingMode.Shared;

            // Get a selector string that will return all I2C controllers on the system
            string aqs = I2cDevice.GetDeviceSelector();

            // Find the I2C bus controller device with our selector string
            devices = await DeviceInformation.FindAllAsync(aqs);

            //search for the controller
            if (!devices.Any())
            {
                throw new IOException("No I2C controllers were found on the system");
            }

            //see if we can find the hat
            device = await I2cDevice.FromIdAsync(devices[0].Id, settings);

            //await rootPage.uart.SendText("I2C Device at Address " + address.ToString() + " Initialized\n\r");
        }
        private async void UpdateDevices()
        {
            // Get a list of all Audio Input or Output devices
            m_deviceInformationCollection = await DeviceInformation.FindAllAsync(m_deviceSelectorString);

            //deviceListBox.Items.Clear();
            this.DeviceInformationList.Clear();

            if (!m_deviceInformationCollection.Any())
            {
                //deviceListBox.Items.Add("No audio devices found!");
            }

            if (AudioDeviceType.Input == m_deviceType)
            {
                //deviceListBox.Items.Add("Select an audio input device:");
            }
            else
            {
                //deviceListBox.Items.Add("Select an audio output device:");
            }

            foreach (var deviceInformation in m_deviceInformationCollection)
            {
                //deviceListBox.Items.Add(deviceInformation.Name);
                this.DeviceInformationList.Add(deviceInformation);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 异步加载串口列表
        /// </summary>
        public async void SerialList()
        {
            string selectors = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection decices = await DeviceInformation.FindAllAsync(selectors);

            if (decices.Any())
            {
                for (int i = 0; i < decices.Count(); i++)
                {
                    if (AllPortName.Contains(decices[i].Name))
                    {
                        continue;
                    }
                    else
                    {
                        AllPortName.Add(decices[i].Name);
                    }
                }
                //PortName = PortName.Distinct().ToList();
            }
            else
            {
                AllPortName.Clear();
            }
        }
        private static async Task <MediaCapture[]> InitializeCameraAsync()
        {
            List <MediaCapture>         mediaCaptureDevices = new List <MediaCapture>();
            DeviceInformationCollection videoDevices        = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (!videoDevices.Any())
            {
                Debug.WriteLine("No cameras found.");
                return(mediaCaptureDevices.ToArray());
            }
            foreach (DeviceInformation device in videoDevices)
            {
                MediaCapture mediaCapture = new MediaCapture();

                MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = device.Id
                };

                await mediaCapture.InitializeAsync(mediaInitSettings);
                await SetMaxResolution(mediaCapture);


                mediaCaptureDevices.Add(mediaCapture);
            }

            return(mediaCaptureDevices.ToArray());
        }
Ejemplo n.º 5
0
        public async Task InitializeCameraAsync()
        {
            try
            {
                if (_mediaCapture == null)
                {
                    _mediaCapture         = new MediaCapture();
                    _mediaCapture.Failed += MediaCapture_Failed;

                    _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (_cameraDevices == null || !_cameraDevices.Any())
                    {
                        throw new NotSupportedException();
                    }

                    var device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);

                    var cameraId = device?.Id ?? _cameraDevices.First().Id;

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (Panel == Panel.Back)
                    {
                        _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = true;
                    }

                    IsInitialized = true;
                    CanSwitch     = _cameraDevices?.Count > 1;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
            catch (UnauthorizedAccessException)
            {
                errorMessage.Text = "Camera_Exception_UnauthorizedAccess".GetLocalized();
            }
            catch (NotSupportedException)
            {
                errorMessage.Text = "Camera_Exception_NotSupported".GetLocalized();
            }
            catch (TaskCanceledException)
            {
                errorMessage.Text = "Camera_Exception_InitializationCanceled".GetLocalized();
            }
            catch (Exception)
            {
                errorMessage.Text = "Camera_Exception_InitializationError".GetLocalized();
            }
        }
Ejemplo n.º 6
0
        private async void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            /* Create an I2cDevice with our selected bus controller and I2C settings */
            var settings = new I2cConnectionSettings(_baseAddress)
            {
                BusSpeed = I2cBusSpeed.FastMode
            };
            DeviceInformationCollection devices = null;

            _initialized = await Task.Run(async() =>
            {
                // Get a selector string that will return all I2C controllers on the system
                string aqs = I2cDevice.GetDeviceSelector();

                // Find the I2C bus controller device with our selector string
                devices = await DeviceInformation.FindAllAsync(aqs);

                //search for the controller
                if (!devices.Any())
                {
                    throw new IOException("No I2C controllers were found on the system");
                }

                //see if we can find the hat
                _servoPiHat = await I2cDevice.FromIdAsync(devices[0].Id, settings);
                return(true);
            });

            if (_servoPiHat == null)
            {
                string message;
                if (devices != null && devices.Count > 0)
                {
                    message = string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by another application. Please ensure that no other applications are using I2C.",
                        settings.SlaveAddress,
                        devices[0].Id);
                }
                else
                {
                    message = "Could not initialize the device!";
                }

                throw new IOException(message);
            }

            _initialized = true;
            Reset();
            this.SetDesiredFrequency(50);
        }
Ejemplo n.º 7
0
        ///<summary>
        ///Open port to make a connect
        ///打开串口开始连接
        ///</summary>
        ///<param name="portName">Name of COM port to open</param>
        ///<param name="pAddress">StaatusFrame类的实例的地址</param>
        ///<param name="baudRate">baud rate of COM port 传输速率</param>
        ///<param name="parity">type of data parity</param>
        ///<param name="dataBits">Number of data bits</param>
        ///<param name="stopbits">Number of stop</param>
        public async Task <bool> Open(string portName, StatusFrame pAddress, uint baudRate = 9600, SerialParity parity = SerialParity.None, ushort dataBits = 8, SerialStopBitCount stopBits = SerialStopBitCount.One)
        {
            //close open port 关闭当前正在打开的串口
            //防止错误覆盖
            Close();

            //get a list of devices from the given portname
            string selector = SerialDevice.GetDeviceSelector(portName);

            // Get a list of devices that match the given name
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            // If any device found...
            if (devices.Any())
            {
                // Get first device (should be only device)
                DeviceInformation deviceInfo = devices.First();

                // Create a serial port device from the COM port device ID
                this.SerialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                // If serial device is valid...
                if (this.SerialDevice != null)
                {
                    // Setup serial port configuration
                    this.SerialDevice.StopBits = stopBits;
                    this.SerialDevice.Parity   = parity;
                    this.SerialDevice.BaudRate = baudRate;
                    this.SerialDevice.DataBits = dataBits;

                    // Create a single device writer for this port connection
                    this.dataWriterObject = new DataWriter(this.SerialDevice.OutputStream);

                    // Create a single device reader for this port connection
                    this.dataReaderObject = new DataReader(this.SerialDevice.InputStream);

                    // Allow partial reads of the input stream
                    this.dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;


                    pAddress.PortName = portName;

                    // Port is now open
                    this.IsOpen = true;
                }
            }

            return(this.IsOpen);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 串口异步设置
        /// </summary>
        /// <param name="PortName"></param>
        private async void SerialSet(string PortName)
        {
            string selectors = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection decices = await DeviceInformation.FindAllAsync(selectors);

            if (decices.Any())
            {
                for (int i = 0; i < decices.Count(); i++)
                {
                    if (decices[i].Name.Equals(PortName))
                    {
                        Device = await SerialDevice.FromIdAsync(decices[i].Id);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            string qFilter = SerialDevice.GetDeviceSelector("COM3");
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);

            if (devices.Any())
            {
                string deviceId = devices.First().Id;
                await OpenPort(deviceId);
            }

            ReadCancellationTokenSource = new CancellationTokenSource();
            while (true)
            {
                await Listen();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Funcion que se encarga de abrir el puerto
        /// </summary>
        /// <returns></returns>
        public async Task <bool> OpenPort()
        {
            // Close open port
            ClosePort();

            // Get a device selector from the given port name
            string selector = SerialDevice.GetDeviceSelector(_portName);

            // Get a list of devices that match the given name
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            // If any device found...
            if (devices.Any())
            {
                // Get first device (should be only device)
                DeviceInformation deviceInfo = devices.First();

                // Create a serial port device from the COM port device ID
                this.serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                // If serial device is valid...
                if (this.serialDevice != null)
                {
                    // Setup serial port configuration
                    this.serialDevice.StopBits = _stopBits;
                    this.serialDevice.Parity   = _parity;
                    this.serialDevice.BaudRate = _baudRate;
                    this.serialDevice.DataBits = _dataBits;

                    // Create a single device writer for this port connection
                    this.dataWriterObject = new DataWriter(this.serialDevice.OutputStream);

                    // Create a single device reader for this port connection
                    this.dataReaderObject = new DataReader(this.serialDevice.InputStream);

                    // Allow partial reads of the input stream
                    this.dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

                    // Port is now open
                    this.IsOpen = true;
                }
            }

            return(this.IsOpen);
        }
Ejemplo n.º 11
0
        async void ListDevices()
        {
            String ids = "";

            availableSelection.Items.Clear();
            String aqsFilter = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(aqsFilter);

            //Log(devices.Count);
            if (devices.Any())
            {
                DeviceInformation[] infos = devices.ToArray();
                foreach (DeviceInformation info in infos)
                {
                    //Log(info.Name);
                    //Log(info.Id);
                    try
                    {
                        SerialDevice sd = await SerialDevice.FromIdAsync(info.Id);

                        var x = sd.PortName;//wenn es der Port nicht geöffnet werden kann wird hier eine exception auftreten => Exception basierter filter für die Auswahl in der Combobox
                        var y = sd.BaudRate;
                        //Log(sd.PortName);
                        //Log(sd.BaudRate.ToString());
                        ids += info.Id + "|";
                        availableSelection.Items.Add(new TextBox()
                        {
                            IsReadOnly = true, IsHitTestVisible = false, Text = info.Name + " (" + sd.PortName + ")"
                        });
                        sd.Dispose();
                    }
                    catch (Exception)
                    {
                        if (shouldBeReading)
                        {
                        }                       //nur um die warning zu unterdrücken
                        //ex.PrintStackTrace();
                        //Log("EXC");
                    }
                    //&Log("");
                }
                devIds = ids.Split("|");
                availableSelection.SelectedIndex = 0;
            }
        }
Ejemplo n.º 12
0
        public async void SerialConnection()
        {
            string qFilter = SerialDevice.GetDeviceSelector("COM3");
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);

            if (devices.Any())
            {
                string deviceId = devices.First().Id;

                await OpenPort(deviceId);
            }

            ReadCancellationTokenSource = new CancellationTokenSource();

            while (true)
            {
                await Listen();
            }
        }
Ejemplo n.º 13
0
        private async void MainPage_LoadedAsync(object sender, RoutedEventArgs e)
        {
            // Get available devices for capturing media and list them 
            _allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (_allVideoDevices == null || !_allVideoDevices.Any())
            {
                Debug.WriteLine("No devices found.");
                return;
            }
            //add to  device list
            foreach (DeviceInformation camera in _allVideoDevices)
            {
                if (CameraSelectionList.Items != null)
                {
                    CameraSelectionList.Items.Add(camera.Name);
                }
            }
        }
Ejemplo n.º 14
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //searches for video devices
            _allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (_allVideoDevices == null || !_allVideoDevices.Any())
            //Provides error in case of no devices
            {
                Debug.WriteLine("No devices found.");
                return;
            }
            foreach (DeviceInformation camera in _allVideoDevices)
            {
                if (CameraSelectionList.Items != null)
                {
                    CameraSelectionList.Items.Add(camera.Name);
                }
            }
        }
Ejemplo n.º 15
0
        private async void MainPage_LoadedAsync(object sender, RoutedEventArgs e)
        {
            // Get available devices for capturing media and list them
            _allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (_allVideoDevices == null || !_allVideoDevices.Any())
            {
                Debug.WriteLine("No devices found.");
                return;
            }
            //add to  device list
            foreach (DeviceInformation camera in _allVideoDevices)
            {
                if (CameraSelectionList.Items != null)
                {
                    CameraSelectionList.Items.Add(camera.Name);
                }
            }
        }
Ejemplo n.º 16
0
        private async void com2()
        {
            string deviceId = "";
            string aqs      = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection dlist = await DeviceInformation.FindAllAsync(aqs);

            if (dlist.Any())
            {
                deviceId = dlist.First().Id;//调试这个是有值了的
            }
            t2.Text = deviceId;
            using (SerialDevice serialPort = await SerialDevice.FromIdAsync(deviceId))
            {
                //serialPort 这个值都是空的 null
                var vv = SerialDevice.FromIdAsync(deviceId);
                var v  = serialPort?.PortName;
                t1.Text = v;
                t3.Text = "还是没有数据";
            }
        }
Ejemplo n.º 17
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            string qFilter = SerialDevice.GetDeviceSelector("UART0");
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(qFilter);

            if (devices.Any())
            {
                string deviceId = devices.First().Id;

                await OpenPort(deviceId);
            }

            ReadCancellationTokenSource = new CancellationTokenSource();

            while (true)
            {
                //System.Diagnostics.Debug.WriteLine("program came before await listen");
                await Listen();
            }
        }
Ejemplo n.º 18
0
        public void Initialize()
        {
            var settings = new I2cConnectionSettings(address)
            {
                BusSpeed = I2cBusSpeed.FastMode
            };
            DeviceInformationCollection devices = null;

            Task.Run(async() =>
            {
                string aqs = I2cDevice.GetDeviceSelector();
                devices    = await DeviceInformation.FindAllAsync(aqs);
                if (!devices.Any())
                {
                    throw new IOException("No I2C controllers were found on the system");
                }
                sensor = await I2cDevice.FromIdAsync(devices[0].Id, settings);
            }).Wait();

            if (sensor == null)
            {
                string message;
                if (devices != null && devices.Count > 0)
                {
                    message = string.Format(
                        "Slave address {0} on I2C Controller {1} is currently in use by another application. Please ensure that no other applications are using I2C.",
                        settings.SlaveAddress,
                        devices[0].Id);
                }
                else
                {
                    message = "Could not initialize the device!";
                }

                throw new IOException(message);
            }
            Debug.WriteLine("Sensor connected");
        }
Ejemplo n.º 19
0
        public async Task InitializeCameraAsync()
        {
            try
            {
                if (_setup == null)
                {
                    _setup = new SetupService();
                }
                isAutoShot = await _setup.GetAutomode();

                if (_mediaCapture == null)
                {
                    _mediaCapture         = new MediaCapture();
                    _mediaCapture.Failed += MediaCapture_Failed;

                    _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (_cameraDevices == null || !_cameraDevices.Any())
                    {
                        throw new NotSupportedException();
                    }
                    DeviceInformation device;
                    if (_cameraDevices.Count > 1)
                    {
                        device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Windows.Devices.Enumeration.Panel.Back);
                    }
                    else
                    {
                        device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);
                    }

                    var cameraId = device?.Id ?? _cameraDevices.First().Id;


                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (_mediaCapture.VideoDeviceController.FocusControl.Supported)
                    {
                        isAutoFocusCapable = true;
                        errorMessage.Text  = "VIZZoneInFront".GetLocalized();
                    }
                    else
                    {
                        isAutoFocusCapable = false;
                        errorMessage.Text  = "NoFocusCamera".GetLocalized();
                    }

                    IMediaEncodingProperties IProps = this._mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
                    vep = (VideoEncodingProperties)IProps;

                    DrawLineOnCanvas(vep.Width, vep.Height);


                    if (Panel == Windows.Devices.Enumeration.Panel.Back)
                    {
                        //_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        //_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = false;
                    }

                    IsInitialized = true;

                    CanSwitch = _cameraDevices?.Count > 1;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
            catch (UnauthorizedAccessException)
            {
                errorMessage.Text = "Camera_Exception_UnauthorizedAccess".GetLocalized();
            }
            catch (NotSupportedException)
            {
                errorMessage.Text = "Camera_Exception_NotSupported".GetLocalized();
            }
            catch (TaskCanceledException)
            {
                errorMessage.Text = "Camera_Exception_InitializationCanceled".GetLocalized();
            }
            catch (Exception)
            {
                errorMessage.Text = "Camera_Exception_InitializationError".GetLocalized();
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            //Save application state and stop any background activity
            var currentView = (Window.Current.Content as AppShell)?.AppFrame?.Content;

            if (currentView != null && currentView.GetType() == typeof(RealTimeDemo))
            {
                await(currentView as RealTimeDemo).HandleApplicationShutdownAsync();
            }

            using (var session = new ExtendedExecutionSession())
            {
                session.Reason      = ExtendedExecutionReason.Unspecified;
                session.Description = "Upload Data";
                var result = await session.RequestExtensionAsync();

                await Util.CallEventHubHttp("test");

                if (result == ExtendedExecutionResult.Denied)
                {
                    await Util.CallEventHubHttp("denied");
                }
                else
                {
                    DeviceInformationCollection videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (!videoDevices.Any())
                    {
                        Debug.WriteLine("No cameras found.");
                        await Util.CallEventHubHttp("no device");
                    }
                    else
                    {
                        DeviceInformation camera;
                        if (SettingsHelper.Instance.CameraName == "")
                        {
                            camera = videoDevices.FirstOrDefault();
                        }
                        else
                        {
                            camera = videoDevices.FirstOrDefault(c => c.Name == SettingsHelper.Instance.CameraName);
                        }

                        if (camera == null)
                        {
                            await Util.CallEventHubHttp("null");
                        }
                        MediaCapture mediaCapture = new MediaCapture();

                        MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings
                        {
                            VideoDeviceId      = camera.Id,
                            PhotoCaptureSource = PhotoCaptureSource.VideoPreview
                        };

                        await mediaCapture.InitializeAsync(mediaInitSettings);

                        //await SetMaxResolution(mediaCapture);

                        PhotoHelper.camera = mediaCapture;
                        while (true)
                        {
                            var stream = await PhotoHelper.TakePhoto();

                            var faces = await FaceServiceHelper.DetectAsync(stream, true, true, ImageAnalyzer.DefaultFaceAttributeTypes);

                            //Debug.WriteLine(faces.First().FaceId);
                            await Util.CallEventHubHttp("working");

                            await Task.Delay(1000);
                        }
                    }
                }
                deferral.Complete();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// initialize SerialPortComboBox with names of all available serial ports
        /// </summary>
        private async Task <List <SerialPortTuple> > GetAvailableSerialPorts()
        {
            /*
             * SEE https://social.msdn.microsoft.com/Forums/windowsapps/en-US/0c638b8e-482d-462a-97e6-4d8bc86d8767/uwp-windows-10-apps-windowsdevicesserialcommunicationserialdevice-class-not-working?forum=wpdevelop
             *
             *  (a) There are several ways to get the Id
             *  //[1] via COM
             *  var selector = SerialDevice.GetDeviceSelector("COM3"); //Get the serial port on port '3'
             *  var myDevices = await DeviceInformation.FindAllAsync(selector);
             *  //[2] via USB VID-PID
             *  ushort vid = 0x0403;
             *  ushort pid = 0x6001;
             *  string aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(vid, pid);
             *  var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);
             *  //[3] More general
             *  string aqs = SerialDevice.GetDeviceSelector();
             *  var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);
             *  (b) Check if there is at least one
             *              if (myDevices.Count == 0)
             *              {
             *                  //Report error
             *                  return;
             *              }
             *  (c) Use first instance
             *              string id = myDevices[0].Id;  //Or if more than one use index other than 1
             *              serialDevice = await SerialDevice.FromIdAsync(id);
             *          if( serialDevice == null)
             *          {
             *      //Report error
             *      return;
             *          }
             *          serialDevice.Baud = 9600;
             *              serialDevice.DataBits = 8;
             *              serialDevice.Parity = SerialParity.None;
             *              serialDevice.StopBits = SerialStopBitCount.One;
             *              serialDevice.Handshake = SerialHandshake.None;
             *          //async code for send and receive
             *      .. etc
             *  (d) Close connection
             *          serialDevice.Close();
             *  </code>
             */

            //string[] ports = new string[] { "COM3", "COM7" };     // SerialPort.GetPortNames(); - not available in UW: System.IO.Ports
            //SerialPortComboBox.ItemsSource = ports;

            string aqs = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);

            List <SerialPortTuple> ports = new List <SerialPortTuple>();

            if (myDevices.Any())
            {
                foreach (var device in myDevices)
                {
                    ports.Add(new SerialPortTuple()
                    {
                        Name = device.Name, Id = device.Id
                    });
                }
            }
            else
            {
                StatusLabel.Text = "there are no serial devices representing Hardware Brick";
            }

            return(ports);
        }
Ejemplo n.º 22
0
        public async void OpenOptionsFile(MainPage page)
        {
            string slaveId  = "";
            string deviceId = "";
            string TimeOut  = "";
            string interval = "";
            string period   = "";
            string Ncom     = "";
            string speed    = "";
            string bit      = "";
            string parity   = "";
            string stopBit  = "";
            string typeConn = "";
            string IP       = "";
            string portTcp  = "";
            string typeD    = "";
            string conn     = "";

            ////Открываем локальную папку
            //StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            //// получаем файл
            //StorageFile configFile = await localFolder.GetFileAsync("config.ini");
            //// читаем файл
            //string text = await FileIO.ReadTextAsync(configFile);

            string text = ReadConfigFile();

            //Десериализуем Json формат
            dynamic xxx = Newtonsoft.Json.JsonConvert.DeserializeObject(text);


            var count = -1;
            int cd    = 0;

            //Выбор Девайсов из config
            foreach (object d in xxx.Device)
            {
                count++;
                if (page.selectDev == count.ToString())
                {
                    slaveId  = $"{xxx.Device[count].slaveId}";
                    deviceId = $"{xxx.Device[count].deviceId}";
                    TimeOut  = $"{xxx.Device[count].timeOut}";
                    interval = $"{xxx.Device[count].interval}";
                    period   = $"{xxx.Device[count].period}";
                    typeD    = $"{xxx.Device[count].typeD}";
                    conn     = $"{xxx.Device[count].conn}";
                    cd       = count;
                }
            }

            count = -1;
            foreach (object d in xxx.Connections)
            {
                count++;
                typeConn = xxx.Connections[count].typeConn;
                Ncom     = $"{xxx.Connections[count].Ncom}";
                speed    = $"{xxx.Connections[count].speed}";
                bit      = $"{xxx.Connections[count].bit}";
                parity   = $"{xxx.Connections[count].parity}";
                stopBit  = $"{xxx.Connections[count].stopBit}";
                IP       = xxx.Connections[count].IP;
                portTcp  = xxx.Connections[count].portTcp;
            }
            //slaveId = $"{xxx.Device[count].slaveId}";
            //    deviceId = $"{xxx.Device[count].deviceId}";
            //    TimeOut = $"{xxx.Device[count].timeOut}";
            //    interval = $"{xxx.Device[count].interval}";
            //    period = $"{xxx.Device[count].period}";
            //    typeD = $"{xxx.Device[count].typeD}";
            //    conn = $"{xxx.Device[count].conn}";
            //    typeConn = xxx.Connections[count].typeConn;
            //    Ncom = $"{xxx.Connections[count].Ncom}";
            //    speed = $"{xxx.Connections[count].speed}";
            //    bit = $"{xxx.Connections[count].bit}";
            //    parity = $"{xxx.Connections[count].parity}";
            //    stopBit = $"{xxx.Connections[count].stopBit}";
            //    IP = xxx.Connections[count].IP;
            //    portTcp = xxx.Connections[count].portTcp;

            // count = 0;
            page.comboDeviceNumber.Items.Clear();
            foreach (object d in xxx.Device)
            {
                count++;
                page.comboDeviceNumber.Items.Add(count);
            }

            if (typeConn == "COM")
            {
                page.connectCom.IsChecked = true;
            }
            else if (typeConn == "TCP")
            {
                page.connectTcp.IsChecked = true;
            }
            ;
            if (typeD == "PW")
            {
                page.comboDeviceType.SelectedIndex = 0;
            }
            else
            {
                page.comboDeviceType.SelectedIndex = 1;
            }


            page.textRowSlaveId.Text             = slaveId;
            page.textRowTimeOut.Text             = TimeOut;
            page.textRowInterval.Text            = interval;
            page.textRowPeriod.Text              = period;
            page.textRowDeviceId.Text            = deviceId;
            page.textRowIpAdres.Text             = IP;
            page.textRowPortIP.Text              = portTcp;
            page.comboDeviceNumber.SelectedIndex = cd;
            if (speed == "9600")
            {
                page.s9600.IsChecked = true;
            }
            else if (speed == "19200")
            {
                page.s19200.IsChecked = true;
            }
            else if (speed == "38400")
            {
                page.s38400.IsChecked = true;
            }
            else if (speed == "57600")
            {
                page.s57600.IsChecked = true;
            }
            else if (speed == "115200")
            {
                page.s115200.IsChecked = true;
            }
            if (bit == "7")
            {
                page.bit7.IsChecked = true;
            }
            else
            {
                page.bit8.IsChecked = true;
            }
            if (parity == "none")
            {
                page.parityNone.IsChecked = true;
            }
            else if (parity == "Odd")
            {
                page.parityOdd.IsChecked = true;
            }
            else if (parity == "Even")
            {
                page.parityEven.IsChecked = true;
            }
            if (stopBit == "2")
            {
                page.stopBit2.IsChecked = true;
            }
            else
            {
                page.stopBit1.IsChecked = true;
            }

            List <string> namberPort = new List <string>();
            var           lk         = namberPort.Count;

            page.ComboBoxCom.Items.Clear();
            int first = 0;

            for (int i = 1; i < 10; i++)
            {
                // Берем селектор выбранного сом порта
                string filt = SerialDevice.GetDeviceSelector("COM" + i);
                // Выбираем все устройства с селектором данного сом порта
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(filt);

                // Если обнаружено хоть одно устройство
                if (devices.Any())
                {
                    page.ComboBoxCom.Items.Add("COM" + i);
                    if (first == 0)
                    {
                        first = 2;
                        page.ComboBoxCom.SelectedIndex = 0;
                        //string ggh = "COM9" + i;
                        //ComboBoxCom.PlaceholderText = ggh;
                        //string ddd = ComboBoxCom.SelectedIndex.ToString();
                    }
                    namberPort.Add("COM" + i);
                }
            }
        }
Ejemplo n.º 23
0
        private async void Light_Controll(object sender, RoutedEventArgs e)
        {
            objTextBox.Text = "Θέλετε να ανοίξετε ή να κλείσετε τα φώτα;";
            await Speak(sender, e);

            await Task.Delay(TimeSpan.FromSeconds(2));

            await SpeakToComputer(sender, e);

            //      Create a socket and send udp message
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                                     ProtocolType.Udp);

            IPAddress serverAddr = IPAddress.Parse("192.168.2.20");

            IPEndPoint endPoint = new IPEndPoint(serverAddr, 5005);

            Debug.WriteLine(endPoint.ToString());

            string selector = SerialDevice.GetDeviceSelector("COM5");
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            Debug.WriteLine(devices);
            if (!devices.Any())
            {
                return;
            }
            string       deviceId     = devices.First().Id;
            SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceId);

            serialDevice.BaudRate  = 9600;
            serialDevice.DataBits  = 8;
            serialDevice.StopBits  = SerialStopBitCount.Two;
            serialDevice.Parity    = SerialParity.None;
            serialDevice.Handshake = SerialHandshake.None;
            DataWriter dataWriter = new DataWriter(serialDevice.OutputStream);

            Debug.WriteLine(objTextBox.Text);
            switch (objTextBox.Text)
            {
            case ("open"):
                string text = "1";
                Debug.WriteLine("sending " + text);
                byte[] send_buffer = Encoding.ASCII.GetBytes(text);



                sock.SendTo(send_buffer, endPoint);
                break;


            case ("open USB"):
                dataWriter.WriteString("1");
                await dataWriter.StoreAsync();

                dataWriter.DetachStream();
                dataWriter = null;

                break;

            case ("close USB"):
                dataWriter.WriteString("0");
                await dataWriter.StoreAsync();

                dataWriter.DetachStream();
                dataWriter = null;

                break;



            case ("close"):
                text        = "0";
                send_buffer = Encoding.ASCII.GetBytes(text);
                Debug.WriteLine("sending " + text);
                sock.SendTo(send_buffer, endPoint);

                break;

            default:
                text        = "1";
                send_buffer = Encoding.ASCII.GetBytes(text);
                Debug.WriteLine("sending " + text);
                // sock.SendTo(send_buffer, endPoint);
                await Task.Delay(TimeSpan.FromSeconds(1f));

                text        = "0";
                send_buffer = Encoding.ASCII.GetBytes(text);
                Debug.WriteLine("sending " + text);
                // sock.SendTo(send_buffer, endPoint);
                await Task.Delay(TimeSpan.FromSeconds(1f));

                text        = "1";
                send_buffer = Encoding.ASCII.GetBytes(text);
                Debug.WriteLine("sending " + text);
                // sock.SendTo(send_buffer, endPoint);
                await Task.Delay(TimeSpan.FromSeconds(1f));

                text        = "0";
                send_buffer = Encoding.ASCII.GetBytes(text);
                Debug.WriteLine("sending " + text);
                // sock.SendTo(send_buffer, endPoint);
                break;
            }
        }