コード例 #1
0
ファイル: RCXBrick.cs プロジェクト: old8xp/AForge.NET
        /// <summary>
        /// Connect to Lego RCX brick.
        /// </summary>
        ///
        /// <param name="towerType">Type of IR tower to use for communication with RCX brick.</param>
        ///
        /// <returns>Returns <b>true</b> on successful connection or <b>false</b>
        /// otherwise.</returns>
        ///
        /// <remarks>If connection to RCX brick was established before the call, existing connection will be reused.
        /// If it is required to force reconnection, then <see cref="Disconnect"/> method should be called before.
        /// </remarks>
        ///
        public bool Connect(IRTowerType towerType)
        {
            lock ( sync )
            {
                // check if we are already connected
                if (stack != IntPtr.Zero)
                {
                    return(true);
                }

                uint status;

                // create stack
                status = GhostAPI.GhCreateStack(
                    (towerType == IRTowerType.USB) ? "LEGO.Pbk.CommStack.Port.USB" : "LEGO.Pbk.CommStack.Port.RS232",
                    "LEGO.Pbk.CommStack.Protocol.IR",
                    "LEGO.Pbk.CommStack.Session",
                    out stack);

                if (!GhostAPI.PBK_SUCCEEDED(status))
                {
                    return(false);
                }

                // select first available device
                StringBuilder sb = new StringBuilder(200);
                status = GhostAPI.GhSelectFirstDevice(stack, sb, sb.Length);

                if (!GhostAPI.PBK_SUCCEEDED(status))
                {
                    Disconnect( );
                    return(false);
                }

                // open stack, set interleave, set wait mode and check if the brick is alive
                if (
                    !GhostAPI.PBK_SUCCEEDED(GhostAPI.GhOpen(stack)) ||
                    !GhostAPI.PBK_SUCCEEDED(GhostAPI.GhSetWaitMode(stack, IntPtr.Zero)) ||
                    !GhostAPI.PBK_SUCCEEDED(GhostAPI.GhSetInterleave(stack, 1, 0)) ||
                    !IsAlive( )
                    )
                {
                    Disconnect( );
                    return(false);
                }
            }

            return(true);
        }