Пример #1
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (device == null || form == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                _DBG.WireProtocol.Commands.Monitor_MemoryMap.Range[] range = engine.MemoryMap();

                if (range != null && range.Length > 0)
                {
                    form.DumpToOutput("Type     Start       Size");
                    form.DumpToOutput("--------------------------------");
                    for (int i = 0; i < range.Length; i++)
                    {
                        string mem = "";
                        switch (range[i].m_flags)
                        {
                        case _DBG.WireProtocol.Commands.Monitor_MemoryMap.c_FLASH:
                            mem = "FLASH";
                            break;

                        case _DBG.WireProtocol.Commands.Monitor_MemoryMap.c_RAM:
                            mem = "RAM";
                            break;
                        }
                        form.DumpToOutput(string.Format("{0,-6} 0x{1:x08}  0x{2:x08}", mem, range[i].m_address, range[i].m_length));
                    }
                }
            }
 public DeploymentStatusDialog(MFDevice dev, params EraseOptions[] eraseBlocks)
     : this(dev, null, null)
 {
     m_fEraseCmd   = true;
     m_eraseBlocks = eraseBlocks;
     this.Text     = Properties.Resources.DeploymentStatusTitleErase;
 }
Пример #3
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (form == null || device == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                _DBG.WireProtocol.Commands.Monitor_DeploymentMap.Reply reply = engine.DeploymentMap();

                if (reply != null)
                {
                    for (int i = 0; i < reply.m_count; i++)
                    {
                        _DBG.WireProtocol.Commands.Monitor_DeploymentMap.DeploymentData dd = reply.m_map[i];

                        form.DumpToOutput("Assembly " + i.ToString());
                        form.DumpToOutput("  Address: " + dd.m_address.ToString());
                        form.DumpToOutput("  Size   : " + dd.m_size.ToString());
                        form.DumpToOutput("  CRC    : " + dd.m_CRC.ToString());
                    }

                    if (reply.m_count == 0)
                    {
                        form.DumpToOutput("No deployed assemblies");
                    }
                }
                else
                {
                    form.DumpToOutput("Command Not Supported by Device");
                }
            }
Пример #4
0
        /// <summary>
        /// Connects to the device at the specified port
        /// </summary>
        /// <param name="port"></param>
        public void Connect(MFPortDefinition port)
        {
            this._device              = new MFDeploy().Connect(port);
            this._device.OnDebugText += new EventHandler <DebugOutputEventArgs>(Device_OnDebugText);

            this.Connected(this, EventArgs.Empty);
        }
Пример #5
0
 public MfTargetDevice(MFPortDefinition port, MFDevice device)
 {
     _port   = port;
     _device = device;
     _tc     = App.Kernel.Get <TelemetryClient>();
     Task.Run(() => InitializeAsync());
 }
Пример #6
0
        private void updateSSLKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DumpToOutput("Updating SSL seed...", true);
            Thread.Sleep(0);

            Cursor old = Cursor;

            this.Cursor = Cursors.WaitCursor;

            try
            {
                MFDevice dev = ConnectToSelectedDevice();
                if (dev != null)
                {
                    MFSslKeyConfig cfg = new MFSslKeyConfig(dev);

                    cfg.Save();
                }
            }
            catch
            {
                MessageBox.Show(Properties.Resources.ErrorDeviceNotResponding, Properties.Resources.TitleAppDeploy, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                DisconnectFromSelectedDevice();
                Cursor = old;
                DumpToOutput("Update Complete!", true);
            }
        }
        public MFUsbConfigDialog(MFDevice device)
        {
            m_cfgHelper = new MFConfigHelper(device);
            m_cfg       = new MFUsbConfiguration(device);

            InitializeComponent();
        }
Пример #8
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                MFDevice.IMFDeviceInfo info = device.MFDeviceInfo;

                if (!info.Valid)
                {
                    form.DumpToOutput("DeviceInfo is not valid!");
                }
                else
                {
                    form.DumpToOutput("DeviceInfo:");
                    form.DumpToOutput(String.Format("  HAL build info: {0}, {1}", info.HalBuildVersion.ToString(), info.HalBuildInfo));
                    form.DumpToOutput(String.Format("  OEM Product codes (vendor, model, SKU): {0}, {1}, {2}", info.OEM.ToString(), info.Model.ToString(), info.SKU.ToString()));
                    form.DumpToOutput("  Serial Numbers (module, system):");
                    form.DumpToOutput("    " + info.ModuleSerialNumber);
                    form.DumpToOutput("    " + info.SystemSerialNumber);
                    form.DumpToOutput(String.Format("  Solution Build Info: {0}, {1}", info.SolutionBuildVersion.ToString(), info.SolutionBuildInfo));

                    form.DumpToOutput("  AppDomains:");
                    foreach (MFDevice.IAppDomainInfo adi in info.AppDomains)
                    {
                        form.DumpToOutput(String.Format("    {0}, id={1}", adi.Name, adi.ID));
                    }

                    form.DumpToOutput("  Assemblies:");
                    foreach (MFDevice.IAssemblyInfo ai in info.Assemblies)
                    {
                        form.DumpToOutput(String.Format("    {0},{1}", ai.Name, ai.Version));
                    }
                }
            }
Пример #9
0
        private void SetDeviceId(MFDevice device, Guid id)
        {
            var buffer = id.ToByteArray();
            var config = new MFConfigHelper(device);

            config.WriteConfig("S4NID", buffer);
        }
Пример #10
0
        public DeploymentStatusDialog(MFDevice dev, ReadOnlyCollection <string> files, string[] sig_files)
        {
            m_dev      = dev;
            m_files    = files;
            m_sigFiles = sig_files;

            InitializeComponent();
        }
Пример #11
0
 public override void Dispose()
 {
     if (_device != null)
     {
         _device.Dispose();
         _device = null;
     }
 }
Пример #12
0
 public void Connect()
 {
     CheckResponse(MFDevice.ESCNEnable(Storage.CROP_STORE_MEMORY));
     CheckResponse(_mObjmfDevice.OpenMonPrinter(OpenType.TYPE_PRINTER, "TM-S1000U"));
     CheckResponse(_mObjmfDevice.SCNMICRSetStatusBack());
     ConfigureMulti();
     Scan();
 }
        public MFNetworkConfigDialog(MFDevice device)
        {
            m_cfg         = new MFNetworkConfiguration(device);
            m_cfgHelper   = new MFConfigHelper(device);
            m_wirelessCfg = new MFWirelessConfiguration(device);

            InitializeComponent();
        }
Пример #14
0
        private void cLRCapabilitiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                MFDevice device = ConnectToSelectedDevice();

                if (device != null)
                {
                    _DBG.Engine engine = device.DbgEngine;

                    engine.TryToConnect(0, 100, true, Microsoft.SPOT.Debugger.ConnectionSource.Unknown);

                    Microsoft.SPOT.CLRCapabilities caps = engine.Capabilities;

                    if (caps == null || caps.IsUnknown)
                    {
                        DumpToOutput(Properties.Resources.ErrorNotSupported);
                        DisconnectFromSelectedDevice();
                        return;
                    }

                    Type t = typeof(Microsoft.SPOT.CLRCapabilities);
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        object o = pi.GetValue(caps, null);

                        try
                        {
                            if (o is Microsoft.SPOT.CLRCapabilities.LCDCapabilities ||
                                o is Microsoft.SPOT.CLRCapabilities.SoftwareVersionProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.HalSystemInfoProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.ClrInfoProperties ||
                                o is Microsoft.SPOT.CLRCapabilities.SolutionInfoProperties
                                )
                            {
                                foreach (FieldInfo fi in pi.PropertyType.GetFields())
                                {
                                    DumpToOutput(string.Format("{0,-40}{1}", pi.Name + "." + fi.Name + ":", fi.GetValue(o)));
                                }
                            }
                            else
                            {
                                DumpToOutput(string.Format("{0,-40}{1}", pi.Name + ":", o));
                            }
                        }
                        catch
                        {
                            DumpToOutput(Properties.Resources.ErrorNotSupported);
                        }
                    }
                    DisconnectFromSelectedDevice();
                }
            }
            catch
            {
                DumpToOutput(Properties.Resources.ErrorNotSupported);
            }
        }
Пример #15
0
 public EpsonDigitalizer()
 {
     _mObjmfDevice    = new MFDevice();
     _mObjmfBase      = new MFBase();
     _mObjmfScanFront = new MFScan();
     _mObjmfScanBack  = new MFScan();
     _mObjmfMicr      = new MFMicr();
     _mObjmfProcess   = new MFProcess();
     _mObjmfDevice.SCNMICRStatusCallback += ScnmicrSetStatusBack;
     _documents = new List <Document>();
     _mutex     = new Mutex(false);
 }
Пример #16
0
        public MFAppDeployConfigDialog(MFDevice device, ConfigDialogCommand command)
        {
            if (device != null)
            {
                m_cfgHelper = new MFConfigHelper(device);
                m_appDeploy = new MFApplicationDeployment(device);
            }
            m_command = command;
            m_device  = device;

            InitializeComponent();
        }
Пример #17
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (form == null || device == null)
                {
                    return;
                }

                _DBG.Engine engine = device.DbgEngine;

                engine.RebootDevice(Microsoft.SPOT.Debugger.Engine.RebootOption.EnterBootloader);

                device.ConnectToTinyBooter();
            }
Пример #18
0
        private void OnPlugInExecuteThread()
        {
            MFDevice dev = null;

            if (m_currentPlugInObject == null)
            {
                return;
            }

            try
            {
                m_deploy.OpenWithoutConnect = !m_currentPlugInObject.RequiresConnection;

                dev = ConnectToSelectedDevice();

                if (dev != null)
                {
                    if (m_currentPlugInObject.RunInSeparateThread)
                    {
                        DumpToOutput(string.Format(Properties.Resources.XCommand, m_currentPlugInObject.Name));
                    }

                    if (m_currentPlugInObject.RequiresConnection && (!dev.DbgEngine.TryToConnect(5, 100)))
                    {
                        throw new MFDeviceNoResponseException();
                    }

                    m_currentPlugInObject.OnAction(this, dev);
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception exc)
            {
                DumpToOutput(Properties.Resources.ErrorPrefix + exc.Message);
            }
            finally
            {
                DisconnectFromSelectedDevice();

                m_deploy.OpenWithoutConnect = false;

                if (m_currentPlugInObject.RunInSeparateThread)
                {
                    DumpToOutput(string.Format(Properties.Resources.StatusXComplete, m_currentPlugInObject.Name));
                }

                m_currentPlugInObject = null;
            }
        }
Пример #19
0
    public int Connect()
    {
        int retval = 0; /* okay */

        if (m_device != null)
        {
            Interlocked.Increment(ref m_devRefCount);
        }
        else
        {
            MFPortDefinition port;
            try
            {
                port = FindHeroPortDef();
            }
            catch (Exception excep)
            {
                Console.Out.WriteLine(excep.Message);
                return(-5); /* exception suggests HERO is connected to VS */
            }

            if (port == null)
            {
                retval = -1; /* could not find a device */
            }
            else
            {
                try
                {
                    m_device = m_deploy.Connect(port, null);

                    if (m_device != null)
                    {
                        m_device.OnDebugText += new EventHandler <DebugOutputEventArgs>(OnDbgTxt);

                        Interlocked.Increment(ref m_devRefCount);
                    }
                    else
                    {
                        retval = -2; /* tried to connect and failed */
                    }
                }
                catch (Exception)
                {
                    retval = -3; /* tried to connect and failed */
                }
            }
        }
        return(retval);
    }
Пример #20
0
        private void buttonErase_Click(object sender, EventArgs e)
        {
            MFDevice dev = ConnectToSelectedDevice();

            if (dev != null)
            {
                if (DialogResult.Yes == MessageBox.Show(Properties.Resources.MessageEraseConfirmation, Properties.Resources.TitleEraseConfirmation, MessageBoxButtons.YesNo))
                {
                    DeploymentStatusDialog dlg = new DeploymentStatusDialog(dev);
                    dlg.StartPosition = FormStartPosition.CenterParent;
                    dlg.ShowDialog(this);
                }
                DisconnectFromSelectedDevice();
            }
        }
Пример #21
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                _DBG.Engine engine = device.DbgEngine;

                if (device.ConnectToTinyBooter())
                {
                    // ExecuteMemory at address 0 performs an enumerate and execute, which
                    // will clear the bootloader entry flag
                    engine.ExecuteMemory(0);
                }
                else
                {
                    form.DumpToOutput("Unable to connect to TinyBooter!");
                }
            }
Пример #22
0
        private MFDevice ConnectToNetmfDevice(MFPortDefinition port)
        {
            MFDevice result = null;

            try
            {
                result = _deploy.Connect(port);
            }
            catch
            {
                MessageBox.Show(
                    "Failed to connect to device. You may need to reset your board or restart this program.", "Error",
                    MessageBoxButton.OK);
                result = null;
            }
            return(result);
        }
Пример #23
0
        private void buttonDeploy_Click(object sender, EventArgs e)
        {
            ReadOnlyCollection <string> files = this.Files;

            string[] sigfiles = new string[files.Count];
            int      cnt      = 0;

            if (files.Count <= 0)
            {
                MessageBox.Show(Properties.Resources.WarningNoFilesForDeploy, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            foreach (string file in files)
            {
                if (file.Trim().Length == 0)
                {
                    continue;
                }

                if (!File.Exists(file))
                {
                    MessageBox.Show(this, string.Format(Properties.Resources.ErrorFileCantOpen, file), Properties.Resources.ErrorTitleImageFile, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string signature_file = GetSignatureFileName(file);

                sigfiles[cnt++] = signature_file;
            }

            // update MRU items
            AddMRUFiles(comboBoxImageFile.Text.Trim());

            MFDevice dev = ConnectToSelectedDevice();

            if (dev != null)
            {
                DeploymentStatusDialog dlg = new DeploymentStatusDialog(dev, files, sigfiles);
                dlg.StartPosition = FormStartPosition.CenterParent;
                dlg.ShowDialog(this);

                DisconnectFromSelectedDevice();
            }
        }
Пример #24
0
        static void Main(string[] args)
        {
            using (MFDeploy deploy = new MFDeploy())
            {
                // Obtain devices connected to USB port
                IList <MFPortDefinition> portDefs = deploy.EnumPorts(TransportType.USB);

                // List devices
                Debug.WriteLine("USB Devices:");
                foreach (MFPortDefinition portDef in portDefs)
                {
                    Debug.WriteLine(portDef.Name);
                }

                // Return if no device was found
                if (portDefs.Count == 0)
                {
                    Debug.WriteLine("No device.");
                    return;
                }

                // Connect to first device that was found
                using (MFDevice device = deploy.Connect(portDefs[0]))
                {
                    uint entryPoint = 0;
                    if (device.Deploy("c:\\myapp.hex", // deployment image
                                      "c:\\myapp.sig", // signature file (optional)
                                      ref entryPoint   // return apps entry point
                                      ))
                    {
                        Debug.WriteLine("Deploying succeded.");

                        if (entryPoint != 0) // check if image has an entry point
                        {
                            Debug.WriteLine("Executing application.");
                            device.Execute(entryPoint);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Deploying failed.");
                    }
                }
            }
        }
Пример #25
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.DefaultExt      = "*.key";
                sfd.CheckPathExists = true;
                sfd.Filter          = "Key File (*.key)|*.key|All Files (*.*)|*.*";
                sfd.FilterIndex     = 0;
                sfd.AddExtension    = true;
                sfd.OverwritePrompt = true;
                sfd.Title           = "Create Empty Key";

                if (System.Windows.Forms.DialogResult.OK == sfd.ShowDialog())
                {
                    MFKeyConfig cfg      = new MFKeyConfig();
                    KeyPair     emptyKey = cfg.CreateEmptyKeyPair();
                    cfg.SaveKeyPair(emptyKey, sfd.FileName);
                }
            }
Пример #26
0
            public override void OnAction(IMFDeployForm form, MFDevice device)
            {
                if (device.ConnectToTinyBooter())
                {
                    _WP.Commands.Monitor_FlashSectorMap.Reply reply = device.DbgEngine.GetFlashSectorMap();

                    if (reply != null)
                    {
                        foreach (_WP.Commands.Monitor_FlashSectorMap.FlashSectorData sector in reply.m_map)
                        {
                            if (0 != (sector.m_flags & _WP.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CODE) ||
                                0 != (sector.m_flags & _WP.Commands.Monitor_FlashSectorMap.c_MEMORY_USAGE_CONFIG))
                            {
                                device.DbgEngine.EraseMemory(sector.m_address, sector.m_size);
                            }
                        }
                    }
                }
            }
Пример #27
0
        private Guid GetDeviceId(MFDevice device)
        {
            var result = Guid.Empty;

            try
            {
                var config = new MFConfigHelper(device);
                if (!config.IsValidConfig)
                {
                    throw new Exception("Invalid config");
                }
                if (config.IsFirmwareKeyLocked)
                {
                    throw new Exception("Firmware locked");
                }
                if (config.IsDeploymentKeyLocked)
                {
                    throw new Exception("Deployment locked");
                }
                var data = config.FindConfig("S4NID");
                if (data.Length > 16)
                {
                    var temp = new byte[16];
                    Array.Copy(data, data.Length - 16, temp, 0, 16);
                    data = temp;
                }
                if (data == null)
                {
                    result = Guid.Empty;
                }
                else
                {
                    result = new Guid(data);
                }
            }
            catch
            {
                result = Guid.Empty;
            }
            return(result);
        }
Пример #28
0
        private MFDevice ConnectToSelectedDevice()
        {
            if (m_device != null)
            {
                Interlocked.Increment(ref m_deviceRefCount);
            }
            else
            {
                MFPortDefinition port = null;
                this.Invoke((MethodInvoker) delegate
                {
                    port = GetSelectedItem();
                });

                if (port != null)
                {
                    try
                    {
                        m_device = m_deploy.Connect(port, port is MFTcpIpPort ? m_transportTinyBooter : null);

                        if (m_device != null)
                        {
                            comboBoxTransport.Invoke((MethodInvoker) delegate
                            {
                                comboBoxDevice.Enabled           = false;
                                comboBoxTransport.Enabled        = false;
                                connectToolStripMenuItem.Enabled = false;
                            });

                            m_device.OnDebugText += new EventHandler <DebugOutputEventArgs>(OnDbgTxt);
                            Interlocked.Increment(ref m_deviceRefCount);
                        }
                    }
                    catch (Exception exc)
                    {
                        DumpToOutput(Properties.Resources.ErrorPrefix + exc.Message);
                    }
                }
            }
            return(m_device);
        }
Пример #29
0
        public override void Load(string FriendlyName, int FrameRate, int Height, int Width, string Encoding)
        {
            HResult Return = MFExtern.MFStartup(0x00020070, MFStartup.Full);

            if (Return != 0)
            {
                Console.WriteLine("Constructor: call to MFExtern.MFStartup returned " + Return.ToString());
            }
            List <MFDevice> vcDevices = WMFUtils.GetDevicesByCategory(MFAttributesClsid.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, CLSID.MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);

            foreach (MFDevice device in vcDevices)
            {
                if (device.FriendlyName == FriendlyName)
                {
                    UnderlyingDevice = device;
                    break;
                }
            }
            IMFStreamIndex = GetRequestedStreamFormat(FrameRate, Width, Height, Encoding);
            IMFSnapIndex   = GetRequestedSnapFormat(Width, Height, Encoding);
        }
Пример #30
0
        private void Form1_FormClosing(System.Object sender, FormClosingEventArgs e)
        {
            m_fShuttingDown = true;

            if (m_pluginThread != null && m_pluginThread.IsAlive)
            {
                m_pluginThread.Abort();
            }

            if (m_device != null)
            {
                m_device.Dispose();
                m_device = null;
            }

            if (m_deploy != null)
            {
                m_deploy.Dispose();
                m_deploy = null;
            }
        }
Пример #31
0
            public List<MFDevice> EnumPorts(TransportType type)
            {
                /*
                We need to create two socket for discovery Udp multicast
                socket  sends discovery message
                socket2 receive messages
                */
                if (type != TransportType.Udp) //sanity check
                    type = TransportType.Udp;

                this.m_deviceList.Clear();          //start anew

                try
                {

                    foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                    {
                        if (address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            int num = 0;          // num of bytes return with receive socket
                            int index = 0;        // denotes the beginning of each stream from MF modules
                            int iy = 0;           // counts macaddress bytes
                            byte[] buffer = new byte[0x400]; //data buffer
                            byte[] macarr = new byte[0x06];  //mac address from data buffer
                            Socket socket = null; //tx socket on host
                            Socket socket2 = null;//rx socket on host
                            IPEndPoint localEP = new IPEndPoint(address, 0);
                            EndPoint remoteEP = new IPEndPoint(IPAddress.Any, this.m_DiscoveryMulticastPort);
                            IPEndPoint point3 = new IPEndPoint(address, this.m_DiscoveryMulticastPort);
                            IPEndPoint point4 = new IPEndPoint(this.m_DiscoveryMulticastAddress, this.m_DiscoveryMulticastPort);
                            try
                            {
                                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                                socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                                socket2.Bind(point3);
                                socket2.ReceiveTimeout = 0x3e8;

                                socket2.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(this.m_DiscoveryMulticastAddressRecv, address));
                                socket.Bind(localEP);
                                socket.MulticastLoopback = false;
                                socket.Ttl = 1;
                                socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0x40);
                                socket.SendTo(Encoding.ASCII.GetBytes(this.m_DiscoveryMulticastToken), SocketFlags.None, point4);

                                while (0 < (num = socket2.ReceiveFrom(buffer, index, buffer.Length - index, SocketFlags.None, ref remoteEP)))
                                {
                                    MFDevice mfDev = new MFDevice();
                                    mfDev.setPointRemoteIP(((IPEndPoint)remoteEP).Address.ToString()); //add Remote IP
                                    mfDev.setPointRemotePort(((IPEndPoint)remoteEP).Port);             //add Remote Port
                                    mfDev.setPointRemoteAdrFamily(((IPEndPoint)remoteEP).AddressFamily.ToString());  //add Remote Type
                                    //get/add mac address
                                    iy = 0;
                                    while (iy < 6)
                                    {
                                        macarr[iy] = buffer[index + 8 + iy];
                                        iy++;
                                    }
                                    mfDev.GetMacAddr(macarr);                                           //add Remote Mac Address
                                    m_deviceList.Add(mfDev);     //add object to Factory
                                    index += num;                // new ofset- remote dev answer simultaniously to multicast
                                    socket2.ReceiveTimeout = 200;//timeout of 200ms
                                }
                                socket2.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new MulticastOption(this.m_DiscoveryMulticastAddressRecv));
                            }
                            catch (SocketException)
                            {
                            }
                            finally
                            {
                                if (socket2 != null)
                                {
                                    socket2.Close();
                                    socket2 = null;
                                }
                                if (socket != null)
                                {
                                    socket.Close();
                                    socket = null;
                                }
                            }

                        }
                    }
                }
                catch (Exception)
                {
                }
                return m_deviceList;
            }
Пример #32
0
        //-------------------------------------------------------------------
        // SetDevice
        //
        // Set up preview for a specified video capture device.
        //-------------------------------------------------------------------
        public int SetDevice(MFDevice pDevice)
        {
            int hr = S_Ok;

            IMFActivate pActivate = pDevice.Activator;
            IMFMediaSource pSource = null;
            IMFAttributes pAttributes = null;
            object o = null;

            lock (this)
            {
                try
                {
                    // Release the current device, if any.
                    hr = CloseDevice();

                    if (Succeeded(hr))
                    {
                        // Create the media source for the device.
                        hr = pActivate.ActivateObject(typeof(IMFMediaSource).GUID, out o);
                    }

                    if (Succeeded(hr))
                    {
                        pSource = (IMFMediaSource)o;
                    }

                    // Get Symbolic device link
                    m_pwszSymbolicLink = pDevice.SymbolicName;

                    //
                    // Create the source reader.
                    //

                    // Create an attribute store to hold initialization settings.

                    if (Succeeded(hr))
                    {
                        hr = MFExtern.MFCreateAttributes(out pAttributes, 2);
                    }

                    if (Succeeded(hr))
                    {
                        hr = pAttributes.SetUINT32(MFAttributesClsid.MF_READWRITE_DISABLE_CONVERTERS, 1);
                    }

                    if (Succeeded(hr))
                    {
                        hr = pAttributes.SetUnknown(MFAttributesClsid.MF_SOURCE_READER_ASYNC_CALLBACK, this);
                    }

                    IMFSourceReader pRead = null;
                    if (Succeeded(hr))
                    {
                        hr = MFExtern.MFCreateSourceReaderFromMediaSource(pSource, pAttributes, out pRead);
                    }

                    if (Succeeded(hr))
                    {
                        m_pReader = (IMFSourceReaderAsync)pRead;
                    }

                    if (Succeeded(hr))
                    {
                        // Try to find a suitable output type.
                        for (int i = 0; ; i++)
                        {
                            IMFMediaType pType;
                            hr = m_pReader.GetNativeMediaType((int)MF_SOURCE_READER.FirstVideoStream, i, out pType);
                            if (Failed(hr))
                            {
                                break;
                            }

                            try
                            {
                                hr = TryMediaType(pType);
                                if (Succeeded(hr))
                                {
                                    // Found an output type.
                                    break;
                                }
                            }
                            finally
                            {
                                SafeRelease(pType);
                            }
                        }
                    }

                    if (Succeeded(hr))
                    {
                        hr = ConfigWriter();
                        if (Succeeded(hr))
                        {
                            m_draw.SetBitmap(BitmapOverlayFile);

                            // Ask for the first sample.
                            hr = m_pReader.ReadSample((int)MF_SOURCE_READER.FirstVideoStream, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                        }
                    }

                    if (Failed(hr))
                    {
                        if (pSource != null)
                        {
                            pSource.Shutdown();

                            // NOTE: The source reader shuts down the media source
                            // by default, but we might not have gotten that far.
                        }
                        CloseDevice();
                    }
                }
                finally
                {
                    SafeRelease(pSource);
                    SafeRelease(pAttributes);
                }
            }

            return hr;
        }