Example #1
0
        /// <summary>
        /// Helper method for retrieving type lib attributes for the given type lib
        /// </summary>
        internal static void GetTypeLibAttrForTypeLib(ref ITypeLib typeLib, out TYPELIBATTR typeLibAttr)
        {
            typeLib.GetLibAttr(out IntPtr pAttrs);

            // GetLibAttr should never return null, this is just to be safe
            if (pAttrs == IntPtr.Zero)
            {
                throw new COMException(
                          ResourceUtilities.GetResourceString("ResolveComReference.CannotGetTypeLibAttrForTypeLib"));
            }

            try
            {
                typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(TYPELIBATTR));
            }
            finally
            {
                typeLib.ReleaseTLibAttr(pAttrs);
            }
        }
Example #2
0
        /// <summary>
        /// Helper method for retrieving type attributes for a given type info
        /// </summary>
        /// <param name="typeInfo"></param>
        /// <param name="typeAttr"></param>
        /// <returns></returns>
        internal static void GetTypeAttrForTypeInfo(ITypeInfo typeInfo, out TYPEATTR typeAttr)
        {
            IntPtr pAttrs = IntPtr.Zero;

            typeInfo.GetTypeAttr(out pAttrs);

            // GetTypeAttr should never return null, this is just to be safe
            if (pAttrs == IntPtr.Zero)
            {
                throw new COMException(
                          ResourceUtilities.FormatResourceString("ResolveComReference.CannotRetrieveTypeInformation"));
            }

            try
            {
                typeAttr = (TYPEATTR)Marshal.PtrToStructure(pAttrs, typeof(TYPEATTR));
            }
            finally
            {
                typeInfo.ReleaseTypeAttr(pAttrs);
            }
        }
Example #3
0
        internal ComMethodDesc(ITypeInfo typeInfo, FUNCDESC funcDesc)
            : this(funcDesc.memid)
        {
            _hasTypeInfo = true;
            InvokeKind   = funcDesc.invkind;

            ELEMDESC returnValue = funcDesc.elemdescFunc;

            _returnValue = new ComParamDesc(ref returnValue);

            int cNames;

            string[] rgNames = new string[1 + funcDesc.cParams];
            typeInfo.GetNames(_memid, rgNames, rgNames.Length, out cNames);
            if (IsPropertyPut)
            {
                rgNames[rgNames.Length - 1] = "value";
                cNames++;
            }
            Debug.Assert(cNames == rgNames.Length);
            _name = rgNames[0];

            _parameters = new ComParamDesc[funcDesc.cParams];

            int offset = 0;

            for (int i = 0; i < funcDesc.cParams; i++)
            {
                ELEMDESC elemDesc = (ELEMDESC)Marshal.PtrToStructure(
                    new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + offset),
                    typeof(ELEMDESC));

                _parameters[i] = new ComParamDesc(ref elemDesc, rgNames[1 + i]);

                offset += Marshal.SizeOf(typeof(ELEMDESC));
            }
        }
Example #4
0
        public bool GetAllCameraMetadataTags(
            IntPtr cameraMetadataHandle, List <CameraMetadataTag> resultList)
        {
            IntPtr ndkMetadataHandle = IntPtr.Zero;

            if (InstantPreviewManager.IsProvidingPlatform)
            {
                InstantPreviewManager.LogLimitedSupportMessage("access camera metadata tags");
                return(false);
            }

            ExternApi.ArImageMetadata_getNdkCameraMetadata(m_NativeSession.SessionHandle,
                                                           cameraMetadataHandle, ref ndkMetadataHandle);

            IntPtr          tagsHandle = IntPtr.Zero;
            int             tagsCount  = 0;
            NdkCameraStatus status     = ExternApi.ACameraMetadata_getAllTags(
                ndkMetadataHandle, ref tagsCount, ref tagsHandle);

            if (status != NdkCameraStatus.Ok)
            {
                ARDebug.LogErrorFormat(
                    "ACameraMetadata_getAllTags error with native camera error code: {0}",
                    status);
                return(false);
            }

            for (int i = 0; i < tagsCount; i++)
            {
                resultList.Add((CameraMetadataTag)Marshal.PtrToStructure(
                                   MarshalingHelper.GetPtrToUnmanagedArrayElement <int>(tagsHandle, i),
                                   typeof(int)));
            }

            return(true);
        }
        public static void SetCommandText(IntPtr pCmdTextInt, string text)
        {
            if (text != null)
            {
                OLECMDTEXT olecmdtext = (OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(OLECMDTEXT));
                if ((olecmdtext.cmdtextf & (uint)OLECMDTEXTF.OLECMDTEXTF_NAME) == 0)
                {
                    return;
                }

                char[] source       = text.ToCharArray();
                IntPtr bufferOffset = Marshal.OffsetOf(typeof(OLECMDTEXT), "rgwz");
                IntPtr lengthOffset = Marshal.OffsetOf(typeof(OLECMDTEXT), "cwActual");
                int    length       = Math.Min(((int)olecmdtext.cwBuf) - 1, source.Length);

                // copy the new text
                long bufferAddress = (long)pCmdTextInt + (long)bufferOffset;
                Marshal.Copy(source, 0, (IntPtr)bufferAddress, length);
                // null terminator
                Marshal.WriteInt16(pCmdTextInt, (int)bufferOffset + length * 2, 0);
                // length including null terminator
                Marshal.WriteInt32(pCmdTextInt, (int)lengthOffset, length + 1);
            }
        }
Example #6
0
        /// <summary>
        /// For a given type, analyze all the functions implemented by it. That means all the argument and return types.
        /// </summary>
        /// <param name="typeInfo"></param>
        /// <param name="typeAttributes"></param>
        private void ScanDefinedFunctions(ITypeInfo typeInfo, TYPEATTR typeAttributes)
        {
            for (int definedFuncIndex = 0; definedFuncIndex < typeAttributes.cFuncs; definedFuncIndex++)
            {
                IntPtr funcDescHandleToRelease = IntPtr.Zero;

                try
                {
                    FUNCDESC funcDesc;
                    ComReference.GetFuncDescForDescIndex(typeInfo, definedFuncIndex, out funcDesc, out funcDescHandleToRelease);

                    int offset = 0;

                    // Analyze the argument types
                    for (int paramIndex = 0; paramIndex < funcDesc.cParams; paramIndex++)
                    {
                        ELEMDESC elemDesc = (ELEMDESC)Marshal.PtrToStructure(
                            new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + offset), typeof(ELEMDESC));

                        AnalyzeElement(typeInfo, elemDesc);

                        offset += Marshal.SizeOf <ELEMDESC>();
                    }

                    // Analyze the return value type
                    AnalyzeElement(typeInfo, funcDesc.elemdescFunc);
                }
                finally
                {
                    if (funcDescHandleToRelease != IntPtr.Zero)
                    {
                        typeInfo.ReleaseFuncDesc(funcDescHandleToRelease);
                    }
                }
            }
        }
Example #7
0
        public bool TryGetValues(IntPtr cameraMetadataHandle,
                                 CameraMetadataTag tag, List <CameraMetadataValue> resultList)
        {
            IntPtr ndkMetadataHandle = IntPtr.Zero;

            ExternApi.ArImageMetadata_getNdkCameraMetadata(m_NativeSession.SessionHandle,
                                                           cameraMetadataHandle, ref ndkMetadataHandle);

            resultList.Clear();
            NdkCameraMetadata entry  = new NdkCameraMetadata();
            NdkCameraStatus   status = ExternApi.ACameraMetadata_getConstEntry(ndkMetadataHandle, tag, ref entry);

            if (status != NdkCameraStatus.Ok)
            {
                ARDebug.LogErrorFormat("ACameraMetadata_getConstEntry error with native camera error code: {0}",
                                       status);
                return(false);
            }

            for (int i = 0; i < entry.Count; i++)
            {
                switch (entry.Type)
                {
                case NdkCameraMetadataType.Byte:
                    sbyte byteValue = (sbyte)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <sbyte>(entry.Value, i),
                        typeof(sbyte));
                    resultList.Add(new CameraMetadataValue(byteValue));
                    break;

                case NdkCameraMetadataType.Int32:
                    int intValue = (int)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <int>(entry.Value, i),
                        typeof(int));
                    resultList.Add(new CameraMetadataValue(intValue));
                    break;

                case NdkCameraMetadataType.Float:
                    float floatValue = (float)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <float>(entry.Value, i),
                        typeof(float));
                    resultList.Add(new CameraMetadataValue(floatValue));
                    break;

                case NdkCameraMetadataType.Int64:
                    long longValue = (long)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <long>(entry.Value, i),
                        typeof(long));
                    resultList.Add(new CameraMetadataValue(longValue));
                    break;

                case NdkCameraMetadataType.Double:
                    double doubleValue = (double)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <double>(entry.Value, i),
                        typeof(double));
                    resultList.Add(new CameraMetadataValue(doubleValue));
                    break;

                case NdkCameraMetadataType.Rational:
                    CameraMetadataRational rationalValue = (CameraMetadataRational)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <CameraMetadataRational>(entry.Value, i),
                        typeof(CameraMetadataRational));
                    resultList.Add(new CameraMetadataValue(rationalValue));
                    break;

                default:
                    return(false);
                }
            }

            return(true);
        }
Example #8
0
        /// <summary>Opens the device for sending direct commands</summary>
        /// <param name="devicePath">Device path</param>
        public Device(string devicePath)
        {
            PlatformId  = DetectOS.GetRealPlatformID();
            Timeout     = 15;
            Error       = false;
            IsRemovable = false;

            if (devicePath.StartsWith("dic://", StringComparison.OrdinalIgnoreCase) ||
                devicePath.StartsWith("aaru://", StringComparison.OrdinalIgnoreCase))
            {
                devicePath =
                    devicePath.Substring(devicePath.StartsWith("dic://", StringComparison.OrdinalIgnoreCase) ? 6 : 7);

                string[] pieces = devicePath.Split('/');
                string   host   = pieces[0];
                devicePath = devicePath.Substring(host.Length);

                _remote = new Remote.Remote(host);

                Error     = !_remote.Open(devicePath, out int errno);
                LastError = errno;
            }
            else
            {
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                {
                    FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
                                                   FileShare.Read | FileShare.Write, IntPtr.Zero,
                                                   FileMode.OpenExisting, FileAttributes.Normal, IntPtr.Zero);

                    if (((SafeFileHandle)FileHandle).IsInvalid)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.Linux:
                {
                    FileHandle =
                        Linux.Extern.open(devicePath,
                                          FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);

                    if ((int)FileHandle < 0)
                    {
                        LastError = Marshal.GetLastWin32Error();

                        if (LastError == 13 ||
                            LastError == 30)    // EACCES or EROFS
                        {
                            FileHandle = Linux.Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);

                            if ((int)FileHandle < 0)
                            {
                                Error     = true;
                                LastError = Marshal.GetLastWin32Error();
                            }
                        }
                        else
                        {
                            Error = true;
                        }

                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.FreeBSD:
                {
                    FileHandle = FreeBSD.Extern.cam_open_device(devicePath, FreeBSD.FileFlags.ReadWrite);

                    if (((IntPtr)FileHandle).ToInt64() == 0)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    var camDevice = (CamDevice)Marshal.PtrToStructure((IntPtr)FileHandle, typeof(CamDevice));

                    if (StringHandlers.CToString(camDevice.SimName) == "ata")
                    {
                        throw new
                              DeviceException("Parallel ATA devices are not supported on FreeBSD due to upstream bug #224250.");
                    }

                    break;
                }

                default: throw new DeviceException($"Platform {PlatformId} not yet supported.");
                }
            }

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            Type     = DeviceType.Unknown;
            ScsiType = PeripheralDeviceTypes.UnknownDevice;

            byte[] ataBuf;
            byte[] inqBuf = null;

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            bool scsiSense = true;

            if (_remote is null)
            {
                // Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                    var query = new StoragePropertyQuery();
                    query.PropertyId           = StoragePropertyId.Device;
                    query.QueryType            = StorageQueryType.Standard;
                    query.AdditionalParameters = new byte[1];

                    IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
                    byte[] descriptorB   = new byte[1000];

                    uint returned = 0;
                    int  error    = 0;

                    bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)FileHandle,
                                                                        WindowsIoctl.IoctlStorageQueryProperty,
                                                                        ref query, (uint)Marshal.SizeOf(query),
                                                                        descriptorPtr, 1000, ref returned,
                                                                        IntPtr.Zero);

                    if (hasError)
                    {
                        error = Marshal.GetLastWin32Error();
                    }

                    Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                    if (!hasError &&
                        error == 0)
                    {
                        var descriptor = new StorageDeviceDescriptor
                        {
                            Version               = BitConverter.ToUInt32(descriptorB, 0),
                            Size                  = BitConverter.ToUInt32(descriptorB, 4),
                            DeviceType            = descriptorB[8],
                            DeviceTypeModifier    = descriptorB[9],
                            RemovableMedia        = descriptorB[10] > 0,
                            CommandQueueing       = descriptorB[11] > 0,
                            VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                            ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                            ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                            SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                            BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                            RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                        };

                        descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];

                        Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0,
                                   descriptor.RawPropertiesLength);

                        switch (descriptor.BusType)
                        {
                        case StorageBusType.SCSI:
                        case StorageBusType.SSA:
                        case StorageBusType.Fibre:
                        case StorageBusType.iSCSI:
                        case StorageBusType.SAS:
                            Type = DeviceType.SCSI;

                            break;

                        case StorageBusType.FireWire:
                            IsFireWire = true;
                            Type       = DeviceType.SCSI;

                            break;

                        case StorageBusType.USB:
                            IsUsb = true;
                            Type  = DeviceType.SCSI;

                            break;

                        case StorageBusType.ATAPI:
                            Type = DeviceType.ATAPI;

                            break;

                        case StorageBusType.ATA:
                        case StorageBusType.SATA:
                            Type = DeviceType.ATA;

                            break;

                        case StorageBusType.MultiMediaCard:
                            Type = DeviceType.MMC;

                            break;

                        case StorageBusType.SecureDigital:
                            Type = DeviceType.SecureDigital;

                            break;

                        case StorageBusType.NVMe:
                            Type = DeviceType.NVMe;

                            break;
                        }

                        switch (Type)
                        {
                        case DeviceType.SCSI:
                        case DeviceType.ATAPI:
                            scsiSense = ScsiInquiry(out inqBuf, out _);

                            break;

                        case DeviceType.ATA:
                            bool atapiSense = AtapiIdentify(out ataBuf, out _);

                            if (!atapiSense)
                            {
                                Type = DeviceType.ATAPI;
                                Identify.IdentifyDevice?ataid = Identify.Decode(ataBuf);

                                if (ataid.HasValue)
                                {
                                    scsiSense = ScsiInquiry(out inqBuf, out _);
                                }
                            }
                            else
                            {
                                Manufacturer = "ATA";
                            }

                            break;
                        }
                    }

                    Marshal.FreeHGlobal(descriptorPtr);

                    if (Windows.Command.IsSdhci((SafeFileHandle)FileHandle))
                    {
                        byte[] sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCsd,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out bool sense);

                        if (!sense)
                        {
                            _cachedCsd = new byte[16];
                            Array.Copy(sdBuffer, 0, _cachedCsd, 0, 16);
                        }

                        sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCid,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedCid = new byte[16];
                            Array.Copy(sdBuffer, 0, _cachedCid, 0, 16);
                        }

                        sdBuffer = new byte[8];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   (MmcCommands)SecureDigitalCommands.SendScr,
                                                                   false, true,
                                                                   MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 |
                                                                   MmcFlags.CommandAdtc, 0, 8, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedScr = new byte[8];
                            Array.Copy(sdBuffer, 0, _cachedScr, 0, 8);
                        }

                        sdBuffer = new byte[4];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   _cachedScr != null
                                                                           ? (MmcCommands)SecureDigitalCommands.
                                                                   SendOperatingCondition
                                                                           : MmcCommands.SendOpCond, false, true,
                                                                   MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
                                                                   MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedScr = new byte[4];
                            Array.Copy(sdBuffer, 0, _cachedScr, 0, 4);
                        }
                    }

                    break;

                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sg", StringComparison.Ordinal))
                    {
                        scsiSense = ScsiInquiry(out inqBuf, out _);
                    }

                    // MultiMediaCard and SecureDigital go here
                    else if (devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (File.Exists("/sys/block/" + devPath + "/device/csd"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/csd", out _cachedCsd);

                            if (len == 0)
                            {
                                _cachedCsd = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/cid"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/cid", out _cachedCid);

                            if (len == 0)
                            {
                                _cachedCid = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/scr"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/scr", out _cachedScr);

                            if (len == 0)
                            {
                                _cachedScr = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/ocr"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/ocr", out _cachedOcr);

                            if (len == 0)
                            {
                                _cachedOcr = null;
                            }
                        }
                    }

                    break;

                default:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;
                }
            }
            else
            {
                Type = _remote.GetDeviceType();

                switch (Type)
                {
                case DeviceType.ATAPI:
                case DeviceType.SCSI:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;

                case DeviceType.SecureDigital:
                case DeviceType.MMC:
                    if (!_remote.GetSdhciRegisters(out _cachedCsd, out _cachedCid, out _cachedOcr, out _cachedScr))
                    {
                        Type     = DeviceType.SCSI;
                        ScsiType = PeripheralDeviceTypes.DirectAccess;
                    }

                    break;
                }
            }

            #region SecureDigital / MultiMediaCard
            if (_cachedCid != null)
            {
                ScsiType    = PeripheralDeviceTypes.DirectAccess;
                IsRemovable = false;

                if (_cachedScr != null)
                {
                    Type = DeviceType.SecureDigital;
                    CID decoded = Decoders.SecureDigital.Decoders.DecodeCID(_cachedCid);
                    Manufacturer = VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }
                else
                {
                    Type = DeviceType.MMC;
                    Decoders.MMC.CID decoded = Decoders.MMC.Decoders.DecodeCID(_cachedCid);
                    Manufacturer = Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }

                return;
            }
            #endregion SecureDigital / MultiMediaCard

            #region USB
            if (_remote is null)
            {
                switch (PlatformId)
                {
                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (Directory.Exists("/sys/block/" + devPath))
                        {
                            string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);

                            if (!string.IsNullOrEmpty(resolvedLink))
                            {
                                resolvedLink = "/sys" + resolvedLink.Substring(2);

                                while (resolvedLink.Contains("usb"))
                                {
                                    resolvedLink = Path.GetDirectoryName(resolvedLink);

                                    if (!File.Exists(resolvedLink + "/descriptors") ||
                                        !File.Exists(resolvedLink + "/idProduct") ||
                                        !File.Exists(resolvedLink + "/idVendor"))
                                    {
                                        continue;
                                    }

                                    var usbFs = new FileStream(resolvedLink + "/descriptors",
                                                               System.IO.FileMode.Open, System.IO.FileAccess.Read);

                                    byte[] usbBuf   = new byte[65536];
                                    int    usbCount = usbFs.Read(usbBuf, 0, 65536);
                                    UsbDescriptors = new byte[usbCount];
                                    Array.Copy(usbBuf, 0, UsbDescriptors, 0, usbCount);
                                    usbFs.Close();

                                    var    usbSr   = new StreamReader(resolvedLink + "/idProduct");
                                    string usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out _usbProduct);

                                    usbSr.Close();

                                    usbSr   = new StreamReader(resolvedLink + "/idVendor");
                                    usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out _usbVendor);

                                    usbSr.Close();

                                    if (File.Exists(resolvedLink + "/manufacturer"))
                                    {
                                        usbSr = new StreamReader(resolvedLink + "/manufacturer");
                                        UsbManufacturerString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/product"))
                                    {
                                        usbSr            = new StreamReader(resolvedLink + "/product");
                                        UsbProductString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/serial"))
                                    {
                                        usbSr           = new StreamReader(resolvedLink + "/serial");
                                        UsbSerialString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    IsUsb = true;

                                    break;
                                }
                            }
                        }
                    }

                    break;

                case PlatformID.Win32NT:
                    Usb.UsbDevice usbDevice = null;

                    // I have to search for USB disks, floppies and CD-ROMs as separate device types
                    foreach (string devGuid in new[]
                    {
                        Usb.GuidDevinterfaceFloppy, Usb.GuidDevinterfaceCdrom, Usb.GuidDevinterfaceDisk,
                        Usb.GuidDevinterfaceTape
                    })
                    {
                        usbDevice = Usb.FindDrivePath(devicePath, devGuid);

                        if (usbDevice != null)
                        {
                            break;
                        }
                    }

                    if (usbDevice != null)
                    {
                        UsbDescriptors        = usbDevice.BinaryDescriptors;
                        _usbVendor            = (ushort)usbDevice.DeviceDescriptor.idVendor;
                        _usbProduct           = (ushort)usbDevice.DeviceDescriptor.idProduct;
                        UsbManufacturerString = usbDevice.Manufacturer;
                        UsbProductString      = usbDevice.Product;

                        UsbSerialString =
                            usbDevice.
                            SerialNumber;         // This is incorrect filled by Windows with SCSI/ATA serial number
                    }

                    break;

                default:
                    IsUsb = false;

                    break;
                }
            }
            else
            {
                if (_remote.GetUsbData(out byte[] remoteUsbDescriptors, out ushort remoteUsbVendor,
                                       out ushort remoteUsbProduct, out string remoteUsbManufacturer,
                                       out string remoteUsbProductString, out string remoteUsbSerial))
                {
                    IsUsb                 = true;
                    UsbDescriptors        = remoteUsbDescriptors;
                    _usbVendor            = remoteUsbVendor;
                    _usbProduct           = remoteUsbProduct;
                    UsbManufacturerString = remoteUsbManufacturer;
                    UsbProductString      = remoteUsbProductString;
                    UsbSerialString       = remoteUsbSerial;
                }
            }
            #endregion USB

            #region FireWire
            if (!(_remote is null))
            {
                if (_remote.GetFireWireData(out _firewireVendor, out _firewireModel, out _firewireGuid,
                                            out string remoteFireWireVendorName, out string remoteFireWireModelName))
                {
                    IsFireWire         = true;
                    FireWireVendorName = remoteFireWireVendorName;
                    FireWireModelName  = remoteFireWireModelName;
                }
            }
Example #9
0
        public bool TryGetValues(IntPtr cameraMetadataHandle,
                                 CameraMetadataTag tag, List <CameraMetadataValue> resultList)
        {
            resultList.Clear();
            uint             utag   = (uint)tag;
            ArCameraMetadata entry  = new ArCameraMetadata();
            ApiArStatus      status =
                ExternApi.ArImageMetadata_getConstEntry(_nativeSession.SessionHandle,
                                                        cameraMetadataHandle, utag,
                                                        ref entry);

            if (status != ApiArStatus.Success)
            {
                ARDebug.LogErrorFormat(
                    "ArImageMetadata_getConstEntry error with native camera error code: {0}",
                    status);
                return(false);
            }

            if (entry.Count > _maximumTagCountForWarning && !_warningTags.Contains((int)tag))
            {
                Debug.LogWarningFormat(
                    "TryGetValues for tag {0} has {1} values. Accessing tags with a large " +
                    "number of values may impede performance.", tag, entry.Count);
                _warningTags.Add((int)tag);
            }

            for (int i = 0; i < entry.Count; i++)
            {
                switch (entry.Type)
                {
                case ArCameraMetadataType.Byte:
                    sbyte byteValue = (sbyte)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <sbyte>(entry.Value, i),
                        typeof(sbyte));
                    resultList.Add(new CameraMetadataValue(byteValue));
                    break;

                case ArCameraMetadataType.Int32:
                    int intValue = (int)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <int>(entry.Value, i),
                        typeof(int));
                    resultList.Add(new CameraMetadataValue(intValue));
                    break;

                case ArCameraMetadataType.Float:
                    float floatValue = (float)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <float>(entry.Value, i),
                        typeof(float));
                    resultList.Add(new CameraMetadataValue(floatValue));
                    break;

                case ArCameraMetadataType.Int64:
                    long longValue = (long)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <long>(entry.Value, i),
                        typeof(long));
                    resultList.Add(new CameraMetadataValue(longValue));
                    break;

                case ArCameraMetadataType.Double:
                    double doubleValue = (double)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <double>(entry.Value, i),
                        typeof(double));
                    resultList.Add(new CameraMetadataValue(doubleValue));
                    break;

                case ArCameraMetadataType.Rational:
                    CameraMetadataRational rationalValue =
                        (CameraMetadataRational)Marshal.PtrToStructure(
                            MarshalingHelper
                            .GetPtrToUnmanagedArrayElement <CameraMetadataRational>(
                                entry.Value, i),
                            typeof(CameraMetadataRational));
                    resultList.Add(new CameraMetadataValue(rationalValue));
                    break;

                default:
                    return(false);
                }
            }

            return(true);
        }
Example #10
0
        internal static DeviceInfo[] GetList()
        {
            string[]          passDevices = Directory.GetFiles("/dev/", "pass*", SearchOption.TopDirectoryOnly);
            List <DeviceInfo> listDevices = new List <DeviceInfo>();

            foreach (string passDevice in passDevices)
            {
                var    deviceInfo = new DeviceInfo();
                IntPtr dev        = cam_open_device(passDevice, FileFlags.ReadWrite);
                var    camDevice  = (CamDevice)Marshal.PtrToStructure(dev, typeof(CamDevice));

                IntPtr ccbPtr = cam_getccb(dev);

                if (ccbPtr.ToInt64() == 0)
                {
                    continue;
                }

                var cgd = (CcbGetdev)Marshal.PtrToStructure(ccbPtr, typeof(CcbGetdev));

                cgd.ccb_h.func_code = XptOpcode.XptGdevType;

                Marshal.StructureToPtr(cgd, ccbPtr, false);

                int error = cam_send_ccb(dev, ccbPtr);

                if (error < 0)
                {
                    cam_freeccb(ccbPtr);

                    continue;
                }

                cgd = (CcbGetdev)Marshal.PtrToStructure(ccbPtr, typeof(CcbGetdev));

                cam_freeccb(ccbPtr);
                cam_close_device(dev);

                string simName = StringHandlers.CToString(camDevice.SimName);
                deviceInfo.Path = passDevice;
                byte[] serialNumber = new byte[camDevice.SerialNumLen];
                Array.Copy(camDevice.SerialNum, 0, serialNumber, 0, serialNumber.Length);
                deviceInfo.Serial = StringHandlers.CToString(serialNumber);

                switch (cgd.protocol)
                {
                case CamProto.ProtoAta:
                case CamProto.ProtoAtapi:
                case CamProto.ProtoSatapm:
                {
                    // Little-endian FreeBSD gives it resorted
                    // Big-endian FreeBSD, no idea
                    byte[] atadTneid = new byte[512];

                    for (int aIndex = 0; aIndex < 512; aIndex += 2)
                    {
                        atadTneid[aIndex]     = cgd.ident_data[aIndex + 1];
                        atadTneid[aIndex + 1] = cgd.ident_data[aIndex];
                    }

                    Identify.IdentifyDevice?idt = Identify.Decode(atadTneid);

                    if (idt.HasValue)
                    {
                        string[] separated = idt.Value.Model.Split(' ');

                        if (separated.Length == 1)
                        {
                            deviceInfo.Vendor = "ATA";
                            deviceInfo.Model  = separated[0];
                        }
                        else
                        {
                            deviceInfo.Vendor = separated[0];
                            deviceInfo.Model  = separated[^ 1];
Example #11
0
 public static T PtrToStructure <T>(IntPtr ptr)
 {
     return(SystemMarshal.PtrToStructure <T>(ptr));
 }