This is the latest working repository used in our demo video for the Maxim to display temperature readings on Bluetooth

Dependencies:   USBDevice

hspguisourcev301/HspGuiSourceV301/HSPGui/NimitzHID.cs

Committer:
darienf
Date:
2021-04-10
Revision:
3:36de8b9e4b1a

File content as of revision 3:36de8b9e4b1a:

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;


namespace SimpleHID
{
    class NimitzHID
    {
        internal const byte COMMAND_SUCCEED = 0xEE;
        internal const byte COMMAND_FAILED = 0xFA;

        // private IntPtr deviceNotificationHandle;
        // private Boolean exclusiveAccess;
        private SafeFileHandle hidHandle;
        private String hidUsage;
        private Boolean myDeviceDetected;
        private String myDevicePathName;
        private SafeFileHandle readHandle;
        private SafeFileHandle writeHandle;

        // private Debugging MyDebugging = new Debugging(); //  For viewing results of API calls via Debug.Write.
        private Guid hidGuid;
        private IntPtr deviceNotificationHandle = System.IntPtr.Zero;
        private HID myHID;

        //internal FrmMain FrmMy;

        ///  <summary>
        ///  Define a class of delegates that point to the Hid.ReportIn.Read function.
        ///  The delegate has the same parameters as Hid.ReportIn.Read.
        ///  Used for asynchronous reads from the device.       
        ///  </summary>

        private delegate void ReadInputReportDelegate(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, ref Boolean myDeviceDetected, ref Byte[] readBuffer, ref Boolean success);

        //  This delegate has the same parameters as AccessForm.
        //  Used in accessing the application's form from a different thread.

        private delegate void MarshalToForm(String action, String textToAdd);
        ///  <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>

        internal Boolean OpenNimitzH()
        {
            Boolean deviceFound = false;
            String[] devicePathName = new String[128];
            Guid hidGuid = Guid.Empty;
            Int32 memberIndex = 0;
            Int32 myProductID = 0x1365;
            Int32 myVendorID = 0x0B6A;
            Boolean success = false;

            myDeviceDetected = false;

            myHID.findHIDs();

            //  ***
            //  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.
                    //  ***
                    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))
                            {
                                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.
                            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.
                //  Learn the capabilities of the device.
                MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);

                //  Find out if the device is a system mouse or keyboard.
                hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);

                //  Get handles to use in requesting Input and Output reports.
                readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);
                writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                //  Flush any waiting reports in the input buffer. (optional)
                MyHid.FlushQueue(readHandle);
            }
            return myDeviceDetected;
        }

        internal void CloseNimitzH()
        {
            if (!(hidHandle == null))
            {
                if (!(hidHandle.IsInvalid))
                {
                    hidHandle.Close();
                }
            }

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

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

        // This function only checks the status variable and does not actively check
        // if the NimitzH is still present.  This function
        // only checks the variable to avoid any timeout delays.
        internal Boolean NimitzHPresent()
        {
            if (myDeviceDetected)
                return true;
            else
                return false;
        }

        //////////////////////////////////////////////////////////////////////
        // Functions that can be called once NimitzH is opened
        //////////////////////////////////////////////////////////////////////

        // This function calls the NimitzH Read Revision command.
        // This is done by sending 0xC2, and then receiving 1 byte major rev, then 1byte minor Rev, and then 0xD2
        // This function returns firmware MAJORVERSION in upper word and MINORVERSION in lower word
        // This function returns -1 if an error occurs

        internal int GetFirmwareVersion()
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[2];

            dataOut[0] = 0x01;//number of bytes to send
            dataOut[1] = 0x02;//firmware command

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return -1;

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return (inputBuffer[3] << 16) + inputBuffer[4];
            else
                return -1;

        }
        internal Boolean TestSendPacket(byte[] sendData, ref byte[] readData)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            byte numData = (byte)sendData.Length;
            Byte[] dataOut = new Byte[3 + numData];

            if ((numData > 62) || (numData < 0))
                return false;			// Max packet size is 62 bytes

            dataOut[0] = (byte)(0x02 + numData);//number of bytes to send (include command and data bytes)
            dataOut[1] = 0x01;//command byte
            dataOut[2] = (byte)(numData);//number of data bytes

            for (int i = 0; i < numData; i++)
                dataOut[i + 3] = sendData[i];

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            for (int i = 0; i < numData; i++)
                readData[i] = inputBuffer[i + 3];

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }
        /****************I2CPacketWrite****************/
        /* Description: Generates the correct sequence of events on the I2C bus for a packet write (up to 60 data bytes) 
        /* Information: New Implementation for packet writes ( SHOULD BE USED in most ALLL Writes/Read of and I2C Device )!!
        /* Paramters: slaveAddress = slave address of DUT (R/W# is set in firmware), numBytes = Number of data bytes to write (1 to 60), 
        /*	memoryaddress = Desired memory location, databuffer = pointer to the data to write on the buss*/
        internal Boolean I2CWritePacket(Byte slaveAddress, Byte memoryaddress, Byte numBytes, Byte[] databuffer)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[64];

            if ((numBytes > 59) || (numBytes < 0))
                return false;			// Max packet size is 60 bytes

            dataOut[0] = (byte)(numBytes + 4);
            dataOut[1] = 0x20;
            dataOut[2] = slaveAddress;
            dataOut[3] = memoryaddress;
            dataOut[4] = numBytes;

            for (int i = 0; i < numBytes; i++)
                dataOut[i + 5] = databuffer[i];

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }

        /****************I2CPacketRead****************/
        /* Description: Generates the correct sequence of events on the I2C bus for a packet read (up to 60 data bytes) 
        /* Information: New Implementation for packet reads ( SHOULD BE USED in most ALLL Writes/Read of and I2C Device )!!
        /* Paramters: slaveAddress = slave address of DUT (R/W# is set in firmware), numBytes = Number of data bytes to write (1 to 60), 
        /*	memoryaddress = Desired memory location, databuffer = pointer to the data read should be saved*/
        internal Boolean I2CReadPacket(Byte slaveAddress, Byte memoryaddress, Byte numBytes, ref Byte[] databuffer)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[5];

            if ((numBytes > 62) || (numBytes < 1))
                return false;			// Max packet size is 62 bytes

            dataOut[0] = 0x04;
            dataOut[1] = 0x21;
            dataOut[2] = (byte)(slaveAddress | 0x01);
            dataOut[3] = memoryaddress;
            dataOut[4] = numBytes;

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            for (int i = 0; i < numBytes; i++)
                databuffer[i] = inputBuffer[i + 3];

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }

        internal Boolean SPIReadPacket(Byte address, Byte numBytes, ref Byte[] data)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[4];

            if ((numBytes > 62) || (numBytes < 1))
                return false;				// Max packet size is 62 bytes

            dataOut[0] = 3;
            dataOut[1] = 0x41;
            dataOut[2] = address;
            dataOut[3] = numBytes;

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            for (int i = 0; i < numBytes; i++)
                data[i] = inputBuffer[i + 3];

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }

        internal Boolean SPIStartSampling(Byte address, Byte numBytes, uint numSamples, ref Byte[] data)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[6];

            if ((numBytes > 62) || (numBytes < 1))
                return false;				// Max packet size is 62 bytes

            dataOut[0] = 5;
            dataOut[1] = 0x45;
            dataOut[2] = address;
            dataOut[3] = numBytes;
            dataOut[4] = (byte)(numSamples >> 8);
            dataOut[5] = (byte)numSamples;

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            for (int i = 0; i < numBytes; i++)
                data[i] = inputBuffer[i + 3];

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }

        internal bool SPIWritePacket(Byte address, Byte numBytes, Byte[] data)
        {
            Boolean success = false;
            Byte[] inputBuffer = null;
            Byte[] dataOut = new Byte[64];

            if ((numBytes > 60) || (numBytes < 1))
                return false;				// Max packet size is 60 bytes

            dataOut[0] = (byte)(numBytes + 3);
            dataOut[1] = 0x40;
            dataOut[2] = address;
            dataOut[3] = numBytes;

            for (int i = 0; i < numBytes; i++)
                dataOut[4 + i] = data[i];

            success = InputOutputReports(dataOut, ref inputBuffer);

            if (!success)
                return false;

            if (inputBuffer[2] == COMMAND_SUCCEED)
                return true;
            else
                return false;
        }
        ///  <summary>
        ///  Sends an Output report, then retrieves an Input report.
        ///  Assumes report ID = 0 for both reports.
        ///  </summary>

        private Boolean InputOutputReports(Byte[] data, ref Byte[] inputReportBuffer)
        {
            // Byte[] inputReportBuffer = null;
            Byte[] outputReportBuffer = null;
            Boolean success = false;

            success = false;

            //  Don't attempt to exchange reports if valid handles aren't available
            //  (as for a mouse or keyboard under Windows 2000/XP.)

            if (!readHandle.IsInvalid && !writeHandle.IsInvalid)
            {
                //  Don't attempt to send an Output report if the HID has no Output report.
                if (MyHid.Capabilities.OutputReportByteLength > 0)
                {
                    //  Set the size of the Output report buffer.   

                    outputReportBuffer = new Byte[MyHid.Capabilities.OutputReportByteLength];

                    outputReportBuffer[0] = 0;      // Ensure Report ID = 0


                    for (int i = 0; i < data.Length; i++)
                        outputReportBuffer[i + 1] = data[i];

                    //  Use WriteFile to send the report.
                    //  If the HID has an interrupt OUT endpoint, WriteFile uses an 
                    //  interrupt transfer to send the report. 
                    //  If not, WriteFile uses a control transfer.

                    Hid.OutputReportViaInterruptTransfer myOutputReport = new Hid.OutputReportViaInterruptTransfer();
                    success = myOutputReport.Write(outputReportBuffer, writeHandle);
                }

                if (!success)
                    return false;

                //  Read an Input report
                success = false;

                //  Don't attempt to send an Input report if the HID has no Input report.
                //  (The HID spec requires all HIDs to have an interrupt IN endpoint,
                //  which suggests that all HIDs must support Input reports.)

                if (MyHid.Capabilities.InputReportByteLength > 0)
                {
                    //  Set the size of the Input report buffer. 
                    inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength];

                    Hid.InputReportViaInterruptTransfer myInputReport = new Hid.InputReportViaInterruptTransfer();
                    myInputReport.Read(hidHandle, readHandle, writeHandle, ref myDeviceDetected, ref inputReportBuffer, ref success);

                }

            }
            return success;
        }
    }
}