Example #1
0
#pragma warning disable CA1303 // Do not pass literals as localized parameters
        static async Task Main(string[] args)
        {
            bool debugMode = false;
            Uri  socketUri = null;

            CaptureConfiguration.Init();

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed(options =>
            {
                socketUri = options.Uri == null ? new Uri(CaptureConfiguration.Configuration["Piscato.Gateway.Endpoint"]) : options.Uri;
                debugMode = options.Debug;
            });

            Console.WriteLine("Start recording");
            DeviceManagement.DisplayAllDevices();

            var conversationId = Guid.NewGuid().ToString();

            await StartCaptureAsync(socketUri, conversationId, debugMode).ConfigureAwait(false);

            StopCapture();
            Console.WriteLine("End of recording");
            Cleanup();

            Console.CancelKeyPress += (s, e) =>
            {
                Exit();
            };

            Console.ReadLine();
            Exit();
        }
        private void ProcessPhoneForWizard(UIDevice device)
        {
            if (this._deviceArrivalTimer != null)
            {
                this._deviceArrivalTimer.Stop();
            }
            SingletonModelItem <UIDeviceList> .Instance.DeviceConnectedEvent  -= new DeviceListEventHandler(this.OnDeviceConnected);
            SingletonModelItem <UIDeviceList> .Instance.AllowDeviceConnections = false;
            if (device.Class == DeviceClass.WindowsPhone && device.Relationship == DeviceRelationship.None && !device.RequiresAutoRestore)
            {
                if (device.SupportsOOBECompleted && !device.OOBECompleted)
                {
                    SingletonModelItem <UIDeviceList> .Instance.HideDevice(device);

                    DeviceManagement.ShowDeviceOOBEIncompleteDialog();
                    this.WizardType = FirstLaunchWizardType.Standard;
                }
                else
                {
                    SingletonModelItem <UIDeviceList> .Instance.DeviceDisconnectedEvent += new DeviceListEventHandler(this.OnDeviceDisconnected);
                    this.WizardType = FirstLaunchWizardType.PhoneFirstConnect;
                }
            }
            else
            {
                this.WizardType = FirstLaunchWizardType.Standard;
            }
        }
Example #3
0
 public void Stop(bool[] parSelectedPads, DeviceManagement devManLevel)
 {
     for (uint dsID = 1; dsID <= SCPConstants.MAX_XINPUT_DEVICES; dsID++)
     {
         if (parSelectedPads[dsID - 1])
         {
             uint id = GetvjFromDS(dsID);
             try
             {
                 if (vibrationCore != null)
                 {
                     vibrationCore.FfbStop(id);
                     vibrationCore = null;
                 }
                 joystick.RelinquishVJD(id);
             }
             catch
             {
                 //if this ever produces an error
             }
         }
     }
     if ((devManLevel & DeviceManagement.vJoy_Device) == DeviceManagement.vJoy_Device)
     {
         EnableVJoy(false);
     }
 }
        // GET: Device/Details/5
        public JsonResult DeviceDetails()
        {
            int id = ((UserSessionModel)this.HttpContext.Session["user"]).Id;
            List <DeviceModel> deviceModels = new DeviceManagement(id).GetUserDevices();

            return(Json(deviceModels, JsonRequestBehavior.AllowGet));
        }
Example #5
0
 public FakeNobreak(string _vid, string _pid)
 {
     vid = _vid;
     pid = _pid;
     MyDeviceManagement = new DeviceManagement();
     myOutputReport     = new Hid.OutputReport();
     myInputReport      = new Hid.InputReport();
 }
Example #6
0
        //public event FalhaDeRedeEventHandler FalhaDeRedeEvent;
        //public event BateriaOkEventHandler BateriaOkEvent;
        ////public event DesligamentoSistema;
        //public event HibernacaoSistema;
        //public event RetornoSistema;
        //public event TesteSolicitado;
        //public event RetornoTeste;
        //public event ModoBypass;
        //public event AnormalidadeEventHandler AnormalidadeEvent;

        public FakeNobreak()
        {
            vid = "0483";
            pid = "0035";
            MyDeviceManagement = new DeviceManagement();
            myOutputReport     = new Hid.OutputReport();
            myInputReport      = new Hid.InputReport();
        }
Example #7
0
 public override object this[object key]
 {
     get => base[key];
     set
     {
         base[key] = value;
         DeviceManagement.HandleSetupQueue();
     }
 }
        public Boolean RegisterDeviceNotification(IntPtr hwndHandle)
        {
            if (false == DeviceManagement.RegisterForHIDDeviceNotifications(hwndHandle, ref m_pdeviceHandler))
            {
                m_strLastErrorInfo = "Failed to register for HID device notifications!";
                return(false);
            }

            return(true);
        }
        internal static void ForceDisconnect()
        {
            _usbDevice.Disconnected = true;
            DeviceDetected          = false;

            _usbDevice     = new WinUsbDevice();
            _deviceManager = new DeviceManagement();

            _devicePathName = string.Empty;
        }
        public Boolean UnregisterDeviceNotification()
        {
            if (false == DeviceManagement.StopReceivingDeviceNotifications(m_pdeviceHandler))
            {
                m_strLastErrorInfo = "Failed to stop receiving HID device notifications!";
                return(false);
            }

            return(true);
        }
        private void TestDeviceManagement_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var window = new DeviceManagement
            {
                Owner                 = this,
                ShowInTaskbar         = false,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            window.ShowDialog();
        }
        private void InitDataGridView()
        {
            dgvMyDevice.Rows.Clear();                      /* 清空表格 */
            deviceManagement = new DeviceManagement();
            int count = deviceManagement.DeviceList.Count; /* 设备数量 */

            for (int idx = 0; idx < count; idx++)          /* 将设备添加到表格中 */
            {
                int index = dgvMyDevice.Rows.Add();
                dgvMyDevice.Rows[index].Cells[0].Value = deviceManagement.DeviceList[idx].name;
            }
        }
        public String[] FindDevice(String tDeviceType, params Object[] tParameter)
        {
            /*! check device ID */
            if (tDeviceType != "ES_USB_HID")
            {
                m_strLastErrorInfo = "Unknown device type.";
                return(null);
            }

            if (null == tParameter)
            {
                m_strLastErrorInfo = "Illegal Vender ID and Product ID";
                return(null);
            }
            else if (tParameter.Length < 2)
            {
                m_strLastErrorInfo = "Illegal Vender ID and Product ID";
                return(null);
            }


            UInt16 tVenderID  = 0;
            UInt16 tProductID = 0;

            if ((tParameter[0] is UInt16) || (tParameter[0] is Int16) || (tParameter[0] is UInt32) || (tParameter[0] is Int32))
            {
                tVenderID = (UInt16)tParameter[0];
            }
            else
            {
                m_strLastErrorInfo = "Illegal Vender ID and Product ID:";
                return(null);
            }

            if ((tParameter[1] is UInt16) || (tParameter[1] is Int16) || (tParameter[1] is UInt32) || (tParameter[1] is Int32))
            {
                tProductID = (UInt16)tParameter[1];
            }
            else
            {
                m_strLastErrorInfo = "Illegal Vender ID and Product ID:";
                return(null);
            }

            String[] tResult = DeviceManagement.FindHIDDevices((Int16)tVenderID, (Int16)tProductID);
            if (null == tResult)
            {
                m_strLastErrorInfo = "Could not find specified USB HID device!";
            }

            return(tResult);
        }
 public JsonResult Create(DeviceModel model)
 {
     try
     {
         int id = ((UserSessionModel)this.HttpContext.Session["user"]).Id;
         DeviceManagement objDevceManager = new DeviceManagement(id);
         objDevceManager.CreateDevice(model);
         return(Json(true));
     }
     catch
     {
         return(Json(false));
     }
 }
Example #15
0
        public ActionResult DeleteConfirmed(long id)
        {
            Device device = db.Devices.Find(id);

            db.Devices.Remove(device);
            db.SaveChanges();

            // Remove the specified device from IoT Hub
            var task = Task.Run(async() =>
            {
                await DeviceManagement.RemoveDeviceAsync(device.DeviceId);
            });

            task.Wait();

            return(RedirectToAction("Index"));
        }
Example #16
0
 /// <summary>
 /// The guid and the form that will utilize the mechaboard will be passed as
 /// arguments to the constructor
 /// In the context of our final project, the form reference that will
 /// be passed to the constructor is the
 /// reference for the mainform only. Other forms will subscribe and
 /// unsubscribe to/from device notifications via
 /// the methods of the MechaBoard class. Note that form reference is passed solely for subscribing
 /// </summary>
 /// <param name="guid">the unique identifier string for the mechaboard that is to be used</param>
 /// <param name="form_reference">the form that is going to utilize the functionalities
 /// of the mechaboar</param>
 public MechaBoard(String guid, Form form_reference)
 {
     //notification handle for the main board
     deviceNotificationHandle = IntPtr.Zero;
     //device for usb communication
     device = new WinUsbDevice();
     //manager for the device
     deviceManager = new DeviceManagement();
     //path name of the device used for identification
     devicePathName = "";
     //whether device detected or not
     isDeviceDetected = false;
     //guid of the device
     deviceGUID = guid;
     //form reference used to register the notifications about the board, should be the
     //reference of the mainform
     formReference = form_reference;
     //lock handle to safely provide accesses to the board
     boardLockHandle = new object();
 }
Example #17
0
        // GET: Devices/Create
        public ActionResult Create()
        {
            //return View();
            int    count  = db.Devices.Count <Device>();
            Device entity = null;
            int    maxId  = count;

            if (count > 0)
            {
                entity = db.Devices.OrderByDescending(x => x.DeviceId).First();
                if (!int.TryParse(entity.DeviceId.Substring(6), out maxId))
                {
                    maxId = count;
                }
            }

            string deviceId = "Device" + (maxId + 1).ToString("D3");

            // Add the specified device to IoT Hub
            var task = Task.Run(async() =>
            {
                await DeviceManagement.AddDeviceAsync(deviceId);
            });

            task.Wait();

            Device device = new Device
            {
                DeviceId         = deviceId,
                DeviceKey        = DeviceManagement.GetDeviceKey(),
                ConnectionString = DeviceManagement.GetIothubConnectionString(),
                IsUsed           = false,
                IsActive         = false,
                TimeStamp        = DateTime.UtcNow
            };

            // Add the specified device to [Devices] table
            db.Devices.Add(device);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        private void dgvMyDevice_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvMyDevice.CurrentRow == null)
            {
                return;
            }
            int    index = dgvMyDevice.CurrentRow.Index; /* 获取选择行号 */
            string name  = dgvMyDevice.Rows[index].Cells[0].Value.ToString();

            deviceManagement = new DeviceManagement();
            int count = deviceManagement.DeviceList.Count; /* 获取设备数量 */

            for (int idx = 0; idx < count; idx++)          /* 获取设备名称与MAC */
            {
                if (deviceManagement.DeviceList[idx].name == name)
                {
                    tbDeviceName.Text    = name;
                    tbID.Text            = deviceManagement.DeviceList[idx].ID.ToString();
                    tbDeviceAddress.Text = deviceManagement.DeviceList[idx].mac;
                }
            }
        }
Example #19
0
        private static void DisposeNIA()
        {
            try
            {
                //  Close open handles to the device.
                if (!(hidHandle == null))
                {
                    if (!(hidHandle.IsInvalid))
                    {
                        hidHandle.Close();
                    }
                }

                if (!(readHandle == null))
                {
                    if (!(readHandle.IsInvalid))
                    {
                        readHandle.Close();
                    }
                }

                if (!(writeHandle == null))
                {
                    if (!(writeHandle.IsInvalid))
                    {
                        writeHandle.Close();
                    }
                }

                //  Stop receiving notifications.
                DeviceManagement deviceManagement = new DeviceManagement();
                deviceManagement.StopReceivingDeviceNotifications(deviceNotificationHandle);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #20
0
 public void Stop(bool[] parSelectedPads, DeviceManagement devManLevel)
 {
     for (uint dsID = 1; dsID <= SCPConstants.MAX_XINPUT_DEVICES; dsID++)
     {
         if (parSelectedPads[dsID - 1])
         {
             uint id = GetvjFromDS(dsID);
             try
             {
                 if (vibrationCore != null)
                 {
                     vibrationCore.FfbStop(id);
                     vibrationCore = null;
                 }
                 joystick.RelinquishVJD(id);
             }
             catch
             {
                 //if this ever produces an error
             }
         }
     }
     if ((devManLevel & DeviceManagement.vJoy_Device) == DeviceManagement.vJoy_Device)
     {
         EnableVJoy(false);
     }
 }
Example #21
0
        ///  <summary>
        ///  Uses a series of API calls to locate a HID-class device
        ///  by its Vendor ID and Product ID.
        ///  </summary>
        ///
        ///  <returns>
        ///   True if the device is detected, False if not detected.
        ///  </returns>

        public static Boolean FindTheHid(
            int myVendorID
            , int myProductID
            , ref IntPtr FrmMyHandle
            , ref IntPtr deviceNotificationHandle
            , ref Boolean exclusiveAccess
            , ref String hidUsage
            , ref Boolean myDeviceDetected
            , ref String myDevicePathName
            , ref FileStream fileStreamDeviceData
            , ref SafeFileHandle hidHandle
            , ref DeviceManagement MyDeviceManagement
            , ref Hid MyHid
            , ref string message
            , ref string txtInputReportBufferSize
            )
        {
            Boolean deviceFound = false;

            String[] devicePathName = new String[128];
            Guid     hidGuid        = Guid.Empty;
            Int32    memberIndex    = 0;
            //Int32 myProductID = 0;
            //Int32 myVendorID = 0;
            Boolean success = false;

            try
            {
                myDeviceDetected = false;
                CloseCommunications(
                    ref myDeviceDetected
                    , ref fileStreamDeviceData
                    , ref hidHandle
                    );

                //  Get the device's Vendor ID and Product ID

                //myVendorID = Main.CardReader_VID;
                //myProductID = Main.CardReader_PID;

                //  ***
                //  API function: 'HidD_GetHidGuid
                //  Purpose: Retrieves the interface class GUID for the HID class.
                //  Accepts: 'A System.Guid object for storing the GUID.
                //  ***

                Hid.HidD_GetHidGuid(ref hidGuid);

                //  Fill an array with the device path names of all attached HIDs.
                deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                //  If there is at least one HID, attempt to read the Vendor ID and Product ID
                //  of each device until there is a match or all devices have been examined.

                if (deviceFound)
                {
                    memberIndex = 0;

                    do
                    {
                        //  ***
                        //  API function:
                        //  CreateFile

                        //  Purpose:
                        //  Retrieves a handle to a device.

                        //  Accepts:
                        //  A device path name returned by SetupDiGetDeviceInterfaceDetail
                        //  The type of access requested (read/write).
                        //  FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                        //  A Security structure or IntPtr.Zero.
                        //  A creation disposition value. Use OPEN_EXISTING for devices.
                        //  Flags and attributes for files. Not used for devices.
                        //  Handle to a template file. Not used.

                        //  Returns: a handle without read or write access.
                        //  This enables obtaining information about all HIDs, even system
                        //  keyboards and mice.
                        //  Separate handles are used for reading and writing.
                        //  ***

                        // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.
                        hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                        if (!hidHandle.IsInvalid)
                        {
                            //  The returned handle is valid,
                            //  so find out if this is the device we're looking for.

                            //  Set the Size property of DeviceAttributes to the number of bytes in the structure.

                            MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);

                            //  ***
                            //  API function:
                            //  HidD_GetAttributes

                            //  Purpose:
                            //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                            //  Product ID, and Product Version Number for a device.

                            //  Accepts:
                            //  A handle returned by CreateFile.
                            //  A pointer to receive a HIDD_ATTRIBUTES structure.

                            //  Returns:
                            //  True on success, False on failure.
                            //  ***

                            success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                            if (success)
                            {
                                //  Find out if the device matches the one we're looking for.
                                if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID))
                                {
                                    //  Display the information in form's list box.
                                    message = "was found.";

                                    myDeviceDetected = true;

                                    //  Save the DevicePathName for OnDeviceChange().
                                    myDevicePathName = devicePathName[memberIndex];
                                }
                                else
                                {
                                    //  It's not a match, so close the handle.

                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                            else
                            {
                                //  There was a problem in retrieving the information.

                                //Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                myDeviceDetected = false;
                                hidHandle.Close();
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.

                        memberIndex = memberIndex + 1;
                    }while (!((myDeviceDetected || (memberIndex == devicePathName.Length))));
                }

                if (myDeviceDetected)
                {
                    //  The device was detected.
                    //  Register to receive notifications if the device is removed or attached.

                    success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, FrmMyHandle, hidGuid, ref deviceNotificationHandle);

                    //  Learn the capabilities of the device.

                    MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);

                    if (success)
                    {
                        //  Find out if the device is a system mouse or keyboard.

                        hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);

                        //  Get the Input report buffer size.

                        GetInputReportBufferSize(
                            ref exclusiveAccess
                            , ref hidHandle
                            , ref MyHid
                            , ref txtInputReportBufferSize
                            );

                        //Close the handle and reopen it with read/write access.

                        hidHandle.Close();
                        hidHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                        if (hidHandle.IsInvalid)
                        {
                            exclusiveAccess = true;
                        }
                        else
                        {
                            if (MyHid.Capabilities.InputReportByteLength > 0)
                            {
                                //  Set the size of the Input report buffer.

                                Byte[] inputReportBuffer = null;
                                inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength];

                                fileStreamDeviceData = new FileStream(hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false);
                            }

                            if (MyHid.Capabilities.OutputReportByteLength > 0)
                            {
                                Byte[] outputReportBuffer = null;
                                outputReportBuffer = new Byte[MyHid.Capabilities.OutputReportByteLength];
                            }

                            //  Flush any waiting reports in the input buffer. (optional)

                            MyHid.FlushQueue(hidHandle);
                        }
                    }
                }
                else
                {
                    //  The device wasn't detected.
                    myDeviceDetected = false;
                    message          = "not found.";
                }

                return(myDeviceDetected);
            }

            catch (Exception ex)
            {
                DisplayException("FindTheHid", ex);
                //throw;
            }

            return(false);
        }
Example #22
0
        public bool Start(bool[] parSelectedPads, PadSettings config, DeviceManagement devManLevel)
        {
            //Setup vJoy
            //Perform device enable/disable based on dll version
            //EnableVJoy needs to know which version of vJoy we are running
            joystick = new vJoy();
            UInt32 DllVer = 0, DrvVer = 0;

            joystick.DriverMatch(ref DllVer, ref DrvVer);
            //MIN Version Check 1
            vJoyVersion = DllVer;
            if (vJoyVersion < vJoyConstants.MIN_VER)
            {
                Trace.WriteLine("vJoy version less than required: Aborting\n");
                Stop(parSelectedPads, devManLevel);
                return(false);
            }

            if ((devManLevel & DeviceManagement.vJoy_Config) == DeviceManagement.vJoy_Config)
            {
                EnableVJoy(false);
                SetupVjoy(parSelectedPads, config);
                vJoyInstall.RefreshvJoy(); //do it like vJConfig does (needed in 2.1.6)
                EnableVJoy(true);
            }
            else if ((devManLevel & DeviceManagement.vJoy_Device) == DeviceManagement.vJoy_Device)
            {
                EnableVJoy(true);
            }

            if (!joystick.vJoyEnabled())
            {
                Trace.WriteLine("vJoy driver not enabled: Failed Getting vJoy attributes.\n");
                return(false);
            }
            else
            {
                Trace.WriteLine(string.Format("Vendor : {0}\nProduct: {1}\nVersion: {2}\n",
                                              joystick.GetvJoyManufacturerString(),
                                              joystick.GetvJoyProductString(),
                                              joystick.GetvJoySerialNumberString()));

                // Test if DLL matches the driver
                bool match = joystick.DriverMatch(ref DllVer, ref DrvVer);
                if (match)
                {
                    Trace.WriteLine(string.Format("Version of Driver Matches DLL Version ({0:X})", DllVer));
                    Trace.WriteLine(string.Format("Version of vJoyInterfaceWrap.dll is ({0})",
                                                  typeof(vJoy).Assembly.GetName().Version));
                    Trace.WriteLine(string.Format("Version of ScpControl.dll is ({0})\n",
                                                  typeof(ScpControl.ScpProxy).Assembly.GetName().Version));
                }
                else
                {
                    Trace.WriteLine(string.Format("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})\n", DrvVer, DllVer));
                    Stop(parSelectedPads, devManLevel);
                    return(false);
                }
                //MinVersion Check
                vJoyVersion = DrvVer;
                if (vJoyVersion < vJoyConstants.MIN_VER)
                {
                    Trace.WriteLine("vJoy version less than required: Aborting\n");
                    Stop(parSelectedPads, devManLevel);
                    return(false);
                }
            }

            for (uint dsID = 1; dsID <= SCPConstants.MAX_XINPUT_DEVICES; dsID++)
            {
                if (parSelectedPads[dsID - 1])
                {
                    uint id = GetvjFromDS(dsID);

                    // Acquire the target
                    VjdStat status = joystick.GetVJDStatus(id);
                    if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
                    {
                        Trace.WriteLine(string.Format("Failed to acquire vJoy device number {0}.", id));
                        Stop(parSelectedPads, devManLevel);
                        return(false);
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("Acquired vJoy device number {0}.", id));
                    }
                    Trace.WriteLine(string.Format("Buttons : {0}.", joystick.GetVJDButtonNumber(id)));
                    Trace.WriteLine(string.Format("DiscPov : {0}.", joystick.GetVJDDiscPovNumber(id)));
                    Trace.WriteLine(string.Format("ContPov : {0}.", joystick.GetVJDContPovNumber(id)));
                    //FFB
                    if (config.ffb)
                    {
                        vibrationCore = new vJoyVibrate(joystick);
                        vibrationCore.FfbInterface(dsID);
                        vibrationCore.VibrationCommand += VibEventProxy;
                    }
                    // Reset this device to default values
                    joystick.ResetVJD(id);
                    //Set Axis to mid value
                    joyReport[dsID - 1].AxisX    = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].AxisY    = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].AxisZ    = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].AxisXRot = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].AxisYRot = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].AxisZRot = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].Slider   = vJoyConstants.HALF_AXIS_VALUE;
                    joyReport[dsID - 1].Dial     = vJoyConstants.HALF_AXIS_VALUE;
                }
            }
            return(true);
        }
Example #23
0
        public bool Start(bool[] parSelectedPads, PadSettings config, DeviceManagement devManLevel)
        {
            //Setup vJoy
            //Perform device enable/disable based on dll version
            //EnableVJoy needs to know which version of vJoy we are running
            joystick = new vJoy();
            UInt32 DllVer = 0, DrvVer = 0;
            joystick.DriverMatch(ref DllVer, ref DrvVer);
            //MIN Version Check 1
            vJoyVersion = DllVer;
            if (vJoyVersion < vJoyConstants.MIN_VER)
            {
                Trace.WriteLine("vJoy version less than required: Aborting\n");
                Stop(parSelectedPads, devManLevel);
                return false;
            }

            if ((devManLevel & DeviceManagement.vJoy_Config) == DeviceManagement.vJoy_Config)
            {
                EnableVJoy(false);
                SetupVjoy(parSelectedPads, config);
                vJoyInstall.RefreshvJoy(); //do it like vJConfig does (needed in 2.1.6)
                EnableVJoy(true);
            }
            else if ((devManLevel & DeviceManagement.vJoy_Device) == DeviceManagement.vJoy_Device)
            {
                EnableVJoy(true);
            }

            if (!joystick.vJoyEnabled())
            {
                Trace.WriteLine("vJoy driver not enabled: Failed Getting vJoy attributes.\n");
                return false;
            }
            else
            {
                Trace.WriteLine(String.Format("Vendor : {0}\nProduct: {1}\nVersion: {2}\n",
                joystick.GetvJoyManufacturerString(),
                joystick.GetvJoyProductString(),
                joystick.GetvJoySerialNumberString()));

                // Test if DLL matches the driver
                bool match = joystick.DriverMatch(ref DllVer, ref DrvVer);
                if (match)
                {
                    Trace.WriteLine(String.Format("Version of Driver Matches DLL Version ({0:X})", DllVer));
                    Trace.WriteLine(String.Format("Version of vJoyInterfaceWrap.dll is ({0})",
                        typeof(vJoy).Assembly.GetName().Version));
                    Trace.WriteLine(String.Format("Version of ScpControl.dll is ({0})\n",
                        typeof(ScpControl.ScpProxy).Assembly.GetName().Version));
                }
                else
                {
                    Trace.WriteLine(String.Format("Version of Driver ({0:X}) does NOT match DLL Version ({1:X})\n", DrvVer, DllVer));
                    Stop(parSelectedPads, devManLevel);
                    return false;
                }
                //MinVersion Check
                vJoyVersion = DrvVer;
                if (vJoyVersion < vJoyConstants.MIN_VER)
                {
                    Trace.WriteLine("vJoy version less than required: Aborting\n");
                    Stop(parSelectedPads, devManLevel);
                    return false;
                }
            }

            for (uint dsID = 1; dsID <= SCPConstants.MAX_XINPUT_DEVICES; dsID++)
            {
                if (parSelectedPads[dsID - 1])
                {
                    uint id = GetvjFromDS(dsID);

                    // Acquire the target
                    VjdStat status = joystick.GetVJDStatus(id);
                    if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!joystick.AcquireVJD(id))))
                    {
                        Trace.WriteLine(String.Format("Failed to acquire vJoy device number {0}.", id));
                        Stop(parSelectedPads, devManLevel);
                        return false;
                    }
                    else
                    {
                        Trace.WriteLine(String.Format("Acquired vJoy device number {0}.", id));
                    }
                    Trace.WriteLine(String.Format("Buttons : {0}.", joystick.GetVJDButtonNumber(id)));
                    Trace.WriteLine(String.Format("DiscPov : {0}.", joystick.GetVJDDiscPovNumber(id)));
                    Trace.WriteLine(String.Format("ContPov : {0}.", joystick.GetVJDContPovNumber(id)));
                    //FFB
                    if (config.ffb)
                    {
                        vibrationCore = new vJoyVibrate(joystick);
                        vibrationCore.FfbInterface(dsID);
                        vibrationCore.VibrationCommand += VibEventProxy;
                    }
                    // Reset this device to default values
                    joystick.ResetVJD(id);
                    //Set Axis to mid value
                    joyReport[dsID - 1].AxisX = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].AxisY = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].AxisZ = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].AxisXRot = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].AxisYRot = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].AxisZRot = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].Slider = HALF_VJOY_AXIS;
                    joyReport[dsID - 1].Dial = HALF_VJOY_AXIS;
                }
            }
            return true;
        }
Example #24
0
        public async Task <Tuple <DeviceProperties, Token> > ViewsAsync(string[] cmdInputs)
        {
            Console.WriteLine("VisionCloud SDK");

            do
            {
                var validUserName   = false;
                var un              = string.Empty;
                var pd              = string.Empty;
                var validPswd       = false;
                var validDeviceName = false;

                do
                {
                    ConsoleHelper.WriteInstruction("\nEnter username:\t");
                    un = Console.ReadLine();

                    if (string.IsNullOrEmpty(un))
                    {
                        ConsoleHelper.WriteError("Illegal entry for field: UserName");
                    }
                    else if (un.Length < 8)
                    {
                        ConsoleHelper.WriteError("Invalid length for field: UserName. Please try again...");
                    }
                    else
                    {
                        validUserName = true;
                    }
                } while (validUserName == false);

                do
                {
                    ConsoleHelper.WriteInstruction("\nEnter Password:\t");
                    Console.ForegroundColor = ConsoleColor.Black;
                    pd = Console.ReadLine();

                    if (string.IsNullOrEmpty(un))
                    {
                        ConsoleHelper.WriteError("Illegal entry for field: Password. Please try again...");
                    }
                    else if (un.Length < 8)
                    {
                        ConsoleHelper.WriteError("Invalid length for field: Password. Please try again...");
                    }
                    else
                    {
                        validPswd = true;
                    }
                } while (validPswd == false);

                do
                {
                    ConsoleHelper.WriteInstruction("\nEnter Device Name:\t");
                    dn = Console.ReadLine();

                    if (string.IsNullOrEmpty(dn))
                    {
                        ConsoleHelper.WriteError("Illegal entry for field: Device Name");
                    }
                    else if (dn.Length < 4)
                    {
                        ConsoleHelper.WriteError("Invalid length for field: Device Name. Please try again...");
                    }
                    else
                    {
                        validDeviceName = true;
                    }
                } while (validDeviceName == false);

                var token = LoginService.GetToken(un, pd);
                jwt = token;
                if (jwt != null)
                {
                    isLoggedIn = true;
                    DeviceManagement dm = new DeviceManagement(jwt);
                    deviceProperties = await dm.GetDeviceInfoAsync(dn);

                    deviceProperties.Name = dn;
                }
                else
                {
                    ConsoleHelper.WriteError("Unable to authenticate. Please check your credentials");
                }

                if (deviceProperties != null)
                {
                    ConsoleHelper.WriteObjectInfo(deviceProperties);
                }

                if (jwt != null && (deviceProperties?.AppsOnDevice == null || deviceProperties?.AppsOnDevice.Count == 0))
                {
                    ConsoleHelper.WriteWarning("No Apps found that are running on the device. You have limted access through sdk when device is offline. Please try again later...");
                }
            } while (isLoggedIn == false || jwt == null || deviceProperties.DeviceID == null);

            return(new Tuple <DeviceProperties, Token>(deviceProperties, jwt));
        }
Example #25
0
        /// <summary>
        /// Uses a series of API calls to locate a HID-class device
        /// by its Vendor ID and Product ID.
        /// </summary>
        /// <returns>True if the device is detected, False if not detected.</returns>
        private bool FindTheHid()
        {
            string[] DevicePathName = new string[128];
            FileIOApiDeclarations.SECURITY_ATTRIBUTES Security = new FileIOApiDeclarations.SECURITY_ATTRIBUTES();

            try
            {
                if (Settings.Instance.ExtensiveLogging)
                {
                    Log.Debug("MiniDisplay.VFD_Control: Searching for display with VendorID:{0:X} & ProductID:{1:X}", _VendorID,
                              _ProductID);
                }

                Guid HidGuid = Guid.Empty;
                _MyDeviceDetected = false;

                // Values for the SECURITY_ATTRIBUTES structure:
                Security.lpSecurityDescriptor = 0;
                Security.bInheritHandle       = Convert.ToInt32(true);
                Security.nLength = Marshal.SizeOf(Security);


                /*
                 *        API function: 'HidD_GetHidGuid
                 *        Purpose: Retrieves the interface class GUID for the HID class.
                 *        Accepts: 'A System.Guid object for storing the GUID.
                 */

                HidApiDeclarations.HidD_GetHidGuid(ref HidGuid);
                if (Settings.Instance.ExtensiveLogging)
                {
                    Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("GetHidGuid"));
                }

                // Display the GUID.
                string GUIDString = HidGuid.ToString();
                if (Settings.Instance.ExtensiveLogging)
                {
                    Log.Debug("MiniDisplay.VFD_Control: GUID for system HIDs: " + GUIDString);
                }

                // Fill an array with the device path names of all attached HIDs.
                bool DeviceFound = DeviceManagement.FindDeviceFromGuid(HidGuid, ref DevicePathName);

                // If there is at least one HID, attempt to read the Vendor ID and Product ID
                // of each device until there is a match or all devices have been examined.

                if (DeviceFound)
                {
                    int MemberIndex = 0;
                    do
                    {
                        // ***
                        // API function:
                        // CreateFile
                        // Purpose:
                        // Retrieves a handle to a device.
                        // Accepts:
                        // A device path name returned by SetupDiGetDeviceInterfaceDetail
                        // The type of access requested (read/write).
                        // FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                        // A Security structure. Using Null for this may cause problems under Windows XP.
                        // A creation disposition value. Use OPEN_EXISTING for devices.
                        // Flags and attributes for files. Not used for devices.
                        // Handle to a template file. Not used.
                        // Returns: a handle that enables reading and writing to the device.
                        // ***

                        _HIDHandle = FileIOApiDeclarations.CreateFile
                                         (DevicePathName[MemberIndex],
                                         FileIOApiDeclarations.GENERIC_READ | FileIOApiDeclarations.GENERIC_WRITE,
                                         FileIOApiDeclarations.FILE_SHARE_READ | FileIOApiDeclarations.FILE_SHARE_WRITE,
                                         ref Security,
                                         FileIOApiDeclarations.OPEN_EXISTING, 0, 0);

                        if (Settings.Instance.ExtensiveLogging)
                        {
                            Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("CreateFile"));
                        }
                        if (Settings.Instance.ExtensiveLogging)
                        {
                            Log.Debug("MiniDisplay.VFD_Control: Returned handle: " + _HIDHandle.ToString("x") + "h");
                        }

                        if (_HIDHandle != FileIOApiDeclarations.INVALID_HANDLE_VALUE)
                        {
                            // The returned handle is valid,
                            // so find out if this is the device we're looking for.

                            // Set the Size property of DeviceAttributes to the number of bytes in the structure.
                            _MyHID.DeviceAttributes.Size = Marshal.SizeOf(_MyHID.DeviceAttributes);

                            // ***
                            // API function:
                            // HidD_GetAttributes
                            // Purpose:
                            // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                            // Product ID, and Product Version Number for a device.
                            // Accepts:
                            // A handle returned by CreateFile.
                            // A pointer to receive a HIDD_ATTRIBUTES structure.
                            // Returns:
                            // True on success, False on failure.
                            // ***

                            int Result = HidApiDeclarations.HidD_GetAttributes(_HIDHandle, ref _MyHID.DeviceAttributes);


                            if (Settings.Instance.ExtensiveLogging)
                            {
                                Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("HidD_GetAttributes"));
                            }

                            if (Result != 0)
                            {
                                if (Settings.Instance.ExtensiveLogging)
                                {
                                    Log.Debug("MiniDisplay.VFD_Control: HIDD_ATTRIBUTES structure filled without error.");
                                }

                                if (Settings.Instance.ExtensiveLogging)
                                {
                                    Log.Debug(
                                        "MiniDisplay.VFD_Control: Vendor ID: {0:X}, Product ID: {1:X}, Version {2:X}" +
                                        _MyHID.DeviceAttributes.VendorID, _MyHID.DeviceAttributes.ProductID,
                                        _MyHID.DeviceAttributes.VersionNumber);
                                }

                                // Find out if the device matches the one we're looking for.
                                if ((_MyHID.DeviceAttributes.VendorID == _VendorID) &
                                    (_MyHID.DeviceAttributes.ProductID == _ProductID))
                                {
                                    // It's the desired device.
                                    if (Settings.Instance.ExtensiveLogging)
                                    {
                                        Log.Debug("MiniDisplay.VFD_Control: My device detected");
                                    }

                                    _MyDeviceDetected = true;

                                    // Save the DevicePathName so OnDeviceChange() knows which name is my device.
                                }
                                else
                                {
                                    // It's not a match, so close the handle.
                                    _MyDeviceDetected = false;

                                    FileIOApiDeclarations.CloseHandle(_HIDHandle);

                                    if (Settings.Instance.ExtensiveLogging)
                                    {
                                        Log.Debug("MiniDisplay.VFD_Control: " + Debugging.ResultOfAPICall("CloseHandle"));
                                    }
                                }
                            }
                            else
                            {
                                // There was a problem in retrieving the information.
                                if (Settings.Instance.ExtensiveLogging)
                                {
                                    Log.Debug("MiniDisplay.VFD_Control: Error in filling HIDD_ATTRIBUTES structure.");
                                }
                                _MyDeviceDetected = false;
                                FileIOApiDeclarations.CloseHandle(_HIDHandle);
                            }
                        }

                        // Keep looking until we find the device or there are no more left to examine.
                        MemberIndex = MemberIndex + 1;
                    } while (!(_MyDeviceDetected || (MemberIndex == DevicePathName.Length) || DevicePathName[MemberIndex] == null));
                }

                if (_MyDeviceDetected)
                {
                    // The device was detected.
                    // Learn the capabilities of the device.
                    _MyHID.Capabilities = _MyHID.GetDeviceCapabilities(_HIDHandle);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                //HandleException(this.Name + ":" + System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }
            return(_MyDeviceDetected);
        }
Example #26
0
 public skyetek_hid(String path)
 {
     MyDebugging = new Debugging(); //  For viewing results of API calls via Debug.Write.
     MyDeviceManagement = new DeviceManagement();
     MyHid = new Hid();
     readBuffer = new Queue<byte>(65);
     ReadFinished = false;
     ReadStart = 0;
     myDevicePathName = path;
 }
        public byte[] person_array_get(PersonnelManagement.PersonInfo PersonInfo)
        {
            Stm32_crc stm32_crc = new Stm32_crc();
            UInt32    crc       = 0;

            byte[] user_data = new byte[1 + USER_PACK_SIZE];
            byte[] data      = new byte[USER_PACK_SIZE];
            string temp_str;

            byte[] temp;

            /* 有效期 */
            System.Globalization.DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy年MM月dd日 HH:mm:ss";
            DateTime limitTime = Convert.ToDateTime(PersonInfo.limitTime, dtFormat);
            int      year      = limitTime.Year;
            int      month     = limitTime.Month;
            int      day       = limitTime.Day;
            int      hour      = limitTime.Hour;
            int      minute    = limitTime.Minute;
            int      second    = limitTime.Second;

            /* 用户号 */
            user_data[1] = (byte)((PersonInfo.uID & 0x00FF) >> 0);
            user_data[2] = (byte)((PersonInfo.uID & 0xFF00) >> 8);

            /* RFID卡号 */
            user_data[3] = (byte)((PersonInfo.cardID & 0x000000FF) >> 0);
            user_data[4] = (byte)((PersonInfo.cardID & 0x0000FF00) >> 8);
            user_data[5] = (byte)((PersonInfo.cardID & 0x00FF0000) >> 16);
            user_data[6] = (byte)((PersonInfo.cardID & 0xFF000000) >> 24);

            /* 激活状态 */
            user_data[7] = (byte)PersonInfo.activeState;

            /* 学号 */
            temp_str = PersonInfo.studentID;
            temp     = Encoding.Default.GetBytes(temp_str);
            Buffer.BlockCopy(temp, 0, user_data, 8, temp.Length);

            /* 姓名 */
            temp_str = PersonInfo.name;
            temp     = Encoding.GetEncoding("utf-8").GetBytes(temp_str);
            //temp = Encoding.Default.GetBytes(temp_str);
            Buffer.BlockCopy(temp, 0, user_data, 24, temp.Length);

            /* 权限 */
            DeviceManagement deviceManagement = new DeviceManagement();
            int count = deviceManagement.DeviceList.Count; /* 设备数量 */

            temp     = new byte[16];
            temp_str = PersonInfo.authority;
            string[] split_array = temp_str.Replace(" ", "").Split(',');
            for (int i = 0; i < split_array.Length; i++)
            {
                if (split_array[i] == "超级管理员")
                {
                    temp[15] |= (byte)(1 << 7);
                }
                else if (split_array[i] == "管理员")
                {
                    temp[15] |= (byte)(1 << 6);
                }
                else
                {
                    for (int j = 0; j < count; j++)
                    {
                        if (split_array[i] == deviceManagement.DeviceList[j].name)
                        {
                            Int32 id = (Int32)deviceManagement.DeviceList[j].ID;
                            temp[id / 8] |= (byte)(1 << (id % 8));
                        }
                    }
                }
            }
            Buffer.BlockCopy(temp, 0, user_data, 40, temp.Length);

            /* 是否有时间限制 */
            user_data[56] = (byte)PersonInfo.isLimitTime;

            /* 有效期 */
            user_data[57] = (byte)(year & 0xFF);
            user_data[58] = (byte)((year & 0xFF00) >> 8);
            user_data[59] = (byte)month;
            user_data[60] = (byte)day;
            user_data[61] = (byte)hour;
            user_data[62] = (byte)minute;
            user_data[63] = (byte)second;

            /* 指纹号 */
            for (int i = 0; i < 5; i++)
            {
                user_data[64 + i * 2] = (byte)((PersonInfo.eigenNum[i] & 0x00FF) >> 0);
                user_data[65 + i * 2] = (byte)((PersonInfo.eigenNum[i] & 0xFF00) >> 8);
            }

            /* 指纹特征值 */
            for (int i = 0; i < 5; i++)
            {
                temp = String_Byte.strToHexByte(PersonInfo.eigen[i]);
                Buffer.BlockCopy(temp, 0, user_data, 74 + i * 193, temp.Length);
            }

            /* crc */
            crc             = stm32_crc.block_crc_calc(user_data, 1, USER_PACK_SIZE - 4 - 16);
            user_data[1039] = (byte)((crc & 0x000000FF) >> 0);
            user_data[1040] = (byte)((crc & 0x0000FF00) >> 8);
            user_data[1041] = (byte)((crc & 0x00FF0000) >> 16);
            user_data[1042] = (byte)((crc & 0xFF000000) >> 24);

            /* 进出状态 */
            temp = new byte[16];
            Buffer.BlockCopy(temp, 0, user_data, 1043, temp.Length);

            Buffer.BlockCopy(user_data, 1, data, 0, data.Length);

            return(data);
        }
Example #28
0
 internal DeviceMonitorProxy()
 {
     _devManager = new DeviceManagement();
     _devManager.DeviceConnected    += this._devManager_DeviceConnected;
     _devManager.DeviceDisconnected += this._devManager_DeviceDisconnected;
 }
Example #29
0
        public static void Main(string[] args)
        {
            Console.WriteLine("============================ IBM WatsonIoTP Sample ============================");

            string orgID      = "";
            string deviceType = "";
            string deviceId   = "";
            string authType   = "";
            string authKey    = "";
            bool   isSync     = true;

            Console.WriteLine("Device Management Sample");

            Console.Write("Enter your org id :");
            orgID = Console.ReadLine();

            Console.Write("Enter your device type :");
            deviceType = Console.ReadLine();

            Console.Write("Enter your device id :");
            deviceId = Console.ReadLine();

            Console.Write("Enter your auth key :");
            authKey = Console.ReadLine();


            DeviceInfo simpleDeviceInfo = new DeviceInfo();

            simpleDeviceInfo.description         = "My device";
            simpleDeviceInfo.deviceClass         = "My device class";
            simpleDeviceInfo.manufacturer        = "My device manufacturer";
            simpleDeviceInfo.fwVersion           = "Device Firmware Version";
            simpleDeviceInfo.hwVersion           = "Device HW Version";
            simpleDeviceInfo.model               = "My device model";
            simpleDeviceInfo.serialNumber        = "12345";
            simpleDeviceInfo.descriptiveLocation = "My device location";

            DeviceManagement deviceClient = new DeviceManagement(orgID, deviceType, deviceId, authType, authKey, isSync);

            deviceClient.deviceInfo      = simpleDeviceInfo;
            deviceClient.mgmtCallback   += processMgmtResponse;
            deviceClient.actionCallback += (string reqestId, string action) => {
                Console.WriteLine("req Id:" + reqestId + "	Action:"+ action + " called");
                if (action == "reboot")
                {
                    deviceClient.sendResponse(reqestId, DeviceManagement.RESPONSECODE_ACCEPTED, "");

                    Thread.Sleep(2000);
                    deviceClient.disconnect();

                    Console.WriteLine("disconnected");
                    Thread.Sleep(5000);

                    Console.WriteLine("Re connected");
                    deviceClient.connect();

                    deviceClient.manage(4000, true, true);
                }
                if (action == "reset")
                {
                    deviceClient.sendResponse(reqestId, DeviceManagement.RESPONSECODE_FUNCTION_NOT_SUPPORTED, "");
                }
            };
            deviceClient.fwCallback += (string action, DeviceFirmware fw) => {
                if (action == "download")
                {
                    deviceClient.setState(DeviceManagement.UPDATESTATE_DOWNLOADING);
                    Console.WriteLine("Start downloading new Firmware from " + fw.uri);
                    Thread.Sleep(2000);
                    Console.WriteLine("completed Download");
                    deviceClient.setState(DeviceManagement.UPDATESTATE_DOWNLOADED);
                }
                if (action == "update")
                {
                    deviceClient.setUpdateState(DeviceManagement.UPDATESTATE_IN_PROGRESS);
                    Console.WriteLine("Start Updating new Firmware ");
                    Thread.Sleep(2000);
                    Console.WriteLine("Updated new Firmware ");
                    deviceClient.setUpdateState(DeviceManagement.UPDATESTATE_SUCCESS);
                }
            };
            deviceClient.connect();
            deviceClient.subscribeCommand("testcmd", "json", 2);
            deviceClient.commandCallback += processCommand;
            Console.WriteLine("Manage");
            deviceClient.manage(4000, true, true);
            Console.WriteLine("Set Location");
            deviceClient.setLocation(77.5667, 12.9667, 0, 10);

            //Console.Write("Press any key to exit . . . ");
            Console.ReadKey();
//			deviceClient.disconnect();
        }
Example #30
0
        public static void Main(string[] args)
        {
            Console.WriteLine("============================ IBM WatsonIoTP Sample ============================");

            string orgID      = "";
            string deviceType = "";
            string deviceId   = "";
            string authType   = "";
            string authKey    = "";
            bool   isSync     = true;

            Console.WriteLine("Device Management Sample");

            Console.Write("Enter your org id :");
            orgID = Console.ReadLine();

            Console.Write("Enter your device type :");
            deviceType = Console.ReadLine();

            Console.Write("Enter your device id :");
            deviceId = Console.ReadLine();

            Console.Write("Enter your auth key :");
            authKey = Console.ReadLine();



            DeviceInfo simpleDeviceInfo = new DeviceInfo();

            simpleDeviceInfo.description         = "My device";
            simpleDeviceInfo.deviceClass         = "My device class";
            simpleDeviceInfo.manufacturer        = "My device manufacturer";
            simpleDeviceInfo.fwVersion           = "Device Firmware Version";
            simpleDeviceInfo.hwVersion           = "Device HW Version";
            simpleDeviceInfo.model               = "My device model";
            simpleDeviceInfo.serialNumber        = "12345";
            simpleDeviceInfo.descriptiveLocation = "My device location";

            DeviceManagement deviceClient = new DeviceManagement(orgID, deviceType, deviceId, authType, authKey, isSync);

            deviceClient.deviceInfo    = simpleDeviceInfo;
            deviceClient.mgmtCallback += processMgmtResponse;
            deviceClient.connect();
            Console.WriteLine("Manage");
            deviceClient.manage(4000, true, true);
            Console.WriteLine("Manage With Meta");
            deviceClient.manage(4000, true, true, new{ Key = "" });
            Console.WriteLine("Add Error Code");
            deviceClient.addErrorCode(12);
            Console.WriteLine("Clear Error Code");
            deviceClient.clearErrorCode();
            Console.WriteLine("Add Log");
            deviceClient.addLog("test", "data", 1);
            Console.WriteLine("Clear Log");
            deviceClient.clearLog();
            Console.WriteLine("Set Location");
            deviceClient.setLocation(77.5667, 12.9667, 0, 10);
            Console.WriteLine("Unmanage");
            deviceClient.unmanage();
            Console.Write("Press any key to exit . . . ");
            Console.ReadKey();
            deviceClient.disconnect();
        }
Example #31
0
 public void ClientUpdateSkipped() => DeviceManagement.HideSetupDevice();
 public IDeviceManagement Build()
 {
     return(DeviceManagement.Create(Camera));
 }
Example #33
0
        public void connect(UInt16 vid, UInt16 pid, bool skip)
        {
            if (connected)
            {
                Log.Write(String.Format("USBInterface.connect() for already connected interface - vid{0}, pid={1}, skip={2}) begins\n", vid, pid, skip));
            }
            else
            {
                System.Guid Guid  = new System.Guid(GUID_STRING);
                Int32       index = 0;

                Log.Write(String.Format("USBInterface.connect() begins vid{0}, pid={1}, skip={2}) begins\n", vid, pid, skip));

                while (true)
                {
                    bool bUseThisDevice = true;

                    if (!myDeviceManagement.FindDeviceFromGuid(Guid, out devicePathName, ref index))
                    {
                        throw new System.IO.IOException(String.Format("Unable to locate a USB device with GUID {0}, vid={1}, pid={2}, skip={3}", Guid, vid, pid, skip));
                    }

                    Log.Write(String.Format("USBInterface.connect(): Considering USB Device {0}\n", devicePathName));

                    UInt16 foundVid, foundPid;

                    DeviceManagement.parsePath(devicePathName, out foundVid, out foundPid);

                    Log.Write(String.Format("USBInterface.connect(): checking VID/PID - foundVID={0} foundPID={1}\n", foundVid, foundPid));

                    if (vid != 0)
                    {
                        bool bVIDMatch = (foundVid == vid);
                        bool bPIDMatch = (foundPid == pid);

                        Log.Write(String.Format("USBInterface.connect(): initally bVIDMatch={0} bPIDMatch={1}\n", bVIDMatch, bPIDMatch));

                        // a pid of 0xffff matches guide cameras

                        if (pid == 0xffff)
                        {
                            bPIDMatch = (foundPid == 507) || (foundPid == 509) || (foundPid == 517);
                        }

                        bUseThisDevice = (bVIDMatch && bPIDMatch);

                        Log.Write(String.Format("USBInterface.connect(): pre skip check bVIDMatch={0} bPIDMatch={1} bUseThisDevice={2}\n", bVIDMatch, bPIDMatch, bUseThisDevice));

                        if (skip)
                        {
                            bUseThisDevice = !bUseThisDevice;
                        }

                        Log.Write(String.Format("USBInterface.connect(): post skip check bVIDMatch={0} bPIDMatch={1} bUseThisDevice={2}\n", bVIDMatch, bPIDMatch, bUseThisDevice));
                    }

                    if (bUseThisDevice)
                    {
                        // For reasons I don't undersand, we can get a device handle for a device thatis already open,
                        // even though we specify no sharing of the file when we open it.  So, in order to make sure
                        // that we don't open the same camera twice we create a mutex that has the same name as
                        // the device (execpt that we have to replace "\" with "/" because // mutex names cannot contain "\").
                        // If we find that the mutex already existed, we assume the device is already in use and keep looking.

                        String mutexName = devicePathName.Replace("\\", "/");
                        bool   createdNew;

                        m_mutex = new Mutex(true, mutexName, out createdNew);

                        Log.Write(String.Format("USBInterface.connect(): mutexName={0} createdNew={1}\n", mutexName, createdNew));

                        if (!createdNew)
                        {
                            Log.Write(String.Format("USBInterface.connect(): mutex was already in use - closing handle and continuing search\n"));
                        }
                        else
                        {
                            Log.Write(String.Format("USBInterface: attempting to get a handle for USB Device {0}\n", devicePathName));

                            if (FileIO.GetDeviceHandle(devicePathName, out deviceHandle))
                            {
                                Log.Write(String.Format("USBInterface.connect(): deviceHandle.IsInvalid={0}\n", deviceHandle.IsInvalid));
                                connected = true;
                                vid       = foundVid;
                                pid       = foundPid;
                                break;
                            }

                            Log.Write(String.Format("USBInterface.connect(): Unable to get a device handle for GUID {0} using path {1} - skipping", Guid, devicePathName));
                        }

                        m_mutex.Close();
                    }
                    else
                    {
                        Log.Write(String.Format("USBInterface.connect(): skipping USB Device {0} because of skip/vid/pid\n", devicePathName));
                    }
                }
            }
        }