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");
        }
        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 #3
0
        public MainWindow()
        {
            InitializeComponent();
            string comPort = FindDeviceHack.TryAndFindIOIODevice();

            ComPort_Field.Text = comPort;
            if (comPort != null)
            {
                IOIOConnection connection = new SerialConnectionFactory().CreateConnection(comPort);

                ObserverConnectionState handlerCaptureState = new ObserverConnectionState();
                RotationObserver        rotationObserver    = new RotationObserver(
                    L3G4200DConstants.Gyro_DPS_LSB_2000,        // must match the sensitivity in register initialization
                    PollingIntervalMsec,
                    this.X_Angle, this.Y_Angle, this.Z_Angle,
                    this.X_RawField, this.Y_RawField, this.Z_RawField,
                    this.X_CallibField, this.Y_CallibField, this.Z_CallibField,
                    this.Teapot
                    );

                OurImpl_ = new IOIOImpl(connection, new List <IObserverIOIO>()
                {
                    handlerCaptureState, rotationObserver
                }
                                        );
                OurImpl_.WaitForConnect();

                IConnectedDeviceResponse device = handlerCaptureState.ConnectedDeviceDescription();
                if (device != null)
                {
                    // could display board details
                }
                CommandFactory_ = new IOIOMessageCommandFactory();
                ConfigureCompass();
                ConfigureTimedEvents();
            }
            else
            {
                ComPort_Field.Text = "Unable to find an IOIO device";
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            string comPort = FindDeviceHack.TryAndFindIOIODevice();

            ComPort_Field.Text = comPort;
            if (comPort != null)
            {
                IOIOConnection connection = new SerialConnectionFactory().CreateConnection(comPort);

                ObserverConnectionState handlerCaptureState = new ObserverConnectionState();
                MessageObserver         textBoxObserver     = new MessageObserver(this.MessageLog);

                OurImpl_ = new IOIOImpl(connection, new List <IObserverIOIO>()
                {
                    handlerCaptureState, textBoxObserver
                }
                                        );
                OurImpl_.WaitForConnect();

                IConnectedDeviceResponse device = handlerCaptureState.ConnectedDeviceDescription();
                if (device != null)
                {
                    BoardDetails.Text = "Bootloader:" + device.BootloaderId
                                        + "\n" + "Firmware:" + device.FirmwareId
                                        + "\n" + "Hardware: " + device.HardwareId;
                }
                IOIOMessageCommandFactory commandFactory = new IOIOMessageCommandFactory();
                ConfigurePwm(commandFactory);
                ConfigureLed(commandFactory);
                ConfigureDigitalInput(commandFactory);
            }
            else
            {
                //this.Close();
                BoardDetails.Text = "Unable to find an IOIO device";
            }
        }
        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
        }
        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 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());
        }