public void IOIOImpl_ToggleLED()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection(false);

            this.CreateCaptureLogHandlerSet();
            // we'll add the handler state on top of the default handlers so we don't have to peek into impl
            IOIO ourImpl = CreateIOIOImplAndConnect(ourConn,
                                                    new List <IObserverIOIO>()
            {
                this.CapturedConnectionState_, this.CapturedSingleQueueAllType_, this.CapturedLogs_
            });

            LOG.Debug("Setup Complete");
            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids

            DigitalOutputSpec ledSpec = new DigitalOutputSpec(Spec.LED_PIN);
            // SHOULD USE THE FACTORY instead of this lame ...
            IDigitalOutputConfigureCommand confDigitalOut = new DigitalOutputConfigureCommand(
                ledSpec);
            IDigitalOutputValueSetCommand turnItOn  = new DigitalOutputSetValueCommand(ledSpec, true);
            IDigitalOutputValueSetCommand turnItOff = new DigitalOutputSetValueCommand(ledSpec, false);

            ourImpl.PostMessage(confDigitalOut);
            for (int i = 0; i < 8; i++)
            {
                System.Threading.Thread.Sleep(150);
                ourImpl.PostMessage(turnItOn);
                System.Threading.Thread.Sleep(150);
                ourImpl.PostMessage(turnItOff);
            }
            // this test can fail if we can't connect to the device but otherwise no way to read pin 1 values
            Assert.IsTrue(true, "there is no status to check");
        }
Exemple #2
0
 public void MyTestInitialize()
 {
     ConnectionsOpenedDuringTest = new List <IOIOConnection>();
     DevicesOpenedDuringTest     = new List <IOIO>();
     GoodConnection_             = null;
     LOG.Debug("Done MyTestInitialize");
 }
Exemple #3
0
        public void MyTestCleanup()
        {
            DevicesOpenedDuringTest.ForEach(x =>
            {
                //x.Sync();
                // would like to reset so board is in original state every time we connect
                x.SoftReset();   // resets state without dropping connection
                // would we do this and wait instead
                //x.HardReset(); // like disconnecting the power
                x.Disconnect();
                LOG.Info("Disconnected " + x.ToString());
            });
            ConnectionsOpenedDuringTest.ForEach(x =>
            {
                if (x.CanClose())
                {
                    x.Disconnect();
                    LOG.Info("Disconnected " + x.ToString());
                }
            });
            GoodConnection_ = null;

            CapturedLogs_               = null;
            CapturedConnectionState_    = null;
            CapturedSingleQueueAllType_ = null;
            HandlerObservable_          = null;

            System.Threading.Thread.Sleep(100);
            LOG.Debug("Done MyTestCleanup");
        }
        public void CreateDigitalOutputTo_ToggleLED()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            // add our handlers on to p of default so we don't have to grovel around in the internal variables
            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids

            DigitalOutputSpec ledSpec = new DigitalOutputSpec(Spec.LED_PIN);
            IDigitalOutputConfigureCommand commandSetup = new DigitalOutputConfigureCommand(
                ledSpec, false);
            IDigitalOutputValueSetCommand commandOn  = new DigitalOutputSetValueCommand(ledSpec, true);
            IDigitalOutputValueSetCommand commandOff = new DigitalOutputSetValueCommand(ledSpec, false);

            //// TODO should use the hardware from the captured connection
            IResourceManager rManager = new ResourceManager(Hardware.IOIO0003);

            commandSetup.Alloc(rManager);
            commandOn.Alloc(rManager);
            commandOff.Alloc(rManager);

            commandSetup.ExecuteMessage(fooOut);
            for (int i = 0; i < 8; i++)
            {
                System.Threading.Thread.Sleep(200);
                commandOn.ExecuteMessage(fooOut);
                System.Threading.Thread.Sleep(200);
                commandOff.ExecuteMessage(fooOut);
            }
            Assert.IsTrue(true, "there is no status to check");
        }
        public void SerialConnectionFactory_CreateConnectionBad()
        {
            IOIOConnectionFactory factory    = new SerialConnectionFactory();
            IOIOConnection        connection = factory.CreateConnection(TestHarnessSetup.BAD_CONN_NAME);

            LOG.Info("Should have failed test on " + TestHarnessSetup.BAD_CONN_NAME);
        }
Exemple #6
0
        /// <summary>
        /// Use this to create your IOIO because it retains references to Tasks that are automatically cleaned up for you
        /// This should probably changed to take a list of observers instead
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        internal IOIO CreateIOIOImplAndConnect(IOIOConnection connection, List <IObserverIOIO> observers)
        {
            IOIO ourImpl = new IOIOImpl(connection, observers);

            DevicesOpenedDuringTest.Add(ourImpl);
            ourImpl.WaitForConnect();
            return(ourImpl);
        }
        public void UartTest_LoopbackOut31In32()
        {
            //// TODO should use the hardware from the captured connection
            IResourceManager rManager = new ResourceManager(Hardware.IOIO0003);
            IOIOConnection   ourConn  = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            ObserverTxStatusUart bufferObserver = new ObserverTxStatusUart();

            this.HandlerObservable_.Subscribe(bufferObserver);
            // add our own handler so we don't have to grovel aroudn in there
            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids


            UartConfigureCommand commandCreate = new UartConfigureCommand(
                new DigitalInputSpec(32), new DigitalOutputSpec(31), 38400, UartParity.NONE, UartStopBits.ONE);

            commandCreate.Alloc(rManager);
            commandCreate.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(10);

            string helloWorld = "Hello World";

            byte[] helloWorldBytes = System.Text.Encoding.ASCII.GetBytes(helloWorld);

            LOG.Debug("Sending Hello World");
            UartSendDataCommand commandSend = new UartSendDataCommand(commandCreate.UartDef, helloWorldBytes);

            commandSend.Alloc(rManager);
            commandSend.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(50);

            LOG.Debug("Closing Uart");
            UartCloseCommand commandClose = new UartCloseCommand(commandCreate.UartDef);

            commandClose.Alloc(rManager);
            commandClose.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(50);

            // IUartFrom is the parent interface for all messages coming from the UARt
            Assert.AreEqual(1 + 1 + helloWorldBytes.Count() + 1, this.CapturedSingleQueueAllType_.OfType <IUartFrom>().Count());

            Assert.AreEqual(1, this.CapturedSingleQueueAllType_.OfType <IUartOpenFrom>().Count(), "didn't get IUartOpenFrom");
            Assert.AreEqual(1, this.CapturedSingleQueueAllType_.OfType <IUartReportTxStatusFrom>().Count(), "didn't get IUartReportTXStatusFrom");

            IEnumerable <IUartDataFrom> readValues = this.CapturedSingleQueueAllType_.OfType <IUartDataFrom>();

            Assert.AreEqual(helloWorldBytes.Count(), readValues.Count(), "Didn't find the number of expected IUartFrom: " + readValues.Count());
            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured " + +this.CapturedSingleQueueAllType_.Count());
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());

            Assert.AreEqual(1, this.CapturedSingleQueueAllType_.OfType <IUartCloseFrom>().Count());
            // should verify close command in the resource
        }
Exemple #8
0
 /// <summary>
 /// This lets you add a custom handler if you want to pick one of the other threading models
 /// for your observers
 /// </summary>
 /// <param name="conn"></param>
 /// <param name="customHandler">your handler.  This always adds:
 ///     IOIOHandlerCaptureConnectionState , IOIOHandlerCaptureLog</param>
 public IOIOImpl(IOIOConnection conn, IIncomingHandlerIOIO customHandler)
 {
     if (conn == null)
     {
         throw new IllegalStateException("Silly Rabbit: You can't create an IOIOImpl without a connection!");
     }
     this.Conn_ = conn;
     ConfigureHandlers(customHandler, null);
 }
Exemple #9
0
 /// <summary>
 /// This lets you add observers to the default handler with the default threading model
 /// </summary>
 /// <param name="conn"></param>
 /// <param name="observers"></param>
 public IOIOImpl(IOIOConnection conn, List <IObserverIOIO> observers)
 {
     if (conn == null)
     {
         throw new IllegalStateException("Silly Rabbit: You can't create an IOIOImpl without a connection!");
     }
     this.Conn_ = conn;
     ConfigureHandlers(null, observers);
 }
Exemple #10
0
        public void IOIOProtocolIncoming_StartRunLoop()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");
            IOIOProtocolIncoming fooIn = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);

            // wait for reply
            System.Threading.Thread.Sleep(2000);
            Assert.IsNotNull(CapturedConnectionState_.EstablishConnectionFrom_);
        }
Exemple #11
0
        /// <summary>
        /// Creates a "good" serial GoodConnection_ and registeres it for automatic closure
        /// </summary>
        /// <param name="leaveConnectionOpen">defaults to true because that is the way the first tests ran.
        ///     set to false for IOIOImpl</param>
        /// <returns>connected that is set on instance variable</returns>
        internal IOIOConnection CreateGoodSerialConnection(bool leaveConnectionOpen = true)
        {
            IOIOConnectionFactory factory = new SerialConnectionFactory();

            GoodConnection_ = factory.CreateConnection(TestHarnessSetup.GOOD_CONN_NAME);
            this.ConnectionsOpenedDuringTest.Add(GoodConnection_); // always add connections used by incoming
            if (leaveConnectionOpen)
            {
                GoodConnection_.WaitForConnect(); // actually IsOpen the GoodConnection_
            }
            LOG.Debug("Done CreateGoodSerialConnection");
            return(GoodConnection_);
        }
Exemple #12
0
        public void IOIOProtocolOutgoing_CheckInterfaceVersion()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");
            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids
            fooOut.checkInterfaceVersion();
            // wait for reply
            System.Threading.Thread.Sleep(2000);
            Assert.IsTrue(CapturedConnectionState_.Supported_.IsSupported, " the HandlerContainer_ returned not supported interface.");
        }
        public void ServoTest_SimpleServoTest()
        {
            //// TODO should use the hardware from the captured connection
            IResourceManager rManager = new ResourceManager(Hardware.IOIO0003);
            IOIOConnection   ourConn  = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(20);                  // wait for us to get the hardware ids
            int pwmFrequency             = 100;
            DigitalOutputSpec pwmPinSpec = new DigitalOutputSpec(3, DigitalOutputSpecMode.NORMAL);

            // configure for servo
            PwmOutputConfigureCommand commandCreatePWM = new PwmOutputConfigureCommand(pwmPinSpec, pwmFrequency);

            commandCreatePWM.Alloc(rManager);
            commandCreatePWM.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(100);

            for (int i = 0; i < 4; i++)
            {
                // change it after settling
                PwmOutputUpdateCommand lowValue = new PwmOutputUpdatePulseWidthCommand(commandCreatePWM.PwmDef, 600);
                lowValue.Alloc(rManager);
                lowValue.ExecuteMessage(fooOut);
                System.Threading.Thread.Sleep(500);
                // change it after settling
                PwmOutputUpdateCommand highValue = new PwmOutputUpdatePulseWidthCommand(commandCreatePWM.PwmDef, 2000);
                highValue.Alloc(rManager);
                highValue.ExecuteMessage(fooOut);
                System.Threading.Thread.Sleep(500);
            }
            PwmOutputCloseCommand commandReleasePwm = new PwmOutputCloseCommand(commandCreatePWM.PwmDef);

            commandReleasePwm.Alloc(rManager);
            commandReleasePwm.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(500);
            //IEnumerable<IReportAnalogPinValuesFrom> readValues = this.HandlerSingleQueueAllType_.CapturedMessages_
            //	.OfType<IReportAnalogPinValuesFrom>();
            //Assert.IsTrue(readValues.Count() >= 1, "Didn't find the number of expected IReportAnalogPinValuesFrom: " + readValues.Count());
            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured " + +this.CapturedSingleQueueAllType_.Count());
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());
            // should verify close command
        }
Exemple #14
0
        public void CreateAnalogInputOutputTo_AnalogLoopbackOut31In32()
        {
            //// TODO should use the hardware from the captured connection
            IResourceManager rManager = new ResourceManager(Hardware.IOIO0003);
            IOIOConnection   ourConn  = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids
            AnalogInputConfigureCommand commandCreateIn = new AnalogInputConfigureCommand(31, true);

            commandCreateIn.Alloc(rManager);
            commandCreateIn.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(10);
            DigitalOutputSpec pwmPinSpec = new DigitalOutputSpec(32, DigitalOutputSpecMode.NORMAL);

            // set analog "voltage"
            PwmOutputConfigureCommand commandCreatePWM = new PwmOutputConfigureCommand(pwmPinSpec, 1000, 0.3f);

            commandCreatePWM.Alloc(rManager);
            commandCreatePWM.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(100);
            // change it after settling
            PwmOutputUpdateCommand commandChangePWM = new PwmOutputUpdateDutyCycleCommand(commandCreatePWM.PwmDef, 0.7f);

            commandChangePWM.Alloc(rManager);
            commandChangePWM.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(100);
            PwmOutputCloseCommand commandReleasePwm = new PwmOutputCloseCommand(commandCreatePWM.PwmDef);

            commandReleasePwm.Alloc(rManager);
            commandReleasePwm.ExecuteMessage(fooOut);
            System.Threading.Thread.Sleep(50);

            IEnumerable <IReportAnalogPinValuesFrom> readValues = this.CapturedSingleQueueAllType_
                                                                  .OfType <IReportAnalogPinValuesFrom>();

            Assert.IsTrue(readValues.Count() >= 1, "Didn't find the number of expected IReportAnalogPinValuesFrom: " + readValues.Count());
            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured " + this.CapturedSingleQueueAllType_.Count());
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());
            // should verify close command
        }
        public virtual ICollection <IOIOConnection> CreateConnections(ICollection <string> connectionStrings)
        {
            List <IOIOConnection> createdConnections = new List <IOIOConnection>();

            foreach (string singleConnectionString in connectionStrings)
            {
                try
                {
                    IOIOConnection oneConnector = this.CreateConnection(singleConnectionString);
                    createdConnections.Add(oneConnector);
                }
                catch (ConnectionCreationException e)
                {
                    LOG.Debug("Couldn't IsOpen while iterating " + singleConnectionString, e);
                }
            }
            return(createdConnections);
        }
        public void IOIOImpl_DigitaLoopbackOut31In32()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection(false);

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");

            // we'll add the handler state on top of the default handlers so we don't have to peek into impl
            IOIO ourImpl = CreateIOIOImplAndConnect(ourConn,
                                                    new List <IObserverIOIO>()
            {
                this.CapturedConnectionState_, this.CapturedSingleQueueAllType_, this.CapturedLogs_
            });

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids

            // SHOULD USE THE FACTORY instead of this lame ...
            IDigitalOutputConfigureCommand confDigitalOut =
                new DigitalOutputConfigureCommand(new DigitalOutputSpec(31));
            IDigitalInputConfigureCommand configDigitalIn =
                new DigitalInputConfigureCommand(new DigitalInputSpec(32, DigitalInputSpecMode.PULL_UP), true);

            IDigitalOutputValueSetCommand turnItOn  = new DigitalOutputSetValueCommand(new DigitalOutputSpec(31), true);
            IDigitalOutputValueSetCommand turnItOff = new DigitalOutputSetValueCommand(new DigitalOutputSpec(31), false);

            ourImpl.PostMessage(confDigitalOut);
            ourImpl.PostMessage(configDigitalIn);
            for (int i = 0; i < 8; i++)
            {
                System.Threading.Thread.Sleep(100);
                ourImpl.PostMessage(turnItOn);
                System.Threading.Thread.Sleep(100);
                ourImpl.PostMessage(turnItOff);
            }
            System.Threading.Thread.Sleep(100);

            IEnumerable <IMessageFromIOIO> digitalMessagesIn = this.CapturedSingleQueueAllType_;
            int changeCount =
                digitalMessagesIn.OfType <IReportDigitalInStatusFrom>().Where(m => m.Pin == 32).Count();

            Assert.AreEqual(1 + (2 * 8), changeCount, "trying to figure out how many changes we'd see");
        }
Exemple #17
0
        public void IOIOProtocolOutgoing_ToggleLED()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");

            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids

            fooOut.setPinDigitalOut(Spec.LED_PIN, false, DigitalOutputSpecMode.NORMAL);
            for (int i = 0; i < 8; i++)
            {
                System.Threading.Thread.Sleep(200);
                fooOut.setDigitalOutLevel(Spec.LED_PIN, true);
                System.Threading.Thread.Sleep(200);
                fooOut.setDigitalOutLevel(Spec.LED_PIN, false);
            }
            Assert.IsTrue(true, "there is no status to check");
        }
Exemple #18
0
        public void IOIOProtocolOutgoing_DigitalLoopbackOut31In32()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection();

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");

            IOIOProtocolIncoming fooIn  = new IOIOProtocolIncoming(ourConn.GetInputStream(), HandlerObservable_);
            IOIOProtocolOutgoing fooOut = new IOIOProtocolOutgoing(ourConn.GetOutputStream());

            System.Threading.Thread.Sleep(50); // receive the HW ID
            LOG.Info("This test requires Pin 31 and 32 be shorted together");
            fooOut.setPinDigitalIn(31, DigitalInputSpecMode.FLOATING);
            // request to be told of state change.  system will acknowledge this
            fooOut.setChangeNotify(31, true);
            // first change that will be captured...
            fooOut.setPinDigitalOut(32, false, DigitalOutputSpecMode.NORMAL);
            // second change that is captured
            fooOut.setDigitalOutLevel(32, true);
            // we could wait until our acknowledgements are received
            System.Threading.Thread.Sleep(300);
            // all log  methods contain method name which is in the interface so this is reasonably safe
            // we get one change event as soon as the Pin input Pin is configured + 2 changes in test
            int matchingLogs = this.CapturedLogs_.CapturedLogs_.Count(s => s.Contains(typeof(ReportDigitalInStatusFrom).Name));

            // sometimes we get 3 and sometimes 4 (!?)
            Assert.IsTrue(3 == matchingLogs || 4 == matchingLogs, "Should have captured 3 or 4 input changes, not " + matchingLogs + ".  Are pins 31 and 32 shorted together");
            // verify the system acknowledged our request to be notified of state change
            Assert.AreEqual(1, this.CapturedSingleQueueAllType_
                            .OfType <ISetChangeNotifyMessageFrom>().Where(m => m.Pin == 31).Count()
                            , "Unexpected count for IReportDigitalInStatusFrom");
            // verify we got Pin state changes for 31
            Assert.AreEqual(3, this.CapturedSingleQueueAllType_
                            .OfType <IReportDigitalInStatusFrom>().Where(m => m.Pin == 31).Count()
                            , "Unexpected count for IReportDigitalInStatusFrom");
        }
Exemple #19
0
        public void UartTest_BigBufferOut31In32()
        {
            //// TODO should use the hardware from the captured connection
            IOIOConnection ourConn = this.CreateGoodSerialConnection(false);

            this.CreateCaptureLogHandlerSet();
            // MUST use IOIOImpl to get "send" notifications for buffer management
            // add our own handler so we don't have to grovel around in there
            IOIO ourImpl = CreateIOIOImplAndConnect(ourConn,
                                                    new List <IObserverIOIO>()
            {
                this.CapturedConnectionState_, this.CapturedSingleQueueAllType_, this.CapturedLogs_
            });

            LOG.Debug("Setup Complete");
            System.Threading.Thread.Sleep(100); // wait for us to get the hardware ids

            UartConfigureCommand commandCreate = new UartConfigureCommand(
                new DigitalInputSpec(32), new DigitalOutputSpec(31), 19200, UartParity.NONE, UartStopBits.ONE);

            ourImpl.PostMessage(commandCreate);
            System.Threading.Thread.Sleep(10);

            // create byte buffer
            // only 64 can be sent in a single message
            StringBuilder builder    = new StringBuilder();
            int           numBlock10 = 3;

            for (int i = 0; i < numBlock10; i++)
            {
                builder.Append("0123456789");
            }
            string helloWorld = builder.ToString();

            // should overrun the internal buffer to make sure observer flow control is working
            // buffer is 256 so cnt=4 means get one buffer update : cnt=7 means more than one full buffer
            char hack          = 'A';
            int  numBufferSend = 10;

            for (int i = 0; i < numBufferSend; i++)
            {
                byte[] helloWorldBytes = System.Text.Encoding.ASCII.GetBytes(helloWorld + hack);
                LOG.Debug("Sending long string " + i + ":" + helloWorldBytes.Length);
                UartSendDataCommand commandSend = new UartSendDataCommand(commandCreate.UartDef, helloWorldBytes);
                ourImpl.PostMessage(commandSend);
                hack++;
                System.Threading.Thread.Sleep(50);
            }
            // message posts will possibly block if IOIO UART ran out of buffer space
            // but it may still run before all data sent from IOIO buffers to the UART pins
            // really node for this since we wait for UART close
            System.Threading.Thread.Sleep(300);

            LOG.Debug("Closing Uart");
            UartCloseCommand commandClose = new UartCloseCommand(commandCreate.UartDef);

            ourImpl.PostMessage(commandClose);

            // either sleep for some time
            //System.Threading.Thread.Sleep(5000);
            // or wait until we get the close ack
            int maxTimeMsec = 5000;

            while (this.CapturedSingleQueueAllType_.OfType <IUartCloseFrom>().Count() == 0)
            {
                Assert.IsTrue(maxTimeMsec > 0, "Did not receive IUartCloseFrom in the expected amount of time");
                System.Threading.Thread.Sleep(10);
                maxTimeMsec -= 10;
            }

            Assert.AreEqual(1, this.CapturedSingleQueueAllType_.OfType <IUartOpenFrom>().Count(), "didn't get IUartOpenFrom");
            // we should have counted bytes,  count is first buffer size + each update at the 130 mark
            int expectedNumberTxMessages = 1 + ((numBufferSend * numBlock10 * 10) / 130);

            Assert.AreEqual(expectedNumberTxMessages, this.CapturedSingleQueueAllType_.OfType <IUartReportTxStatusFrom>().Count(), "didn't get IUartReportTXStatusFrom");

            int expectedDataPacketsReceived        = (numBlock10 * 10 + 1) * numBufferSend;
            IEnumerable <IUartDataFrom> readValues = this.CapturedSingleQueueAllType_.OfType <IUartDataFrom>();

            Assert.AreEqual(expectedDataPacketsReceived, readValues.Count(), "Didn't find the number of expected IUartFrom: " + readValues.Count());

            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured " + +this.CapturedSingleQueueAllType_.Count());
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());

            Assert.AreEqual(1, this.CapturedSingleQueueAllType_.OfType <IUartCloseFrom>().Count());
            // should verify close command in the Resource manager

            // We get back one packet for each character sent that was looped back + uart open, TX buffer status uart close
            int expectedNumDataPackets = expectedDataPacketsReceived;

            Assert.AreEqual(1 + expectedNumberTxMessages + expectedNumDataPackets + 1, this.CapturedSingleQueueAllType_.OfType <IUartFrom>().Count());
        }
        public void TwiI2CTest_JEELabsExpander_Integration()
        {
            int ExpectedReceiveCount = 0;

            int TwiVirtualDevice = 0;
            // slave address is 7 bits, ExpanderPlug uses 0x20, 0x21, 0x22 0x23 based on jumpers
            int  JeeExpanderAddress = 0x20;
            byte RegisterIoDir      = 0x00;
            byte RegisterIPol       = 0x01; // input polarity
            byte RegisterGpIntEna   = 0x02;
            byte RegisterDefVal     = 0x03;
            byte RegisterIntCon     = 0x04;
            byte RegisterIoCon      = 0x05; // controls auto increment for read
            byte RegisterGppu       = 0x06;
            byte RegisterIntf       = 0x07;
            byte RegisterIntCap     = 0x08;
            byte RegisterGpio       = 0x09; // Port values.  Writing modifes the OLat
            byte RegisterOLat       = 0x0a; // Output Latch

            // all ouitput and inverted
            byte[] ConfigureAllOutput      = new Byte[] { RegisterIoDir, 0x00 };
            byte[] ReadRegisterIoDir       = new Byte[] { RegisterIoDir };
            byte[] ReadRegisterOutputLatch = new Byte[] { RegisterOLat };

            byte[] WriteAllHigh = new Byte[] { RegisterGpio, 0xFF };
            byte[] WriteAllLow  = new Byte[] { RegisterGpio, 0x00 };


            IOIOConnection ourConn = this.CreateGoodSerialConnection(false);

            this.CreateCaptureLogHandlerSet();
            LOG.Debug("Setup Complete");

            // we'll add the handler state on top of the default handlers so we don't have to peek into impl
            ExpectedReceiveCount++;
            IOIO ourImpl = CreateIOIOImplAndConnect(ourConn,
                                                    new List <IObserverIOIO>()
            {
                this.CapturedConnectionState_, this.CapturedSingleQueueAllType_, this.CapturedLogs_
            });

            System.Threading.Thread.Sleep(100);  // wait for us to get the hardware ids

            LOG.Debug("Configuring TWI");
            IOIOMessageCommandFactory  factory      = new IOIOMessageCommandFactory();
            ITwiMasterConfigureCommand startCommand = factory.CreateTwiConfigure(TwiVirtualDevice, TwiMasterRate.RATE_400KHz, false);

            ourImpl.PostMessage(startCommand);
            ExpectedReceiveCount += 2;    // HandleI2cOpen HandleI2cReportTxStatus
            System.Threading.Thread.Sleep(50);
            TwiSpec twiDef = startCommand.TwiDef;

            LOG.Debug("Reading Initial Register Status");
            ITwiMasterSendDataCommand readInitalRegisterState = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, ReadRegisterIoDir, 11);

            ourImpl.PostMessage(readInitalRegisterState);
            ExpectedReceiveCount++; // I2cResultFrom
            System.Threading.Thread.Sleep(50);
            LOG.Debug("Configuring port direction as all output ");
            ITwiMasterSendDataCommand configureDirectionCommand = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, ConfigureAllOutput, 0);

            ourImpl.PostMessage(configureDirectionCommand);
            ExpectedReceiveCount++; // I2cResultFrom
            System.Threading.Thread.Sleep(50);
            LOG.Debug("Reading Post-config Register Status");
            ITwiMasterSendDataCommand readPostConfigRegisterState = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, ReadRegisterIoDir, 11);

            ourImpl.PostMessage(readPostConfigRegisterState);
            ExpectedReceiveCount++; // I2cResultFrom
            System.Threading.Thread.Sleep(50);

            // not really safe to reuse commands because you don't know if they are modified
            ITwiMasterSendDataCommand commandHigh = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, WriteAllHigh, 0);
            ITwiMasterSendDataCommand commandLow  = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, WriteAllLow, 0);
            ITwiMasterSendDataCommand queryOLat   = factory.CreateTwiSendData(twiDef, JeeExpanderAddress, false, ReadRegisterOutputLatch, 1);

            for (int i = 0; i < 2; i++)
            {
                LOG.Debug("Post Low");
                ourImpl.PostMessage(commandLow);
                ExpectedReceiveCount++; // I2cResultFrom
                System.Threading.Thread.Sleep(150);
                LOG.Debug("Check Are Latches Low");
                ourImpl.PostMessage(queryOLat);
                ExpectedReceiveCount++; // I2cResultFrom
                System.Threading.Thread.Sleep(50);
                LOG.Debug("Post High");
                ourImpl.PostMessage(commandHigh);
                ExpectedReceiveCount++; // I2cResultFrom
                System.Threading.Thread.Sleep(150);
                LOG.Debug("Check Are Latches High");
                ourImpl.PostMessage(queryOLat);
                ExpectedReceiveCount++; // I2cResultFrom
                System.Threading.Thread.Sleep(50);
            }

            ITwiMasterCloseCommand closeCommand = factory.CreateTwiClose(twiDef);

            ourImpl.PostMessage(closeCommand);
            ExpectedReceiveCount++; // HandleI2cClose
            System.Threading.Thread.Sleep(100);

            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured:" + +this.CapturedSingleQueueAllType_.Count() + " Expected:" + ExpectedReceiveCount);
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());
            // should verify close command!
            // should verify results of the latch checks.!
            // instead do this lame test!
            Assert.AreEqual(ExpectedReceiveCount, this.CapturedSingleQueueAllType_.Count(),
                            "This test will fail if you do not have a JeeNodes port expander at I2C address " + JeeExpanderAddress
                            + " on Twi " + TwiVirtualDevice);
        }
        public void TwiI2CTest_L3G4200D_Integration()
        {
            IOIOConnection ourConn = this.CreateGoodSerialConnection(false);
            // create our custom I2C result observer and add it to the default set
            ObserverI2cResultTest observer = new ObserverI2cResultTest();

            this.CreateCaptureLogHandlerSet();
            // we'll inject our observers on top of the default handlers so we don't have to peek into impl
            IOIO ourImpl = CreateIOIOImplAndConnect(ourConn, new List <IObserverIOIO>()
            {
                this.CapturedConnectionState_, this.CapturedSingleQueueAllType_, this.CapturedLogs_,
                observer
            });

            LOG.Debug("Setup Complete");
            System.Threading.Thread.Sleep(100);  // wait for us to get the hardware ids

            ourImpl.SoftReset();
            System.Threading.Thread.Sleep(100);

            IOIOMessageCommandFactory  factory      = new IOIOMessageCommandFactory();
            ITwiMasterConfigureCommand startCommand = factory.CreateTwiConfigure(0, TwiMasterRate.RATE_400KHz, false);

            ourImpl.PostMessage(startCommand);
            System.Threading.Thread.Sleep(50);
            TwiSpec twiDef = startCommand.TwiDef;

            LOG.Debug("Ask for Who Am I");
            // send the whoami command - we expect the id to be Gyro_WhoAmI_ID
            byte[] ReadWhoAmiRegisterData             = new byte[] { L3G4200DConstants.Gyro_WhoAmI_Register };
            ITwiMasterSendDataCommand startupCommand1 = factory.CreateTwiSendData(twiDef, L3G4200DConstants.GyroSlaveAddress1, false, ReadWhoAmiRegisterData, 1);

            ourImpl.PostMessage(startupCommand1);
            System.Threading.Thread.Sleep(50);
            // should check for Gyro_WhoAmI_ID_L3G4200D !

            // Enable x, y, z and turn off power down
            // auto increment registers
            byte ControlRegisterAutoIncrement = L3G4200DConstants.Gyro_CTRL_REG1 |= Convert.ToByte(0x80);

            byte[] RegisterConfigurationData = new byte[] { ControlRegisterAutoIncrement,
                                                            Convert.ToByte("00001111", 2),
                                                            Convert.ToByte("00000000", 2),
                                                            Convert.ToByte("00000000", 2),
                                                            L3G4200DConstants.Gyro_Range_DPS_2000,
                                                            //Enable High pass filter
                                                            Convert.ToByte("00000000", 2) };
            LOG.Debug("Updating Registers starting with " + L3G4200DConstants.Gyro_CTRL_REG1.ToString("X") + ":" + RegisterConfigurationData);
            ITwiMasterSendDataCommand ConfigureRegisters = factory.CreateTwiSendData(twiDef, L3G4200DConstants.GyroSlaveAddress1, false, RegisterConfigurationData, 0);

            ourImpl.PostMessage(ConfigureRegisters);

            LOG.Debug("Reading Registers starting with " + L3G4200DConstants.Gyro_CTRL_REG1.ToString("X"));
            byte[] ReadRegisterControl = new byte[] { ControlRegisterAutoIncrement };
            ITwiMasterSendDataCommand ReadRegistersCommand = factory.CreateTwiSendData(twiDef, L3G4200DConstants.GyroSlaveAddress1, false, ReadRegisterControl, 5);

            ourImpl.PostMessage(ReadRegistersCommand);
            System.Threading.Thread.Sleep(50);

            // clear the list
            observer.allEvents = new ConcurrentQueue <II2cResultFrom>();

            // Read back the current values -- could wait for int to go high but can't see it....
            // Top most bit in address turns on auto inc.  That is weirder than usual i2c
            // Who thought that there should be no bitwise byte operators but then came up with |= ?
            // never get more than allowableOutstanding behind
            // on my machine it takes 15msec to receive a message after sending
            int allowableOutstanding = 10;
            int numReps      = 50;
            int count        = 0;
            int maxWaitCount = 50;

            for (int i = 1; i <= numReps; i++)
            {
                LOG.Debug("Send read-only command retreive xyz with auto increment sendCount: " + i);
                observer.LastResult_ = null;
                byte[] ReadFromFirstOutRegisterWithAutoInc = new byte[] { L3G4200DConstants.Gyro_First_Out_Register |= Convert.ToByte(0x80) };
                ITwiMasterSendDataCommand ReadXYZ          = factory.CreateTwiSendData(twiDef, L3G4200DConstants.GyroSlaveAddress1, false, ReadFromFirstOutRegisterWithAutoInc, 6);
                ourImpl.PostMessage(ReadXYZ);
                count = 0;
                while (count <= maxWaitCount && i > observer.allEvents.Count + allowableOutstanding)
                {
                    // waiting for some reply
                    LOG.Debug("waiting: sendCount:" + i + ", observCount:" + observer.allEvents.Count);
                    System.Threading.Thread.Sleep(5);
                    count++;
                }
                if (count >= maxWaitCount)
                {
                    Assert.Fail("waitedCount:" + count + " while trying to send");
                }
            }
            // this is only needed if maxWaitCount > 0
            count = 0;
            while (count < maxWaitCount && numReps > observer.allEvents.Count)
            {
                LOG.Debug("i:" + numReps + ",count:" + observer.allEvents.Count);
                System.Threading.Thread.Sleep(10);
                count++;
            }
            if (count >= maxWaitCount)
            {
                Assert.Fail("waited " + count + " while trying to receive");
            }

            System.Threading.Thread.Sleep(50);
            LOG.Debug("Close Gyroscope");
            ITwiMasterCloseCommand closeCommand = factory.CreateTwiClose(twiDef);

            ourImpl.PostMessage(closeCommand);
            System.Threading.Thread.Sleep(100);

            // logging the messages with any other string doesn't show the messages themselves !?
            LOG.Debug("Captured (all):" + this.CapturedSingleQueueAllType_.Count());
            // expect 6 + number of reports we requested
            LOG.Debug("Captured (i2c):" + observer.allEvents.Count);
            LOG.Debug(this.CapturedSingleQueueAllType_.GetEnumerator());
            // should verify close command
        }