protected double CalibrateTimeStamp(double timeStamp)
        {
            //first convert to continuous time stamp
            double calibratedTimeStamp = 0;
            if (LastReceivedTimeStamp > (timeStamp + (65536 * CurrentTimeStampCycle)))
            {
                CurrentTimeStampCycle = CurrentTimeStampCycle + 1;
            }

            LastReceivedTimeStamp = (timeStamp + (65536 * CurrentTimeStampCycle));
            calibratedTimeStamp = LastReceivedTimeStamp / 32768 * 1000;   // to convert into mS
            if (FirstTimeCalTime)
            {
                FirstTimeCalTime = false;
                CalTimeStart = calibratedTimeStamp;
            }
            if (LastReceivedCalibratedTimeStamp != -1)
            {
                double timeDifference = calibratedTimeStamp - LastReceivedCalibratedTimeStamp;
                double clockConstant = 1024;
                if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2R || HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2)
                {
                    clockConstant = 1024;
                }
                else if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER3)
                {
                    clockConstant = 32768;
                }

                double expectedTimeDifference = (1 / SamplingRate) * 1000; //in ms
                double adjustedETD = expectedTimeDifference + (expectedTimeDifference * 0.1);

                //if (timeDifference > (1 / ((clockConstant / ADCRawSamplingRateValue) - 1)) * 1000)
                if (timeDifference > adjustedETD)
                {
                    //calculate the estimated packet loss within that time period
                    int numberOfLostPackets = ((int)Math.Ceiling(timeDifference / expectedTimeDifference))-1;
                    PacketLossCount = PacketLossCount + numberOfLostPackets;
                    //PacketLossCount = PacketLossCount + 1;
                    long mTotalNumberofPackets = (long)((calibratedTimeStamp - CalTimeStart) / (1 / (clockConstant / ADCRawSamplingRateValue) * 1000));
                    mTotalNumberofPackets = (long)((calibratedTimeStamp - CalTimeStart) / expectedTimeDifference);

                    PacketReceptionRate = (double)((mTotalNumberofPackets - PacketLossCount) / (double)mTotalNumberofPackets) * 100;

                    if (PacketReceptionRate < 99)
                    {
                        //System.Console.WriteLine("PRR: " + PacketReceptionRate);
                    }
                }
            }

            EventHandler handler = UICallback;
            if (handler != null)
            {
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_PACKET_RECEPTION_RATE, (object)GetPacketReceptionRate());
                handler(this, newEventArgs);
            }

            LastReceivedCalibratedTimeStamp = calibratedTimeStamp;
            return calibratedTimeStamp - CalTimeStart; // make it start at zero
        }
        protected void Connect()
        {
            if (!IsConnectionOpen())
            {
                try
                {
                    OpenConnection();

                    StopReading = false;
                    ReadThread = new Thread(new ThreadStart(ReadData));
                    ReadThread.Name = "Read Thread for Device: " + DeviceName;
                    ReadThread.Start();
                    // give the shimmer time to make the changes before continuing
                    System.Threading.Thread.Sleep(500);
                    // Read Shimmer Profile
                    if (IsConnectionOpen())
                    {
                        // Set default firmware version values, if there is not response it means that this values remain, and the old firmware version has been detected
                        // The following are the three main identifiers used to identify the firmware version
                        FirmwareIdentifier = 1;
                        FirmwareVersion = 0;
                        FirmwareVersionFullName = "BoilerPlate 0.1.0";
                        FirmwareInternal = 0;

                        WriteBytes(new byte[1] { (byte)PacketTypeShimmer2.GET_FW_VERSION_COMMAND }, 0, 1);
                        System.Threading.Thread.Sleep(200);

                        WriteBytes(new byte[1] { (byte)PacketTypeShimmer2.GET_FW_VERSION_COMMAND }, 0, 1);
                        System.Threading.Thread.Sleep(200);

                        if (FirmwareVersion != 1.2) //Shimmer2r and Shimmer3 commands differ, using FWVersion to determine if its a Shimmer2r for the time being, future revisions of BTStream (Shimmer2r, should update the command to 3F)
                        {
                            WriteBytes(new byte[1] { (byte)PacketTypeShimmer3.GET_SHIMMER_VERSION_COMMAND }, 0, 1);
                        }
                        else
                        {
                            WriteBytes(new byte[1] { (byte)PacketTypeShimmer2.GET_SHIMMER_VERSION_COMMAND }, 0, 1);
                        }
                        System.Threading.Thread.Sleep(400);

                        ReadBlinkLED();

                        if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2R || HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2)
                        {
                            InitializeShimmer2();
                        }
                        else if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER3)
                        {
                            if (GetFirmwareIdentifier() == FW_IDENTIFIER_LOGANDSTREAM)
                            {
                                WriteBatteryFrequency(0);
                                InitializeShimmer3SDBT();
                            }
                            else if (GetFirmwareIdentifier() == FW_IDENTIFIER_BTSTREAM)
                            {
                                WriteBatteryFrequency(0);
                                InitializeShimmer3();
                            }
                        }
                    }
                }
                catch
                {
                    TimerConnect.Stop(); // Enable it
                    StopReading = true;
                    ReadThread = null;
                    SetState(SHIMMER_STATE_NONE);
                    EventHandler handler = UICallback;
                    if (handler != null)
                    {
                        String message = "Unable to connect to specified port";
                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                        handler(this, newEventArgs);
                    }
                }
            }
            else
            {
                TimerConnect.Stop(); // Enable it
                StopReading = true;
                ReadThread = null;
                SetState(SHIMMER_STATE_NONE);
                EventHandler handler = UICallback;
                if (handler != null)
                {
                    String message = "Unable to connect to specified port";
                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                    handler(this, newEventArgs);
                }
            }
        }
        public void ReadData()
        {
            List<byte> buffer = new List<byte>();
            int i;
            byte[] bufferbyte;
            List<byte> dataByte;
            ObjectCluster objectCluster;
            FlushInputConnection();
            KeepObjectCluster = null;

            while (!StopReading)
            {
                try
                {
                    byte b = (byte)ReadByte();
                    if (ShimmerState == SHIMMER_STATE_STREAMING)
                    {

                        switch (b)
                        {
                            case (byte)PacketTypeShimmer2.DATA_PACKET: //Shimmer3 has the same value
                                if (IsFilled)
                                {
                                    dataByte = new List<byte>();
                                    for (i = 0; i < PacketSize; i++)
                                    {
                                        dataByte.Add((byte)ReadByte());
                                    }

                                    objectCluster = BuildMsg(dataByte);

                                    if (KeepObjectCluster != null)
                                    {
                                        //ObjectClusterBuffer.Add(KeepObjectCluster); // dont need this if not storing packets in buffer
                                    }

                                    // check if there was a previously received packet, if there is send that, as it is a packet without error (zero-zero test), each packet starts with zero
                                    if (KeepObjectCluster != null)
                                    {
                                        //Check the time stamp
                                        if (mEnableTimeStampAlignmentCheck)
                                        {
                                            if (packetTimeStampChecker(objectCluster.RawTimeStamp, KeepObjectCluster.RawTimeStamp))
                                            {
                                                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_DATA_PACKET, (object)KeepObjectCluster);
                                                OnNewEvent(newEventArgs);
                                            }
                                            else
                                            {
                                                System.Console.WriteLine("Throwing Packet");
                                                KeepObjectCluster = null;
                                                ReadByte();
                                            }

                                        }
                                        else
                                        {
                                            CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_DATA_PACKET, (object)KeepObjectCluster);
                                            OnNewEvent(newEventArgs);
                                        }
                                        //
                                        //packetTimeStampChecker(objectCluster.RawTimeStamp, KeepObjectCluster.RawTimeStamp);
                                        //CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_DATA_PACKET, (object)KeepObjectCluster);
                                        //OnNewEvent(newEventArgs);

                                    }
                                    KeepObjectCluster = objectCluster;

                                    buffer.Clear();
                                }
                                break;
                            case (byte)PacketTypeShimmer2.ACK_COMMAND:
                                //Since the ack always proceeds the instreamcmd
                                if (StreamingACKReceived)
                                {

                                    if (GetFirmwareIdentifier() == FW_IDENTIFIER_LOGANDSTREAM)
                                    {
                                        byte c = (byte)ReadByte(); // get the next byte and pass it the ShimmerSDBT, this should be instreamcmd
                                        if (c != (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.INSTREAM_CMD_RESPONSE)
                                        {
                                            KeepObjectCluster = null;
                                        }
                                        else
                                        {
                                            SDBT_switch(c);
                                        }
                                    }
                                    else
                                    {
                                        System.Console.WriteLine("ACK for Command while Streaming Received");
                                    }
                                }
                                else
                                {
                                    System.Console.WriteLine("ACK for Streaming Command Received");
                                    StreamingACKReceived = true;
                                }
                                break;
                            default:
                                System.Console.WriteLine("Misaligned ByteStream Detected");
                                // If it gets here means the previous packet is invalid so make it null so it wont be added to the buffer
                                KeepObjectCluster = null;
                                break;
                        }
                    }
                    else //connected but not streaming
                    {
                        switch (b)
                        {
                            case (byte)PacketTypeShimmer2.DATA_PACKET:  //Read bytes but do nothing with them
                                if (IsFilled)
                                {
                                    dataByte = new List<byte>();
                                    for (i = 0; i < PacketSize; i++)
                                    {
                                        dataByte.Add((byte)ReadByte());
                                    }
                                    buffer.Clear();
                                }
                                break;
                            case (byte)PacketTypeShimmer2.INQUIRY_RESPONSE:
                                if (ShimmerState != SHIMMER_STATE_CONNECTED)
                                {
                                    SetState(SHIMMER_STATE_CONNECTED);
                                }
                                if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2 || HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER2R)
                                {
                                    for (i = 0; i < 5; i++)
                                    {
                                        // get Sampling rate, accel range, config setup byte0, num chans and buffer size
                                        buffer.Add((byte)ReadByte());
                                    }
                                    for (i = 0; i < (int)buffer[3]; i++)
                                    {
                                        // read each channel type for the num channels
                                        buffer.Add((byte)ReadByte());
                                    }
                                    InterpretInquiryResponseShimmer2(buffer);
                                }
                                else if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER3)
                                {
                                    for (i = 0; i < 8; i++)
                                    {
                                        // get Sampling rate, accel range, config setup byte0, num chans and buffer size
                                        buffer.Add((byte)ReadByte());
                                    }
                                    for (i = 0; i < (int)buffer[6]; i++)
                                    {
                                        // read each channel type for the num channels
                                        buffer.Add((byte)ReadByte());
                                    }
                                    InterpretInquiryResponseShimmer3(buffer);
                                }
                                buffer.Clear();
                                break;
                            case (byte)PacketTypeShimmer2.SAMPLING_RATE_RESPONSE:
                                if (HardwareVersion == (int)ShimmerBluetooth.ShimmerVersion.SHIMMER3)
                                {
                                    int value = 0;
                                    value = (int)ReadByte();
                                    value += (((int)ReadByte() << 8) & 0xFF00);
                                    ADCRawSamplingRateValue = value;
                                    SamplingRate = (double)32768 / ADCRawSamplingRateValue;
                                }
                                else
                                {
                                    ADCRawSamplingRateValue = ReadByte();
                                    SamplingRate = (double)1024 / ADCRawSamplingRateValue;
                                }

                                break;
                            case (byte)PacketTypeShimmer2.ACCEL_RANGE_RESPONSE:
                                SetAccelRange(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer3.ACCEL_SAMPLING_RATE_RESPONSE:
                                SetAccelSamplingRate(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer3.MPU9150_GYRO_RANGE_RESPONSE:
                                SetGyroRange(ReadByte());
                                break;
                            case(byte) PacketTypeShimmer3.BAUD_RATE_COMMAND_RESPONSE:
                                SetBaudRate(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer3.DETECT_EXPANSION_BOARD_RESPONSE:
                                // 2 byte response, only need byte 2nd byte
                                byte NumBytes;
                                NumBytes = (byte)ReadByte();
                                // size of byte array to read is NumBytes bytes
                                ExpansionDetectArray = new byte[NumBytes];
                                for (int p = 0; p < NumBytes; p++)
                                {
                                    ExpansionDetectArray[p] = (byte)ReadByte();
                                }
                                if (ExpansionDetectArray[0] == (int)ExpansionBoardDetectShimmer3.EXPANSION_BRIDGE_AMPLIFIER_PLUS) ExpansionBoard = "Bridge Amplifier+";
                                else if (ExpansionDetectArray[0] == (int)ExpansionBoardDetectShimmer3.EXPANSION_GSR_PLUS) ExpansionBoard = "GSR+";
                                else if (ExpansionDetectArray[0] == (int)ExpansionBoardDetectShimmer3.EXPANSION_PROTO3_MINI) ExpansionBoard = "PROTO3 Mini";
                                else if (ExpansionDetectArray[0] == (int)ExpansionBoardDetectShimmer3.EXPANSION_EXG) ExpansionBoard = "ExG";
                                else if (ExpansionDetectArray[0] == (int)ExpansionBoardDetectShimmer3.EXPANSION_PROTO3_DELUXE) ExpansionBoard = "PROTO3 Deluxe";
                                else ExpansionBoard = "Unknown";

                                if (!ExpansionBoard.Equals("Unknown"))
                                {
                                    ExpansionBoard = string.Format("{0} (SR{1}-{2}.{3})", ExpansionBoard, ExpansionDetectArray[0], ExpansionDetectArray[1], ExpansionDetectArray[2]);
                                }
                                break;
                            case (byte)PacketTypeShimmer2.MAG_GAIN_RESPONSE:
                                SetMagRange(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer2.MAG_SAMPLING_RATE_RESPONSE:
                                SetMagSamplingRate(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer2.CONFIG_SETUP_BYTE0_RESPONSE:
                                SetConfigSetupByte0(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer2.GSR_RANGE_RESPONSE:
                                SetGSRRange(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer3.INTERNAL_EXP_POWER_ENABLE_RESPONSE:
                                SetInternalExpPower(ReadByte());
                                break;
                            case (byte)PacketTypeShimmer2.ACK_COMMAND:
                                if (mWaitingForStartStreamingACK)
                                {
                                    SetState(SHIMMER_STATE_STREAMING);
                                    mWaitingForStartStreamingACK = false;
                                }
                                break;
                            case (byte)PacketTypeShimmer2.ACCEL_CALIBRATION_RESPONSE:
                                // size is 21 bytes
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.ACCEL_CALIBRATION_RESPONSE);
                                break;
                            case (byte)PacketTypeShimmer2.GYRO_CALIBRATION_RESPONSE:
                                // size is 21 bytes
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.GYRO_CALIBRATION_RESPONSE);
                                break;
                            case (byte)PacketTypeShimmer2.MAG_CALIBRATION_RESPONSE:
                                // size is 21 bytes
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.MAG_CALIBRATION_RESPONSE);
                                break;
                            case (byte)PacketTypeShimmer2.ALL_CALIBRATION_RESPONSE:
                                //Retrieve Accel
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();
                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.ACCEL_CALIBRATION_RESPONSE);

                                //Retrieve Gyro
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.GYRO_CALIBRATION_RESPONSE);

                                //Retrieve Mag
                                bufferbyte = new byte[21];
                                for (int p = 0; p < 21; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer2.MAG_CALIBRATION_RESPONSE);
                                if (HardwareVersion != (int)ShimmerBluetooth.ShimmerVersion.SHIMMER3)
                                {
                                    //Retrieve EMG n ECG
                                    bufferbyte = new byte[12];
                                    for (int p = 0; p < 12; p++)
                                    {
                                        bufferbyte[p] = (byte)ReadByte();

                                    }
                                    if (bufferbyte[0] == 255 && bufferbyte[1] == 255 && bufferbyte[2] == 255 && bufferbyte[3] == 255)
                                    {
                                        DefaultEMGParams = true;
                                    }
                                    else
                                    {
                                        OffsetEMG = (double)((bufferbyte[0] & 0xFF) << 8) + (bufferbyte[1] & 0xFF);
                                        GainEMG = (double)((bufferbyte[2] & 0xFF) << 8) + (bufferbyte[3] & 0xFF);
                                        DefaultEMGParams = false;
                                    }
                                    if (bufferbyte[4] == 255 && bufferbyte[5] == 255 && bufferbyte[6] == 255 && bufferbyte[7] == 255)
                                    {
                                        DefaultECGParams = true;
                                    }
                                    else
                                    {
                                        OffsetECGLALL = (double)((bufferbyte[4] & 0xFF) << 8) + (bufferbyte[5] & 0xFF);
                                        GainECGLALL = (double)((bufferbyte[6] & 0xFF) << 8) + (bufferbyte[7] & 0xFF);
                                        OffsetECGRALL = (double)((bufferbyte[8] & 0xFF) << 8) + (bufferbyte[9] & 0xFF);
                                        GainECGRALL = (double)((bufferbyte[10] & 0xFF) << 8) + (bufferbyte[11] & 0xFF);
                                        DefaultECGParams = false;
                                    }
                                }
                                else
                                {
                                    //Retrieve Digital Accel Cal Paramters if Shimmer 3
                                    bufferbyte = new byte[21];
                                    for (int p = 0; p < 21; p++)
                                    {
                                        bufferbyte[p] = (byte)ReadByte();

                                    }
                                    RetrieveKinematicCalibrationParametersFromPacket(bufferbyte, (byte)PacketTypeShimmer3.WR_ACCEL_CALIBRATION_RESPONSE);
                                }

                                break;
                            case (byte)PacketTypeShimmer3.BMP180_CALIBRATION_COEFFICIENTS_RESPONSE:
                                bufferbyte = new byte[22];
                                for (int p = 0; p < 22; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();
                                }
                                AC1 = Calculatetwoscomplement((int)((int)(bufferbyte[1] & 0xFF) + ((int)(bufferbyte[0] & 0xFF) << 8)), 16);
                                AC2 = Calculatetwoscomplement((int)((int)(bufferbyte[3] & 0xFF) + ((int)(bufferbyte[2] & 0xFF) << 8)), 16);
                                AC3 = Calculatetwoscomplement((int)((int)(bufferbyte[5] & 0xFF) + ((int)(bufferbyte[4] & 0xFF) << 8)), 16);
                                AC4 = (int)((int)(bufferbyte[7] & 0xFF) + ((int)(bufferbyte[6] & 0xFF) << 8));
                                AC5 = (int)((int)(bufferbyte[9] & 0xFF) + ((int)(bufferbyte[8] & 0xFF) << 8));
                                AC6 = (int)((int)(bufferbyte[11] & 0xFF) + ((int)(bufferbyte[10] & 0xFF) << 8));
                                B1 = Calculatetwoscomplement((int)((int)(bufferbyte[13] & 0xFF) + ((int)(bufferbyte[12] & 0xFF) << 8)), 16);
                                B2 = Calculatetwoscomplement((int)((int)(bufferbyte[15] & 0xFF) + ((int)(bufferbyte[14] & 0xFF) << 8)), 16);
                                MB = Calculatetwoscomplement((int)((int)(bufferbyte[17] & 0xFF) + ((int)(bufferbyte[16] & 0xFF) << 8)), 16);
                                MC = Calculatetwoscomplement((int)((int)(bufferbyte[19] & 0xFF) + ((int)(bufferbyte[18] & 0xFF) << 8)), 16);
                                MD = Calculatetwoscomplement((int)((int)(bufferbyte[21] & 0xFF) + ((int)(bufferbyte[20] & 0xFF) << 8)), 16);
                                break;
                            case (byte)PacketTypeShimmer2.BLINK_LED_RESPONSE:
                                bufferbyte = new byte[1];
                                bufferbyte[0] = (byte)ReadByte();
                                CurrentLEDStatus = bufferbyte[0];
                                break;
                            case (byte)PacketTypeShimmer2.FW_VERSION_RESPONSE:
                                // size is 21 bytes
                                bufferbyte = new byte[6];
                                for (int p = 0; p < 6; p++)
                                {
                                    bufferbyte[p] = (byte)ReadByte();

                                }
                                FirmwareIdentifier = ((double)((bufferbyte[1] & 0xFF) << 8) + (double)(bufferbyte[0] & 0xFF));
                                FirmwareVersion = ((double)((bufferbyte[3] & 0xFF) << 8) + (double)(bufferbyte[2] & 0xFF) + ((double)((bufferbyte[4] & 0xFF)) / 10));
                                FirmwareInternal = ((int)(bufferbyte[5] & 0xFF));
                                FirmwareMajor = (int)((bufferbyte[3] & 0xFF) << 8) + (int)(bufferbyte[2] & 0xFF);
                                FirmwareMinor = (int)(bufferbyte[4] & 0xFF);

                                string fw_id = "";
                                if (FirmwareIdentifier == 1)
                                    fw_id = "BtStream ";
                                else if (FirmwareIdentifier == 3)
                                    fw_id = "LogAndStream ";
                                else
                                    fw_id = "Unknown ";
                                string temp = fw_id + FirmwareVersion.ToString("0.0") + "." + FirmwareInternal.ToString();
                                FirmwareVersionFullName = temp;
                                SetCompatibilityCode();
                                UpdateBasedOnCompatibilityCode();
                                break;
                            case (byte)PacketTypeShimmer2.GET_SHIMMER_VERSION_RESPONSE:
                                bufferbyte = new byte[1];
                                bufferbyte[0] = (byte)ReadByte();
                                HardwareVersion = bufferbyte[0];
                                // set default calibration parameters
                                SetCompatibilityCode();
                                UpdateBasedOnCompatibilityCode();
                                break;
                            case (byte)PacketTypeShimmer3.EXG_REGS_RESPONSE:
                                System.Console.WriteLine("EXG r r" + ChipID);
                                if (ChipID == 1)
                                {
                                    ReadByte();
                                    Exg1RegArray[0] = (byte)ReadByte();
                                    Exg1RegArray[1] = (byte)ReadByte();
                                    Exg1RegArray[2] = (byte)ReadByte();
                                    Exg1RegArray[3] = (byte)ReadByte();
                                    Exg1RegArray[4] = (byte)ReadByte();
                                    Exg1RegArray[5] = (byte)ReadByte();
                                    Exg1RegArray[6] = (byte)ReadByte();
                                    Exg1RegArray[7] = (byte)ReadByte();
                                    Exg1RegArray[8] = (byte)ReadByte();
                                    Exg1RegArray[9] = (byte)ReadByte();
                                }
                                else
                                {
                                    ReadByte();
                                    Exg2RegArray[0] = (byte)ReadByte();
                                    Exg2RegArray[1] = (byte)ReadByte();
                                    Exg2RegArray[2] = (byte)ReadByte();
                                    Exg2RegArray[3] = (byte)ReadByte();
                                    Exg2RegArray[4] = (byte)ReadByte();
                                    Exg2RegArray[5] = (byte)ReadByte();
                                    Exg2RegArray[6] = (byte)ReadByte();
                                    Exg2RegArray[7] = (byte)ReadByte();
                                    Exg2RegArray[8] = (byte)ReadByte();
                                    Exg2RegArray[9] = (byte)ReadByte();
                                }

                                break;

                            default:
                                // This is to extend log and stream functionality
                                if (GetFirmwareIdentifier() == FW_IDENTIFIER_LOGANDSTREAM)
                                {
                                    SDBT_switch(b);
                                }
                                else
                                {
                                    System.Console.WriteLine("?");
                                }
                                break;
                        }
                    }

                }

                catch (System.TimeoutException)
                {
                    //
                    if (ShimmerState == SHIMMER_STATE_STREAMING)
                    {
                        System.Console.WriteLine("Timeout Streaming");
                        StreamTimeOutCount++;
                        if (StreamTimeOutCount == 10)
                        {
                            CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, "Connection lost" );
                            OnNewEvent(newEventArgs);
                            Disconnect();
                        }
                    }

                }
                catch (System.InvalidOperationException)
                {

                }
                catch (System.IO.IOException)
                {

                }

            }

            // only stop reading when disconnecting, so disconnect serial port here too
            CloseConnection();
        }
        public void SetState(int state)
        {
            if (ShimmerState == SHIMMER_STATE_CONNECTED) {

            }

            Boolean stateChanging=false;
            if (ShimmerState!=state){
                stateChanging=true;
            }

            ShimmerState = state;
            /*EventHandler handler = UICallback;
            if (handler != null)
            {
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_STATE_CHANGE, (object)state);
                handler(this, newEventArgs);
            }
             */
            if (stateChanging)
            {
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_STATE_CHANGE, (object)state);
                OnNewEvent(newEventArgs);
            }
        }
Beispiel #5
0
        public void SdConfigWrite()
        {
            string drivePath = "";
            string filePath = "";
            DriveInfo[] drives = DriveInfo.GetDrives();
            int i = 0, sdcardSeq = 0, totalRemovable = 0;

            foreach (DriveInfo drive in drives)
            {
                bool dready = false;
                DriveType dtype;
                dready = drive.IsReady;
                dtype = drive.DriveType;

                if (dready && (dtype == (DriveType)2))
                {
                    sdcardSeq = i;
                    totalRemovable++;
                }
                i++;
            }

            if (totalRemovable == 1)
            {
                drivePath = drives[sdcardSeq].Name;
            }
            else if (totalRemovable > 1)
            {
                String message = totalRemovable + "Two or more removable devices are detected. Please choose the intended Shimmer.";
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_EXTRA_REMOVABLE_DEVICES_DETECTED);
                OnNewEvent(newEventArgs);
                drivePath = TempDrivePath;
            }
            else
            {
                String message = "No removable storage device is found.";
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_ERROR);
                OnNewEvent(newEventArgs);
                return;
            }
            filePath = drivePath + "sdlog.cfg";
            // now file path is found. Read from existing sdlog.cfg file.
            System.IO.StreamWriter file = null;

            file = new System.IO.StreamWriter(filePath, false);

            file.WriteLine("accel=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_A_ACCEL) == 0 ? 0 : 1));//SensorBitmapShimmer3.SensorAAccel
            file.WriteLine("gyro=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_MPU9150_GYRO) == 0 ? 0 : 1));
            file.WriteLine("mag=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_LSM303DLHC_MAG) == 0 ? 0 : 1));
            file.WriteLine("exg1_24bit=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXG1_24BIT) == 0 ? 0 : 1));
            file.WriteLine("exg2_24bit=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXG2_24BIT) == 0 ? 0 : 1));
            file.WriteLine("gsr=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_GSR) == 0 ? 0 : 1));
            file.WriteLine("extch7=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXT_A7) == 0 ? 0 : 1));
            file.WriteLine("extch6=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXT_A6) == 0 ? 0 : 1));
            file.WriteLine("br_amp=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_BRIDGE_AMP) == 0 ? 0 : 1));
            file.WriteLine("vbat=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_VBATT) == 0 ? 0 : 1));
            file.WriteLine("accel_d=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_D_ACCEL) == 0 ? 0 : 1));
            file.WriteLine("extch15=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXT_A15) == 0 ? 0 : 1));
            file.WriteLine("intch1=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_INT_A1) == 0 ? 0 : 1));
            file.WriteLine("intch12=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_INT_A12) == 0 ? 0 : 1));
            file.WriteLine("intch13=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_INT_A13) == 0 ? 0 : 1));
            file.WriteLine("intch14=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_INT_A14) == 0 ? 0 : 1));
            file.WriteLine("accel_mpu=" + ((GetEnabledSensors() & (int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuAccel) == 0 ? 0 : 1));
            file.WriteLine("mag_mpu=" + ((GetEnabledSensors() & (int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuMag) == 0 ? 0 : 1));
            file.WriteLine("exg1_16bit=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXG1_16BIT) == 0 ? 0 : 1));
            file.WriteLine("exg2_16bit=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_EXG2_16BIT) == 0 ? 0 : 1));
            file.WriteLine("pres_bmp180=" + ((GetEnabledSensors() & (int)SensorBitmapShimmer3.SENSOR_BMP180_PRESSURE) == 0 ? 0 : 1));
            double file_sample_rate = (GetSamplingRate());
            file.WriteLine("sample_rate=" + string.Format("{0:N2}", file_sample_rate));
            file.WriteLine("mg_internal_rate=" + GetMagSamplingRate());
            file.WriteLine("mg_range=" + GetMagRange());
            file.WriteLine("acc_internal_rate=" + GetAccelSamplingRate());
            file.WriteLine("accel_mpu_range=" + GetMpu9150AccelRange());
            file.WriteLine("pres_bmp180_prec=" + GetPressureResolution());
            file.WriteLine("gs_range=" + GetGSRRange());
            file.WriteLine("exp_power=" + (GetExpPower() ? 1 : 0));
            file.WriteLine("gyro_range=" + GetGyroRange());
            file.WriteLine("gyro_samplingrate=" + GetMpu9150SamplingRate());
            file.WriteLine("acc_range=" + GetAccelRange());
            file.WriteLine("acc_lpm=" + GetAccelLPBit());
            file.WriteLine("acc_hrm=" + GetAccelHRBit());
            file.WriteLine("user_button_enable=" + (GetUserButton() ? 1 : 0));
            file.WriteLine("iammaster=" + (GetIAmMaster() ? 1 : 0));
            file.WriteLine("sync=" + (GetSync() ? 1 : 0));
            file.WriteLine("singletouch=" + (GetSingleTouch() ? 1 : 0));
            file.WriteLine("tcxo=" + (GetTcxo() ? 1 : 0));
            file.WriteLine("interval=" + GetInterval());
            file.WriteLine("center=" + GetCenter());
            file.WriteLine("myid=" + GetMyID());
            file.WriteLine("Nshimmer=" + GetNshimmer());
            file.WriteLine("shimmername=" + GetShimmerName());
            file.WriteLine("experimentid=" + GetExperimentID());
            file.WriteLine("configtime=" + GetConfigTime());
            file.WriteLine("EXG_ADS1292R_1_CONFIG1=" + Exg1RegArray[0].ToString());
            file.WriteLine("EXG_ADS1292R_1_CONFIG2=" + Exg1RegArray[1].ToString());
            file.WriteLine("EXG_ADS1292R_1_LOFF=" + Exg1RegArray[2].ToString());
            file.WriteLine("EXG_ADS1292R_1_CH1SET=" + Exg1RegArray[3].ToString());
            file.WriteLine("EXG_ADS1292R_1_CH2SET=" + Exg1RegArray[4].ToString());
            file.WriteLine("EXG_ADS1292R_1_RLD_SENS=" + Exg1RegArray[5].ToString());
            file.WriteLine("EXG_ADS1292R_1_LOFF_SENS=" + Exg1RegArray[6].ToString());
            file.WriteLine("EXG_ADS1292R_1_LOFF_STAT=" + Exg1RegArray[7].ToString());
            file.WriteLine("EXG_ADS1292R_1_RESP1=" + Exg1RegArray[8].ToString());
            file.WriteLine("EXG_ADS1292R_1_RESP2=" + Exg1RegArray[9].ToString());
            file.WriteLine("EXG_ADS1292R_2_CONFIG1=" + Exg2RegArray[0].ToString());
            file.WriteLine("EXG_ADS1292R_2_CONFIG2=" + Exg2RegArray[1].ToString());
            file.WriteLine("EXG_ADS1292R_2_LOFF=" + Exg2RegArray[2].ToString());
            file.WriteLine("EXG_ADS1292R_2_CH1SET=" + Exg2RegArray[3].ToString());
            file.WriteLine("EXG_ADS1292R_2_CH2SET=" + Exg2RegArray[4].ToString());
            file.WriteLine("EXG_ADS1292R_2_RLD_SENS=" + Exg2RegArray[5].ToString());
            file.WriteLine("EXG_ADS1292R_2_LOFF_SENS=" + Exg2RegArray[6].ToString());
            file.WriteLine("EXG_ADS1292R_2_LOFF_STAT=" + Exg2RegArray[7].ToString());
            file.WriteLine("EXG_ADS1292R_2_RESP1=" + Exg2RegArray[8].ToString());
            file.WriteLine("EXG_ADS1292R_2_RESP2=" + Exg2RegArray[9].ToString());

            file.Close();
            return;
        }
Beispiel #6
0
        public override void StartStreamingandLog()
        {
            KeepObjectCluster = null;
            if (IsConnectionOpen())
            {
                if (ShimmerState == SHIMMER_STATE_CONNECTED)
                {
                    if (IsFilled)
                    {
                        StreamingACKReceived = false;
                        LastReceivedTimeStamp = 0;
                        CurrentTimeStampCycle = 0;
                        LastReceivedCalibratedTimeStamp = -1;
                        FirstTimeCalTime = true;
                        PacketLossCount = 0;
                        PacketReceptionRate = 100;
                        KeepObjectCluster = null; //This is important and is required!
                        OrientationAlgo = null;
                        if (GetFirmwareIdentifier() == 3)
                        {
                            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_STATUS_COMMAND }, 0, 1);
                            System.Threading.Thread.Sleep(500);
                        }
                        SetSdDir("");
                        if (CurrentDockStatus)
                        {
                            String message = "Streaming only mode. \nShimmer on dock, SD mode not accessible.";
                            CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_WARNING);
                            OnNewEvent(newEventArgs);
                            isLogging = false;
                        }
                        else
                        {
                            isLogging = true;
                        }

                        // btsd changes 2
                        if (GetFirmwareIdentifier() == 3)
                        {
                            System.Console.WriteLine("ShimmerLOG: Send START SDBT CMD");
                            //SetState(SHIMMER_STATE_STREAMING);
                            mWaitingForStartStreamingACK = true;
                            System.Threading.Thread.Sleep(300);
                            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.START_SDBT_COMMAND }, 0, 1);
                            //System.Threading.Thread.Sleep(1500);
                            /*
                            if (isLogging)
                            {
                                WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_DIR_COMMAND }, 0, 1);
                                int i = 11;
                                while (((i--) > 1) && (GetSdDir() == ""))
                                {
                                    System.Threading.Thread.Sleep(200);
                                }
                                if (i == 0)
                                {
                                    // btsd changes 2
                                    System.Console.WriteLine("GetSdDir(): " + GetSdDir());
                                    String message = "BTStream + SDLog, Current SDLog Directory : Could not read the directory name. Pos1.";
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                    OnNewEvent(newEventArgs);
                                    //PControlForm.ChangeStatusLabel("BTStream + SDLog, Current SDLog Directory : Could not read the directory name.");

                                }
                            }*/

                        }
                        else
                        {
                            mWaitingForStartStreamingACK = true;
                            WriteBytes(new byte[1] { (byte)PacketTypeShimmer2.START_STREAMING_COMMAND }, 0, 1);
                        }

                    }
                    else
                    {
                        String message = "Failed to read configuration information from shimmer. Please ensure correct shimmer is connected";
                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_WARNING);
                        OnNewEvent(newEventArgs);
                    }
                }
                else
                {
                    String message = "No serial port is open";
                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_WARNING);
                    OnNewEvent(newEventArgs);
                }
            }
        }
Beispiel #7
0
        public override void SDBT_switch(byte b)
        {
            List<byte> buffer = new List<byte>();
            int i;
            if (GetState() == ShimmerBluetooth.SHIMMER_STATE_STREAMING)
            {
                switch (b)
                {
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.INSTREAM_CMD_RESPONSE: int inStreamCMD = ReadByte();
                        System.Console.WriteLine("In Stream CMD Response");
                        if (inStreamCMD == (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.STATUS_RESPONSE)
                        {
                            //STATUS: 0|0|0|STREAMING|LOGGING|SELFCMD|SENSING|DOCKED
                            int bufferint = ReadByte();
                            bool docked = (bufferint & 0x01) == 1;
                            bool sensing = ((bufferint >> 1) & 0x01) == 1;
                            bool selfcmd = ((bufferint >> 2) & 0x01) == 1;
                            bool logging = ((bufferint >> 3) & 0x01) == 1;
                            bool streaming = ((bufferint >> 4) & 0x01) == 1;
                            System.Console.WriteLine("CMD Response; " + "Docked:" + docked + ",Sensing:" + sensing);

                            //AS is this ok?
                            isLogging = logging;
                            if (streaming)
                            {
                                SetState(ShimmerBluetooth.SHIMMER_STATE_STREAMING);
                            }

                            if (CurrentDockStatus != docked)
                            {
                                CurrentDockStatus = docked;
                                if (docked && isLogging)
                                {
                                    String message = "Shimmer docking detected.\nStop writing to SD card.";
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_WARNING);
                                    OnNewEvent(newEventArgs);

                                    /*if (GetSdDir() != "")
                                        this.Invoke(new Action(() => { PChangeStatusLabel("BT Streaming. Last SDLog Directory : " + pProfile.GetSdDir()); }));
                                    else
                                        this.Invoke(new Action(() => { PChangeStatusLabel("BT Streaming."); }));*/
                                    isLogging = false;
                                }
                            }
                            if (CurrentSensingStatus != sensing)
                            {
                                CurrentSensingStatus = sensing;
                            }
                            if (selfcmd) //fw does this, and sw is forced to do the same
                            {
                                if (CurrentSensingStatus && (GetState() != ShimmerBluetooth.SHIMMER_STATE_STREAMING))// to start sensing
                                {
                                    // btsd changes 2
                                    //PControlForm.buttonStart_Click1();
                                    System.Console.WriteLine("Shimmer Self CMD");
                                    //StartStreamingandLog();
                                }
                                else if (!CurrentSensingStatus && (GetState() == ShimmerBluetooth.SHIMMER_STATE_STREAMING))// to stop sensing
                                {
                                    if (isLogging && (GetSdDir() != ""))
                                    {
                                        // btsd changes 2
                                        String message = "Stopped. Last SDLog Directory : " + GetSdDir();
                                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                        OnNewEvent(newEventArgs);

                                    }
                                    else
                                    {

                                        String message = "Stopped.";
                                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                        OnNewEvent(newEventArgs);
                                        //PControlForm.ChangeStatusLabel("Stopped.");
                                        //this.Invoke(new Action(() => { PChangeStatusLabel("Stopped."); }));
                                    }
                                    SetSdDir("");
                                    if (IsConnectionOpen())
                                    {
                                        SetState(SHIMMER_STATE_CONNECTED);// = false;
                                        isLogging = false;
                                        //PChangeStatusLabel("Stopped");
                                        /*
                                        while (SerialPort.BytesToRead != 0)
                                        {
                                            ReadByte();
                                        }*/
                                        FlushInputConnection();
                                    }
                                }
                            }

                            SetDataReceived(true);
                        }
                        else if (inStreamCMD == (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.DIR_RESPONSE)
                        {
                            buffer.Clear();
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            SetSdDir(System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            System.Console.WriteLine("SetSdDir2: " + System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            System.Console.WriteLine("GetSdDir2: " + GetSdDir());
                            if (GetSdDir().Contains("data") &&
                                GetSdDir().Contains(GetShimmerName()) &&
                                GetSdDir().Contains(GetExperimentID()) &&
                                GetSdDir().Contains(GetConfigTime().ToString()))
                            {
                            }
                            else
                            {
                                SetSdDir("");
                            }

                            if (isLogging)
                            {
                                if (GetSdDir() != "")
                                {   String message = "BTStream + SDLog, Current SDLog Directory : " + GetSdDir();
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                    OnNewEvent(newEventArgs);
                                }
                                else
                                {
                                    String message = "BTStream + SDLog, Current SDLog Directory : Could not read the directory name.";
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                    OnNewEvent(newEventArgs);
                                }
                            }
                            SetDataReceived(true);
                        }
                        buffer.Clear();
                        SetDataReceived(true);
                        break;

                    default:
                        KeepObjectCluster = null;
                        break;
                }
            }
            else
            {
                switch (b)
                {
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.TRIAL_CONFIG_RESPONSE:
                        for (i = 0; i < 3; i++)
                        {
                            // get 2 bytes trial config and 1 byte interval
                            buffer.Add((byte)ReadByte());
                        }
                        fillTrialShimmer3(buffer);
                        buffer.Clear();
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.CENTER_RESPONSE:
                        {
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            SetCenter(System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            buffer.Clear();
                        }
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.SHIMMERNAME_RESPONSE:
                        {
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            System.Console.WriteLine("ShimmerName: " + System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            SetShimmerName(System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            buffer.Clear();
                        }
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.EXPID_RESPONSE:
                        {
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            System.Console.WriteLine("ExpID: " + System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            SetExperimentID(System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            buffer.Clear();
                        }
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.CONFIGTIME_RESPONSE:
                        {
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            try
                            {
                                System.Console.WriteLine("Config Time: " + System.Text.Encoding.Default.GetString(buffer.ToArray()));
                                SetConfigTime(Convert.ToInt64(System.Text.Encoding.Default.GetString(buffer.ToArray())));
                            }
                            catch (FormatException)
                            {
                                SetConfigTime(0);
                            }
                            buffer.Clear();
                        }
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.MYID_RESPONSE:
                        SetMyID(ReadByte());
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.NSHIMMER_RESPONSE:
                        SetNshimmer(ReadByte());
                        SetDataReceived(true);
                        break;
                    case (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.INSTREAM_CMD_RESPONSE: int inStreamCMD = ReadByte();
                        System.Console.WriteLine("CMD Response");
                        if (inStreamCMD == (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.STATUS_RESPONSE)
                        {
                            //STATUS: 0|0|0|0|0|SELFCMD|SENSING|DOCKED
                            int bufferint = ReadByte();
                            bool docked = (bufferint & 0x01) == 1;
                            bool sensing = ((bufferint >> 1) & 0x01) == 1;
                            bool selfcmd = ((bufferint >> 2) & 0x01) == 1;
                            bool logging = ((bufferint >> 3) & 0x01) == 1;
                            bool streaming = ((bufferint >> 4) & 0x01) == 1;
                            System.Console.WriteLine("CMD Response; " + "Docked:" + docked+ ",Sensing:" + sensing);
                            if (CurrentDockStatus != docked)
                            {
                                CurrentDockStatus = docked;
                                if (docked && isLogging)
                                {

                                    String message = "Shimmer docking detected.\nStop writing to SD card.";
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_WARNING);
                                    OnNewEvent(newEventArgs);
                                }
                            }
                            if (CurrentSensingStatus != sensing)
                            {
                                CurrentSensingStatus = sensing;
                            }
                            if (selfcmd) //fw does this, and sw is forced to do the same
                            {
                                if (CurrentSensingStatus && (GetState() != ShimmerBluetooth.SHIMMER_STATE_STREAMING))// to start sensing
                                {
                                    System.Console.WriteLine("S Stream 2");
                                    //StartStreamingandLog();
                                }
                                else if (!CurrentSensingStatus && (GetState() == ShimmerBluetooth.SHIMMER_STATE_STREAMING))// to stop sensing
                                {
                                    if (isLogging && (GetSdDir() != ""))
                                    {

                                        String message = "Stopped. Last SDLog Directory : " + GetSdDir();
                                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);

                                        OnNewEvent(newEventArgs);

                                    }
                                    else
                                    {
                                        String message = "Stopped.";
                                        CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                        OnNewEvent(newEventArgs);

                                    }
                                    SetSdDir("");
                                    if (IsConnectionOpen())
                                    {
                                        SetState(SHIMMER_STATE_CONNECTED);// = false;
                                        isLogging = false;
                                        //PChangeStatusLabel("Stopped");
                                        /*while (SerialPort.BytesToRead != 0)
                                        {
                                            ReadByte();
                                        }*/
                                        FlushInputConnection();
                                    }
                                    // todo: check button status

                                }
                            }

                            SetDataReceived(true);
                        }
                        else if (inStreamCMD == (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.DIR_RESPONSE)
                        {
                            buffer.Clear();
                            int len = ReadByte();
                            for (i = 0; i < len; i++)
                            {
                                buffer.Add((byte)ReadByte());
                            }
                            //buffer.Add((byte)'\0');
                            SetSdDir(System.Text.Encoding.Default.GetString(buffer.ToArray()));
                            if (GetSdDir().Contains("data") &&
                                GetSdDir().Contains(GetShimmerName()) &&
                                GetSdDir().Contains(GetExperimentID()) &&
                                GetSdDir().Contains(GetConfigTime().ToString()))
                            {
                            }
                            else
                            {
                                SetSdDir("");
                            }

                            if (GetSdDir() != "")
                            {
                                if (CurrentSensingStatus)
                                {
                                    String message = "BTStream + SDLog, Current SDLog Directory : " + GetSdDir();
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                    OnNewEvent(newEventArgs);

                                }
                                else
                                {
                                    String message = "BTStream + SDLog, Last Known SDLog Directory : " + GetSdDir();
                                    CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                    OnNewEvent(newEventArgs);

                                }

                            }
                            else
                            {
                                String message = "BTStream + SDLog, Last Known SDLog Directory : Could not read the directory name.";
                                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                                OnNewEvent(newEventArgs);
                            }

                            SetDataReceived(true);
                        }
                        buffer.Clear();
                        SetDataReceived(true);
                        break;

                    default: break;

                }
            }
        }
Beispiel #8
0
        // returns
        // 0    if successful
        // 1    if need InfoMemRead() + SdConfigWrite()
        // -1   if unexpected error happens
        private int SdConfigRead()
        {
            string drivePath = "";
            string filePath = "";
            DriveInfo[] drives = DriveInfo.GetDrives();
            int i = 0, sdcardSeq = 0, totalRemovable = 0;

            foreach (DriveInfo drive in drives)
            {
                bool dready = false;
                DriveType dtype;
                dready = drive.IsReady;
                dtype = drive.DriveType;

                if (dready && (dtype == (DriveType)2))
                {
                    sdcardSeq = i;
                    totalRemovable++;
                }
                i++;
            }

            if (totalRemovable == 1)
            {
                drivePath = drives[sdcardSeq].Name;
            }
            else if (totalRemovable > 1)
            {
                //System.Windows.Forms.
                //Important Change Needed
                //MessageBox.Show(totalRemovable + " removable devices are detected. Please choose the intended Shimmer.", "Message");
                //FolderBrowserDialog fbd = new FolderBrowserDialog();
                //DialogResult result = fbd.ShowDialog();

                //Users should always ensure TempDrivePath is taken care of on the outer class/ui which is called through the method OnMyPropertyChanged
                String message = totalRemovable + "Two or more removable devices are detected. Please choose the intended Shimmer.";
                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message, (int)ShimmerSDBT.ShimmerSDBTMinorIdentifier.MSG_EXTRA_REMOVABLE_DEVICES_DETECTED);
                OnNewEvent(newEventArgs);
                drivePath = TempDrivePath;
            }
            else
            {
                //MessageBox.Show("No SD card was found.", Shimmer.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return -1;
            }
            filePath = drivePath + "sdlog.cfg";

            // now file path is found. Read from existing sdlog.cfg file.
            System.IO.StreamReader file = null;
            int counter = 0;
            string line;

            if (!File.Exists(filePath))
            {
                //MessageBox.Show("Configure file not found. Please connect the intended Shimmer through BlueTooth before further operation.", Shimmer.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return 1;//file not exist, need to read InfoMem
            }
            else//file exists, read here and update app's stored vars
            {
                file = new System.IO.StreamReader(filePath);
                int equals = 0;
                double freq = 0.0;
                byte[] file_sample_rate = new byte[2] { 0, 0 };
                byte[] file_sensors = new byte[3] { 0, 0, 0 };
                byte[] file_trialConfig = new byte[3] { 0, 0, 0 };
                byte[] file_configSetup = new byte[4] { 0, 0, 0, 0 };
                bool centername_set = false;
                SetClockTCXO(0);

                while ((line = file.ReadLine()) != null)
                {
                    counter++;
                    if ((equals = line.IndexOf('=')) == -1)
                        continue;
                    equals++;

                    if (line.Contains("accel="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_A_ACCEL;//Shimmer3.SensorBitmap.SensorAAccel;
                    }
                    else if (line.Contains("gyro="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_MPU9150_GYRO;
                    }
                    else if (line.Contains("mag="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_LSM303DLHC_MAG;
                    }
                    else if (line.Contains("exg1_24bit="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG1_24BIT;
                    }
                    else if (line.Contains("exg2_24bit="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG2_24BIT;
                    }
                    else if (line.Contains("gsr="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_GSR;
                    }
                    else if (line.Contains("extch7="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A7;
                    }
                    else if (line.Contains("extch6="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A6;
                    }
                    else if (line.Contains("vbat="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_VBATT >> 8) & 0xff);
                    }
                    else if (line.Contains("accel_d="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_D_ACCEL >> 8) & 0xff);
                    }
                    else if (line.Contains("extch15="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A15 >> 8) & 0xff);
                    }
                    else if (line.Contains("intch1="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A1 >> 8) & 0xff);
                    }
                    else if (line.Contains("intch12="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A12 >> 8) & 0xff);
                    }
                    else if (line.Contains("intch13="))
                    {
                        if (line[equals] == '1')
                            file_sensors[1] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A13 >> 8) & 0xff);
                    }
                    else if (line.Contains("intch14="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A14 >> 16) & 0xff);
                    }
                    else if (line.Contains("accel_mpu="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuAccel >> 16) & 0xff);//sdbt only
                    }
                    else if (line.Contains("mag_mpu="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuMag >> 16) & 0xff);//sdbt only
                    }
                    else if (line.Contains("exg1_16bit="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG1_16BIT >> 16) & 0xff);
                    }
                    else if (line.Contains("exg2_16bit="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG2_16BIT >> 16) & 0xff);
                    }
                    else if (line.Contains("pres_bmp180="))
                    {
                        if (line[equals] == '1')
                            file_sensors[2] |= (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_BMP180_PRESSURE >> 16) & 0xff);
                    }
                    else if (line.Contains("mag="))
                    {
                        if (line[equals] == '1')
                            file_sensors[0] |= (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_LSM303DLHC_MAG;
                    }
                    else if (line.Contains("sample_rate="))
                        freq = Convert.ToDouble(line.Substring(equals, line.Length - equals));
                    else if (line.Contains("mg_internal_rate="))
                        file_configSetup[2] |= (byte)((Convert.ToInt16(line[equals]) & 0x07) << 2);
                    else if (line.Contains("mg_range="))
                        file_configSetup[2] |= (byte)((Convert.ToInt16(line[equals]) & 0x07) << 5);
                    else if (line.Contains("acc_internal_rate="))
                        file_configSetup[0] |= (byte)((Convert.ToInt16(line[equals]) & 0x0f) << 4);
                    else if (line.Contains("accel_mpu_range="))
                        file_configSetup[3] |= (byte)((Convert.ToInt16(line[equals]) & 0x03) << 6);
                    else if (line.Contains("acc_range="))
                        file_configSetup[0] |= (byte)((Convert.ToInt16(line[equals]) & 0x03) << 2);
                    else if (line.Contains("acc_lpm="))
                        file_configSetup[0] |= (byte)((Convert.ToInt16(line[equals]) & 0x01) << 1);
                    else if (line.Contains("acc_hrm="))
                        file_configSetup[0] |= (byte)((Convert.ToInt16(line[equals]) & 0x01));
                    else if (line.Contains("gs_range="))
                        file_configSetup[3] |= (byte)((Convert.ToInt16(line[equals]) & 0x07) << 1);
                    else if (line.Contains("gyro_samplingrate="))
                        file_configSetup[1] |= (byte)(Convert.ToInt16(line[equals]));
                    else if (line.Contains("gyro_range="))
                        file_configSetup[2] |= (byte)((Convert.ToInt16(line[equals]) & 0x03));
                    else if (line.Contains("pres_bmp180_prec="))
                        file_configSetup[3] |= (byte)((Convert.ToInt16(line[equals]) & 0x03) << 4);
                    else if (line.Contains("user_button_enable="))
                    {
                        if (line[equals] == '1')
                            file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.UserButton;
                    }
                    else if (line.Contains("iammaster="))
                    {
                        if (line[equals] == '1')
                            file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.IAmMaster;
                    }
                    else if (line.Contains("sync="))
                    {
                        if (line[equals] == '1')
                            file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.Sync;
                    }
                    else if (line.Contains("singletouch="))
                    {
                        if (line[equals] == '1')
                            file_trialConfig[1] |= (byte)ShimmerSDBT.TrialConfigBitmap.SingleTouch;
                    }
                    else if (line.Contains("exp_power="))
                    {
                        //if (line.Contains("True"))
                        if (line[equals] == '1')
                            file_trialConfig[1] |= (byte)ShimmerSDBT.TrialConfigBitmap.ExpPower;
                    }
                    else if (line.Contains("tcxo="))
                    {
                        if (line[equals] == '1')
                        {
                            file_trialConfig[1] |= (byte)ShimmerSDBT.TrialConfigBitmap.TCXO;
                            SetClockTCXO(1);
                        }
                    }
                    else if (line.Contains("user_button_enable="))
                    {
                        if (line[equals] == '1')
                            file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.UserButton;
                    }
                    else if (line.Contains("interval="))
                    {
                        try
                        {
                            SetInterval(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                        }
                        catch (FormatException)
                        {
                            SetInterval(0);
                        }
                    }
                    else if (line.Contains("center="))
                    {
                        SetCenter(line.Substring(equals, line.Length - equals));
                        centername_set = true;
                    }
                    else if (line.Contains("myid="))
                    {
                        try
                        {
                            SetMyID(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                        }
                        catch (FormatException)
                        {
                            SetMyID(0);
                        }
                    }
                    else if (line.Contains("Nshimmer="))
                    {
                        try
                        {
                            SetNshimmer(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                        }
                        catch (FormatException)
                        {
                            SetNshimmer(0);
                        }
                    }
                    else if (line.Contains("shimmername="))
                        SetShimmerName(line.Substring(equals, line.Length - equals));
                    else if (line.Contains("experimentid="))
                        SetExperimentID(line.Substring(equals, line.Length - equals));
                    else if (line.Contains("configtime="))
                    {
                        try
                        {
                            SetConfigTime(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                        }
                        catch (FormatException)
                        {
                            SetConfigTime(0);
                        }
                    }
                    else if (line.Contains("EXG_ADS1292R_1_CONFIG1="))
                        Exg1RegArray[0] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_CONFIG2="))
                        Exg1RegArray[1] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_LOFF="))
                        Exg1RegArray[2] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_CH1SET="))
                        Exg1RegArray[3] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_CH2SET="))
                        Exg1RegArray[4] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_RLD_SENS="))
                        Exg1RegArray[5] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_LOFF_SENS="))
                        Exg1RegArray[6] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_LOFF_STAT="))
                        Exg1RegArray[7] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_RESP1="))
                        Exg1RegArray[8] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_1_RESP2="))
                        Exg1RegArray[9] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_CONFIG1="))
                        Exg2RegArray[0] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_CONFIG2="))
                        Exg2RegArray[1] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_LOFF="))
                        Exg2RegArray[2] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_CH1SET="))
                        Exg2RegArray[3] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_CH2SET="))
                        Exg2RegArray[4] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_RLD_SENS="))
                        Exg2RegArray[5] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_LOFF_SENS="))
                        Exg2RegArray[6] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_LOFF_STAT="))
                        Exg2RegArray[7] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_RESP1="))
                        Exg2RegArray[8] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                    else if (line.Contains("EXG_ADS1292R_2_RESP2="))
                        Exg2RegArray[9] = (byte)(Convert.ToInt32(line.Substring(equals, line.Length - equals)));
                }

                file.Close();

                int a = (int)(32768 / freq);
                file_sample_rate[0] = (byte)(a % 256);
                file_sample_rate[1] = (byte)(a / 256);

                // they are sharing adc13,14, so ban them when strain is on
                if ((byte)((byte)file_sensors[1] & (byte)(((int)Shimmer.SensorBitmapShimmer3.SENSOR_BRIDGE_AMP >> 8) & 0xff)) != 0)
                {
                    file_sensors[1] &= (byte)(0xff - (byte)(((int)Shimmer.SensorBitmapShimmer3.SENSOR_INT_A13 >> 8) & 0xff));
                    file_sensors[2] &= (byte)(0xff - (byte)(((int)Shimmer.SensorBitmapShimmer3.SENSOR_INT_A14 >> 16) & 0xff));
                }

                // they are sharing adc1, so ban intch1 when gsr is on
                if ((byte)((byte)file_sensors[0] & (byte)Shimmer.SensorBitmapShimmer3.SENSOR_GSR) != 0)
                    file_sensors[1] &= (byte)(0xff - (byte)(((int)Shimmer.SensorBitmapShimmer3.SENSOR_INT_A1 >> 8) & 0xff));

                if (GetInterval() < 54)
                {
                    SetInterval(54);
                }
                if ((byte)((byte)file_trialConfig[1] & (byte)ShimmerSDBT.TrialConfigBitmap.SingleTouch) != 0)
                {
                    file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.UserButton;
                    file_trialConfig[0] |= (byte)ShimmerSDBT.TrialConfigBitmap.Sync;
                }

                if (!centername_set) // if no center is appointed, let this guy be the center
                    SetCenter("00066643b48e");

                //debug

                List<byte> buffer_channelContents = new List<byte>();
                int nbrAdcChans = 0, nbrDigiChans = 0;

                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_A_ACCEL) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.XLNAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.YLNAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ZLNAccel);
                    nbrAdcChans += 3;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_VBATT >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.VBatt);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A7) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ExternalAdc7);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A6) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ExternalAdc6);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXT_A15 >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ExternalAdc15);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A12 >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.InternalAdc12);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)Shimmer.SensorBitmapShimmer3.SENSOR_BRIDGE_AMP >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.STRAIN_HIGH);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.STRAIN_LOW);
                    nbrAdcChans += 2;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A13 >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.InternalAdc13);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A14 >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.InternalAdc14);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_GSR) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.GsrRaw);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_INT_A1 >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.InternalAdc1);
                    nbrAdcChans++;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_MPU9150_GYRO) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.XGyro);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.YGyro);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ZGyro);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[1] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_D_ACCEL >> 8) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.XWRAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.YWRAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ZWRAccel);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_LSM303DLHC_MAG) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.XMag);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.YMag);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.ZMag);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuAccel >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeXAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeYAccel);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeZAccel);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerSDBT.SensorBitmapShimmer3_unused.SensorMpuMag >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeXMag);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeYMag);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.AlternativeZMag);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_BMP180_PRESSURE >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Temperature);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Pressure);
                    nbrDigiChans += 2;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG1_24BIT) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_Status);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_CH1);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_CH2);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG1_16BIT >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_Status);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_CH1_16Bit);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg1_CH2_16Bit);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[0] & (byte)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG2_24BIT) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_Status);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_CH1);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_CH2);
                    nbrDigiChans += 3;
                }
                if ((byte)((byte)file_sensors[2] & (byte)(((int)ShimmerBluetooth.SensorBitmapShimmer3.SENSOR_EXG2_16BIT >> 16) & 0xff)) != 0)
                {
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_Status);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_CH1_16Bit);
                    buffer_channelContents.Add((byte)ShimmerSDBT.ChannelContents.Exg2_CH2_16Bit);
                    nbrDigiChans += 3;
                }

                // get Sampling rate(0-1), config setup byte0(2-5), num chans(6) and buffer size(7)
                List<byte> buffer_inq = new List<byte>();
                // get trial_config(0-1), interval(2)
                List<byte> buffer_trial = new List<byte>();

                buffer_inq.Add((byte)file_sample_rate[0]);
                buffer_inq.Add((byte)file_sample_rate[1]);
                buffer_inq.Add((byte)file_configSetup[0]);
                buffer_inq.Add((byte)file_configSetup[1]);
                buffer_inq.Add((byte)file_configSetup[2]);
                buffer_inq.Add((byte)file_configSetup[3]);
                buffer_inq.Add((byte)(nbrAdcChans + nbrDigiChans));
                buffer_inq.Add((byte)1);
                for (int channelx = 0; channelx < nbrAdcChans + nbrDigiChans; channelx++)
                {
                    buffer_inq.Add(buffer_channelContents[channelx]);
                }
                InterpretInquiryResponseShimmer3(buffer_inq);

                //byte[] file_sensors = new byte[3] { 0, 0, 0 };

                buffer_trial.Add((byte)file_trialConfig[0]);
                buffer_trial.Add((byte)file_trialConfig[1]);
                buffer_trial.Add((byte)GetInterval());
                fillTrialShimmer3(buffer_trial);
            }
            return 0;
        }
Beispiel #9
0
        // btsd changes
        private void readInfoMem()
        {
            //string status_text = "";
            //PChangeStatusLabel("Inquiring Shimmer Info"); // need to be in a UI thread for update
            SetDataReceived(false);

            // btsd changes 2
            string status_text = "Acquiring Accelerometer Range...";
            CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring Accelerometer Range...";
            //worker.ReportProgress(15, status_text);
            ReadAccelRange();

            status_text = "Acquiring ADC Sampling Rate...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring ADC Sampling Rate...";
            //worker.ReportProgress(20, status_text);
            ReadSamplingRate();

            status_text = "Acquiring Magnetometer Range...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring Magnetometer Range...";
            //worker.ReportProgress(25, status_text);
            ReadMagRange();

            status_text = "Acquiring Gyro Range...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring Gyro Range...";
            //worker.ReportProgress(30, status_text);
            ReadGyroRange();

            status_text = "Acquiring Accel Sampling Rate...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring Accel Sampling Rate...";
            //worker.ReportProgress(35, status_text);
            ReadAccelSamplingRate();

            status_text = "Acquiring Calibration settings...";
            //PControlForm.status_text = "Acquiring Calibration settings...";
            //worker.ReportProgress(40, status_text);
            ReadCalibrationParameters("All");

            status_text = "Acquiring EXG1 configure settings...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring EXG1 configure settings...";
            //worker.ReportProgress(45, status_text);
            ReadEXGConfigurations(1);

            status_text = "Acquiring EXG2 configure settings...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring EXG2 configure settings...";
            //worker.ReportProgress(50, status_text);
            ReadEXGConfigurations(2);

            //There is an inquiry below so no need for this
            status_text = "Acquiring Internal Exp Power setting...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            ReadInternalExpPower();

            status_text = "Acquiring trial configure settings...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring trial configure settings...";
            //worker.ReportProgress(55, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_TRIAL_CONFIG_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring center name...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring center name...";
            //worker.ReportProgress(60, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_CENTER_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring shimmer name...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring shimmer name...";
            //worker.ReportProgress(65, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_SHIMMERNAME_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring experiment ID...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring experiment ID...";
            //worker.ReportProgress(70, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_EXPID_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring Multi Shimmer settings...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring Multi Shimmer settings...";
            //worker.ReportProgress(75, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_MYID_COMMAND }, 0, 1);
            waitTilTimeOut();

            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_NSHIMMER_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring configure time...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring configure time...";
            //worker.ReportProgress(80, status_text);
            WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_CONFIGTIME_COMMAND }, 0, 1);
            waitTilTimeOut();

            status_text = "Acquiring general settings...";
            newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)status_text);
            OnNewEvent(newEventArgs);
            //PControlForm.status_text = "Acquiring general settings...";
            //worker.ReportProgress(85, status_text);
            Inquiry();
        }
Beispiel #10
0
        public override void StopStreaming()
        {
            base.StopStreaming();
            // btsd changes 2
            if (GetFirmwareIdentifier() == 3)
            {
                System.Threading.Thread.Sleep(300);
                WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_STATUS_COMMAND }, 0, 1);
                System.Threading.Thread.Sleep(500);
                String message = "Stopped.";
                if (isLogging)
                {
                    WriteBytes(new byte[1] { (byte)ShimmerSDBT.PacketTypeShimmer3SDBT.GET_DIR_COMMAND }, 0, 1);
                    int i = 11;
                    while (((i--) > 1) && (GetSdDir() == ""))
                    {
                        System.Threading.Thread.Sleep(200);
                    }
                    if (i == 0)
                    {
                        // btsd changes 2
                        System.Console.WriteLine("GetSdDir(): " + GetSdDir());
                        message = "BTStream + SDLog, Current SDLog Directory : Could not read the directory name.";
                        //PControlForm.ChangeStatusLabel("BTStream + SDLog, Current SDLog Directory : Could not read the directory name.");

                    }

                }

                CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_NOTIFICATION_MESSAGE, (object)message);
                OnNewEvent(newEventArgs);
                //PControlForm.ChangeStatusLabel("Stopped, Last SDLog Directory : " + GetSdDir());
                SetSdDir("");

            }
        }
 public void SetState(int state)
 {
     ShimmerState = state;
     /*EventHandler handler = UICallback;
     if (handler != null)
     {
         CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_STATE_CHANGE, (object)state);
         handler(this, newEventArgs);
     }
      */
     CustomEventArgs newEventArgs = new CustomEventArgs((int)ShimmerIdentifier.MSG_IDENTIFIER_STATE_CHANGE, (object)state);
     OnNewEvent(newEventArgs);
 }