Example #1
0
        //if you have MITes data only use this method
        public void SaveRawMITesBuiltinData(GenericAccelerometerData data)
        {
            if (isActive)
            {
                // Create and open the writer to the correct binary file in
                // the correct directory
                DetermineFilePath();

                //Store builtin data before the MITes data if it is timestamped before it
                if ((data != null) && (data.Unixtimestamp < aMITesDecoder.someMITesData[0].unixTimeStamp))
                {
                    SaveRawBuiltinData(data);
                }

                for (int i = 0; i < aMITesDecoder.someMITesDataIndex; i++)
                {
                    aTime     = aMITesDecoder.someMITesData[i].timeStamp;
                    aUnixTime = aMITesDecoder.someMITesData[i].unixTimeStamp;

                    if (aTime < lastTime)
                    {
                        Console.WriteLine("StepBack!: " + (lastTime - aTime));
                    }
                    if (aUnixTime < lastUnixTime)
                    {
                        Console.WriteLine("StepBackUnix!: " + (lastUnixTime - aUnixTime));
                    }

                    // Roughly once per second save full timestamp, no matter what
                    if (isForceTimestampSave || (timeSaveCount == TIMESTAMP_AFTER_SAMPLES))
                    {
                        //WriteTimeDiff(aTime, lastTime, aUnixTime, true); // Force save
                        WriteTimeDiff(aUnixTime, lastUnixTime, true); // Force save
                        timeSaveCount = 0;
                    }
                    else
                    {
                        //WriteTimeDiff(aTime, lastTime, aUnixTime, false);
                        WriteTimeDiff(aUnixTime, lastUnixTime, false);
                        timeSaveCount++;
                    }

                    isForceTimestampSave = false;

                    // Actually save the data!
                    SaveMITesData(aMITesDecoder.someMITesData[i]);
                    // tw.WriteLine(aMITesDecoder.someMITesData[i].unixTimeStamp + ","+ aMITesDecoder.someMITesData[i].x + "," + aMITesDecoder.someMITesData[i].y + "," + aMITesDecoder.someMITesData[i].z);

                    lastTime     = aTime;
                    lastUnixTime = aUnixTime;
                }


                //Store builtin data after the MITes if it is stamped after the MITes data
                if ((data != null) && (data.Unixtimestamp >= aMITesDecoder.someMITesData[0].unixTimeStamp))
                {
                    SaveRawBuiltinData(data);
                }
            }
        }
Example #2
0
        //if you have built in data only use this method
        public void SaveRawBuiltinData(GenericAccelerometerData data)
        {
            //lastUnixTime = 0;
            isForceTimestampSave = true;
            if (isActive)
            {
                // Create and open the writer to the correct binary file in
                // the correct directory
                DetermineFilePath();

                aTime     = data.Timestamp;
                aUnixTime = data.Unixtimestamp;
                if (aTime < lastTime)
                {
                    Console.WriteLine("StepBack!: " + (lastTime - aTime));
                }
                if (aUnixTime < lastUnixTime)
                {
                    Console.WriteLine("StepBackUnix!: " + (lastUnixTime - aUnixTime));
                }

                // Roughly once per second save full timestamp, no matter what
                if (isForceTimestampSave || (timeSaveCount == TIMESTAMP_AFTER_SAMPLES))
                {
                    //WriteTimeDiff(aTime, lastTime, aUnixTime, true); // Force save
                    WriteTimeDiff(aUnixTime, lastUnixTime, true); // Force save
                    timeSaveCount = 0;
                }
                else
                {
                    //WriteTimeDiff(aTime, lastTime, aUnixTime, false);
                    WriteTimeDiff(aUnixTime, lastUnixTime, false);
                    timeSaveCount++;
                }

                isForceTimestampSave = false;

                // Actually save the data!
                // SaveMITesData(aMITesDecoder.someMITesData[i]);

                if (isActive && (bwPLFormat != null))
                {
                    byte[] b = data.encode6Bytes();
                    for (int j = 0; j < b.Length; j++)
                    {
                        bwPLFormat.WriteByte(b[j]);
                    }
                }


                //tw.WriteLine(data.toString());

                lastTime     = aTime;
                lastUnixTime = aUnixTime;
            }
        }
        //if you have built in data only use this method
        public void SaveRawBuiltinData(GenericAccelerometerData data)
        {
            //lastUnixTime = 0;
            isForceTimestampSave = true;
            if (isActive)
            {
                // Create and open the writer to the correct binary file in
                // the correct directory
                DetermineFilePath();

                aTime = data.Timestamp;
                aUnixTime = data.Unixtimestamp;
                if (aTime < lastTime)
                {
                    Console.WriteLine("StepBack!: " + (lastTime - aTime));
                }
                if (aUnixTime < lastUnixTime)
                {
                    Console.WriteLine("StepBackUnix!: " + (lastUnixTime - aUnixTime));
                }

                // Roughly once per second save full timestamp, no matter what
                if (isForceTimestampSave || (timeSaveCount == TIMESTAMP_AFTER_SAMPLES))
                {
                    //WriteTimeDiff(aTime, lastTime, aUnixTime, true); // Force save
                    WriteTimeDiff(aUnixTime, lastUnixTime, true); // Force save
                    timeSaveCount = 0;
                }
                else
                {
                    //WriteTimeDiff(aTime, lastTime, aUnixTime, false);
                    WriteTimeDiff(aUnixTime, lastUnixTime, false);
                    timeSaveCount++;
                }

                isForceTimestampSave = false;

                // Actually save the data! 
                // SaveMITesData(aMITesDecoder.someMITesData[i]);

                if (isActive && (bwPLFormat != null))
                {
                    byte[] b = data.encode6Bytes();
                    for (int j = 0; j < b.Length; j++)
                    {
                        bwPLFormat.WriteByte(b[j]);
                    }
                }


                //tw.WriteLine(data.toString());

                lastTime = aTime;
                lastUnixTime = aUnixTime; 

            }



        }
        //if you have MITes data only use this method
        public void SaveRawMITesBuiltinData(GenericAccelerometerData data)
        {
            if (isActive)
            {
                // Create and open the writer to the correct binary file in
                // the correct directory
                DetermineFilePath();

                //Store builtin data before the MITes data if it is timestamped before it
                if ((data != null) && (data.Unixtimestamp < aMITesDecoder.someMITesData[0].unixTimeStamp))
                    SaveRawBuiltinData(data);

                for (int i = 0; i < aMITesDecoder.someMITesDataIndex; i++)
                {
                    aTime = aMITesDecoder.someMITesData[i].timeStamp;
                    aUnixTime = aMITesDecoder.someMITesData[i].unixTimeStamp;       

                    if (aTime < lastTime)
                    {
                        Console.WriteLine("StepBack!: " + (lastTime-aTime));
                    }
                    if (aUnixTime < lastUnixTime)
                    {
                        Console.WriteLine("StepBackUnix!: " + (lastUnixTime - aUnixTime));
                    }

                    // Roughly once per second save full timestamp, no matter what
                    if (isForceTimestampSave || (timeSaveCount == TIMESTAMP_AFTER_SAMPLES))
                    {
                        //WriteTimeDiff(aTime, lastTime, aUnixTime, true); // Force save
                        WriteTimeDiff(aUnixTime, lastUnixTime, true); // Force save
                        timeSaveCount = 0;
                    }
                    else
                    {
                        //WriteTimeDiff(aTime, lastTime, aUnixTime, false);
                        WriteTimeDiff(aUnixTime, lastUnixTime, false);
                        timeSaveCount++;
                    }

                    isForceTimestampSave = false;

                    // Actually save the data! 
                    SaveMITesData(aMITesDecoder.someMITesData[i]);
                   // tw.WriteLine(aMITesDecoder.someMITesData[i].unixTimeStamp + ","+ aMITesDecoder.someMITesData[i].x + "," + aMITesDecoder.someMITesData[i].y + "," + aMITesDecoder.someMITesData[i].z);

                    lastTime = aTime;
                    lastUnixTime =aUnixTime; 
                }


                //Store builtin data after the MITes if it is stamped after the MITes data
                if ( (data != null) && (data.Unixtimestamp>=aMITesDecoder.someMITesData[0].unixTimeStamp))
                    SaveRawBuiltinData(data);                
            }
        }
Example #5
0
        public GenericAccelerometerData GetSensorData()
        {
            GenericAccelerometerData data = new GenericAccelerometerData(Constants.BUILT_IN_ACCELEROMETER_CHANNEL_ID);
            HTCGSensorData gData = this.diamondTouchSensor.GetRawSensorData();
            data.Type = Constants.DIAMOND_TOUCH_ACCELEROMETER;
            data.MaximumSamplingRate = Constants.DIAMOND_TOUCH_MAX_SAMPLING_RATE;          

            averageX = averageX + Math.Abs(prevX - gData.TiltX);
            averageX = averageY + Math.Abs(prevY - gData.TiltY);
            averageX = averageZ + Math.Abs(prevZ - gData.TiltZ);
            prevX = gData.TiltX;
            prevY = gData.TiltY;
            prevZ = gData.TiltZ;

            data.X = (int)(gData.TiltX+1500);
            data.Y = (int)(gData.TiltY+1500);
            data.Z = (int)(gData.TiltZ+1500);
                     
            return data;

        }
Example #6
0
        public static double StoreBuiltinData(GenericAccelerometerData polledData)
        {
            int sensorIndex = (int)Extractor.sensorIndicies[polledData.ChannelID];
            int adjusted_sensor_index = sensorIndex * 4;
            Extractor.data[adjusted_sensor_index][Extractor.y_index[sensorIndex]] = polledData.X ;
            Extractor.data[adjusted_sensor_index + 1][Extractor.y_index[sensorIndex]] = polledData.Y;
            Extractor.data[adjusted_sensor_index + 2][Extractor.y_index[sensorIndex]] = polledData.Z;
            Extractor.data[adjusted_sensor_index + 3][Extractor.y_index[sensorIndex]] = polledData.Unixtimestamp;

            //increment the y_index for the sensor and wrap around if needed
            Extractor.y_index[sensorIndex] = (Extractor.y_index[sensorIndex] + 1) % Extractor.EXPECTED_WINDOW_SIZES[sensorIndex];

            return polledData.Unixtimestamp;
        }
Example #7
0
        //public void setPlotVals(GenericAccelerometerData builtInData, int startPlotIndex)
        //{

        //    if (builtInData.X > 0)
        //        plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
        //    else
        //        plotVals[startPlotIndex, 0, col] = MITesData.EMPTY;

        //    if (builtInData.Y > 0)
        //        plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
        //    else
        //        plotVals[startPlotIndex, 1, col] = MITesData.EMPTY;

        //    if (builtInData.Z > 0)
        //        plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;
        //    else
        //        plotVals[startPlotIndex, 2, col] = MITesData.EMPTY;


        //    //aPanel.Invalidate(new System.Drawing.Rectangle(col, 0, 2, plotAreaSize.Height));
        //    //col++;
        //    //if (col >= plotAreaSize.Width)
        //    //    col = 0;

        //    //resetPlotVals(col);
        //}

        /// <summary>
        ///
        /// </summary>
        public void setPlotVals(GenericAccelerometerData builtInData, int startPlotIndex)
        {
            int[] returnVals = GetReturnVals();
            int   numVals    = GetReturnValsIndex();

            if ((numVals == 0) && (builtInData != null))
            {
                plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
                plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
                plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;

                aPanel.Invalidate(new System.Drawing.Rectangle(col - 1, 0, 2, plotAreaSize.Height));
                col++;
                if (col >= plotAreaSize.Width)
                {
                    col = 0;
                }

                resetPlotVals(col);
            }
            else
            {
                for (int j = 0; j < numVals; j = j + 4)
                {
                    if (returnVals[j] != MITesDecoder.STATIC_CHANNEL)
                    {
                        id = GetSensorIDMap(returnVals[j]);
                        if (id == MITesData.NONE)
                        {
                            Warning("GetSensorIDMap returned NONE!");
                        }

                        if (id < maxPlots)
                        {
                            x = returnVals[j + 1];
                            y = returnVals[j + 2];
                            z = returnVals[j + 3];

                            if (InValidRange(x))
                            {
                                plotVals[id, 0, col] = x;
                            }
                            else
                            {
                                plotVals[id, 0, col] = MITesData.EMPTY;
                            }

                            if (InValidRange(y))
                            {
                                plotVals[id, 1, col] = y;
                            }
                            else
                            {
                                plotVals[id, 1, col] = MITesData.EMPTY;
                            }

                            if (InValidRange(z))
                            {
                                plotVals[id, 2, col] = z;
                            }
                            else
                            {
                                plotVals[id, 2, col] = MITesData.EMPTY;
                            }

                            //if there are extra plots to plot the builtin sensor data
                            if (startPlotIndex != maxPlots)
                            {
                                if (builtInData != null)
                                {
                                    plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
                                    plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
                                    plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;
                                    //builtInData = null;

                                    //aPanel.Invalidate(new System.Drawing.Rectangle(0, 0,plotAreaSize.Width, plotAreaSize.Height));
                                    //col++;
                                    //if (col >= plotAreaSize.Width)
                                    //    col = 0;

                                    //resetPlotVals(col);
                                }
                                else
                                {
                                    plotVals[startPlotIndex, 0, col] = MITesData.EMPTY;
                                    plotVals[startPlotIndex, 1, col] = MITesData.EMPTY;
                                    plotVals[startPlotIndex, 2, col] = MITesData.EMPTY;
                                }
                            }

                            if (checkIsSeenAllID(id)) // Set isSeenID array
                            {
                                aPanel.Invalidate(new System.Drawing.Rectangle(col - 1, 0, 2, plotAreaSize.Height));
                                col++;
                                if (col >= plotAreaSize.Width)
                                {
                                    col = 0;
                                }

                                resetPlotVals(col);
                            }
                        }
                        else
                        {
                            if (errorPrintCount == 0)
                            {
                                Console.WriteLine("WARNING! Not plotting data from Sensor ID:" + returnVals[j]);
                            }
                            errorPrintCount++;
                            if (errorPrintCount > 1000)
                            {
                                errorPrintCount = 0;
                            }
                        }
                    }
                }
            }

            SetReturnValsIndex(0);
        }
        //public void setPlotVals(GenericAccelerometerData builtInData, int startPlotIndex)
        //{

        //    if (builtInData.X > 0)
        //        plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
        //    else
        //        plotVals[startPlotIndex, 0, col] = MITesData.EMPTY;

        //    if (builtInData.Y > 0)
        //        plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
        //    else
        //        plotVals[startPlotIndex, 1, col] = MITesData.EMPTY;

        //    if (builtInData.Z > 0)
        //        plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;
        //    else
        //        plotVals[startPlotIndex, 2, col] = MITesData.EMPTY;

            
        //    //aPanel.Invalidate(new System.Drawing.Rectangle(col, 0, 2, plotAreaSize.Height));
        //    //col++;
        //    //if (col >= plotAreaSize.Width)
        //    //    col = 0;

        //    //resetPlotVals(col);
        //}

		/// <summary>
		/// 
		/// </summary>
        public void setPlotVals(GenericAccelerometerData builtInData, int startPlotIndex)
        {
            int[] returnVals = GetReturnVals();
            int numVals = GetReturnValsIndex();

            if ((numVals == 0) && (builtInData != null))
            {

                plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
                plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
                plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;

                aPanel.Invalidate(new System.Drawing.Rectangle(col - 1, 0, 2, plotAreaSize.Height));
                col++;
                if (col >= plotAreaSize.Width)
                    col = 0;

                resetPlotVals(col);

            }
            else
            {
                for (int j = 0; j < numVals; j = j + 4)
                {
                    if (returnVals[j] != MITesDecoder.STATIC_CHANNEL)
                    {
                        id = GetSensorIDMap(returnVals[j]);
                        if (id == MITesData.NONE)
                            Warning("GetSensorIDMap returned NONE!");

                        if (id < maxPlots)
                        {
                            x = returnVals[j + 1];
                            y = returnVals[j + 2];
                            z = returnVals[j + 3];

                            if (InValidRange(x))
                                plotVals[id, 0, col] = x;
                            else
                                plotVals[id, 0, col] = MITesData.EMPTY;

                            if (InValidRange(y))
                                plotVals[id, 1, col] = y;
                            else
                                plotVals[id, 1, col] = MITesData.EMPTY;

                            if (InValidRange(z))
                                plotVals[id, 2, col] = z;
                            else
                                plotVals[id, 2, col] = MITesData.EMPTY;

                            //if there are extra plots to plot the builtin sensor data
                            if (startPlotIndex != maxPlots)
                            {
                                if (builtInData != null)
                                {

                                    plotVals[startPlotIndex, 0, col] = builtInData.X / 5;
                                    plotVals[startPlotIndex, 1, col] = builtInData.Y / 5;
                                    plotVals[startPlotIndex, 2, col] = builtInData.Z / 5;
                                    //builtInData = null;

                                    //aPanel.Invalidate(new System.Drawing.Rectangle(0, 0,plotAreaSize.Width, plotAreaSize.Height));
                                    //col++;
                                    //if (col >= plotAreaSize.Width)
                                    //    col = 0;

                                    //resetPlotVals(col);

                                }
                                else
                                {
                                    plotVals[startPlotIndex, 0, col] = MITesData.EMPTY;
                                    plotVals[startPlotIndex, 1, col] = MITesData.EMPTY;
                                    plotVals[startPlotIndex, 2, col] = MITesData.EMPTY;
                                }
                            }

                            if (checkIsSeenAllID(id)) // Set isSeenID array
                            {
                                aPanel.Invalidate(new System.Drawing.Rectangle(col - 1, 0, 2, plotAreaSize.Height));
                                col++;
                                if (col >= plotAreaSize.Width)
                                    col = 0;

                                resetPlotVals(col);
                            }
                        }
                        else
                        {
                            if (errorPrintCount == 0)
                                Console.WriteLine("WARNING! Not plotting data from Sensor ID:" + returnVals[j]);
                            errorPrintCount++;
                            if (errorPrintCount > 1000)
                                errorPrintCount = 0;
                        }
                    }
                }
            }

            SetReturnValsIndex(0);
        }
        private void readDataTimer_Tick(object sender, EventArgs e)
        {
                    
            #region Bluetooth Reconnection Code
#if (PocketPC)



            //Start a reconnection thread
            foreach (Receiver receiver in this.sensors.Receivers)
            {
                if (!receiver.Running) //&& (!receiver.Restarting))
                {
                    aMITesActivityLogger.WriteLogComment("Connection broke with " + receiver.ID + ". Restarting");   
                    //reconnectionThreadQuit[receiver.ID] = false;

                    BluetoothConnector btc=new BluetoothConnector(receiver, this.bluetoothControllers, this.mitesDecoders);
                    aMITesActivityLogger.WriteLogComment("Initializing reconnection thread");   
                    //ts[receiver.ID] = new Thread(new ThreadStart(btc.Reconnect));
                    //ts[receiver.ID].Start();
                    btc.Reconnect();
                    aMITesActivityLogger.WriteLogComment("Reconnection thread started");     
                    receiver.Restarting = true;
                  
                }
                else if (receiver.Restarted)
                {               

                    aMITesActivityLogger.WriteLogComment("Reconnection completed"); 
                    receiver.Restarted = false;
                    receiver.Restarting = false;
                    receiver.Running = true;
                }

            }


#endif

                #endregion Bluetooth Reconnection Code

            #region Poll All Wockets and MITes and Decode Data
       
            Receiver currentReceiver = null;
            try
            {
                //Poll each CONNECTED receiver channel with the right decoder
                foreach (Receiver receiver in this.sensors.Receivers)
                {
                    currentReceiver = receiver;
#if (PocketPC)
                    if ((receiver.Type == SXML.Constants.RECEIVER_BLUETOOTH) && (receiver.Running == true))
                    {
                        if (receiver.Decoder == SXML.Constants.DECODER_MITES)
                            this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.MITES_SENSOR);
                        else if (receiver.Decoder == SXML.Constants.DECODER_WOCKETS)
                            this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.WOCKETS_SENSOR);
                        else if (receiver.Decoder == SXML.Constants.DECODER_SPARKFUN)
                            this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.SPARKFUN_SENSOR);
                    }
                    else 
#endif                        
                        if (receiver.Type == SXML.Constants.RECEIVER_USB)
                        this.mitesDecoders[receiver.ID].GetSensorData(this.mitesControllers[receiver.ID]);
                }

                if (++ttwcounter == 6000)
                {
                    TextWriter ttw = new StreamWriter("\\Internal Storage\\ts.txt");
                    ttw.WriteLine(DateTime.Now.ToLongTimeString());
                    ttw.Close();
                    ttwcounter = 0;
                }

            }
            //Thrown when there is a Bluetooth failure                    
            //TODO: Make sure no USB failure happening
            catch (Exception ex)
            {

                currentReceiver.Running = false;
                //connectionLost = true;
                return;
            }

            //Reset the index of the master decoder and copy all data in order into the master decoder
            this.masterDecoder.someMITesDataIndex = 0;    
            //Only decode running receivers (i.e. with no connection failure)              
            foreach (Receiver receiver in this.sensors.Receivers)
                if (receiver.Running)
                    this.masterDecoder.MergeDataOrderProperly(this.mitesDecoders[receiver.ID]);


            #endregion Poll All Wockets and MITes and Decode Data

            #region Poll Builtin Data

#if (PocketPC)
            GenericAccelerometerData polledData = null;
            if (unprocessedBuiltin == true)
            {
                this.builtinData.Timestamp = Environment.TickCount;
                this.builtinData.Unixtimestamp = UnixTime.GetUnixTime();
                polledData = this.builtinData;
            }
#endif
            #endregion Poll Builtin Data

            #region Train in realtime and generate ARFF File
            if (IsTraining == true)
            {
                //We are autotraining each activity after the other
                if (AutoTraining == true)
                {
                    //Get current activity to train
                    string current_activity = ((AXML.Label)((AXML.Category)this.annotation.Categories[0]).Labels[autoTrainingIndex]).Name;

                    //Check if trained
                    if (Extractor.IsTrained(current_activity))
                    {
                        //store the completed annotation and reset the variables
                        this.currentRecord.EndDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                        this.currentRecord.EndHour = DateTime.Now.Hour;
                        this.currentRecord.EndMinute = DateTime.Now.Minute;
                        this.currentRecord.EndSecond = DateTime.Now.Second;
                        TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0));
                        this.currentRecord.EndUnix = ts.TotalSeconds;
                        this.annotation.Data.Add(this.currentRecord);
                        //each time an activity is stopped, rewrite the file on disk, need to backup file to avoid corruption
                        this.annotation.ToXMLFile();
                        this.annotation.ToCSVFile();
                        isExtracting = false;

                        //Point to the next activity and Calculate the delay to start training
                        this.startActivityTime = Environment.TickCount + Extractor.Configuration.TrainingWaitTime * 1000;//Constants.TRAINING_GAP;
                        autoTrainingIndex++;


                        //If we exceeded the last activity then training is completed
                        if (autoTrainingIndex == ((AXML.Category)this.annotation.Categories[0]).Labels.Count)
                        {
                            this.trainingLabel.Text = "Training Completed";
                            this.goodTimer.reset();
                            this.overallTimer.reset();
                            Thread.Sleep(3000);
                            EndTraining();

                        }
                        else // if there are still activities to train beep twice and reset good timer
                        {
                            this.goodTimer.reset();
#if (PocketPC)
                            PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC));
                            PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC));
#endif
                        }
                    }
                    //if the current activity is not trained and the start time is more that the current time
                    //then calculate the feature vector
                    else if (this.startActivityTime < Environment.TickCount) // TRAINING_GAP passed
                    {
                        //initialize for extraction
                        if (isExtracting == false)
                        {
                            this.trainingLabel.Text = "Training " + current_activity;
                            this.goodTimer.start();
                            //store the current state of the categories
                            this.currentRecord = new AnnotatedRecord();
                            this.currentRecord.StartDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                            this.currentRecord.StartHour = DateTime.Now.Hour;
                            this.currentRecord.StartMinute = DateTime.Now.Minute;
                            this.currentRecord.StartSecond = DateTime.Now.Second;
                            TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0));
                            this.currentRecord.StartUnix = ts.TotalSeconds;
                            this.currentRecord.Labels.Add(new AXML.Label(current_activity, "none"));
                            isExtracting = true;
                        }


                        //Extract feature vector from accelerometer data and write an arff line
                        double lastTimeStamp = Extractor.StoreMITesWindow();
#if (PocketPC)
                        if ((this.sensors.HasBuiltinSensors) && (polledData != null))
                        {
                            //store it in Extractor Buffers as well
                            lastTimeStamp = Extractor.StoreBuiltinData(polledData);
                        }
#endif
                        if (Extractor.GenerateFeatureVector(lastTimeStamp))
                        {
                            Extractor.TrainingTime[current_activity] = (int)Extractor.TrainingTime[current_activity] + Extractor.Configuration.OverlapTime;// get it from configuration
                            string arffSample = Extractor.toString() + "," + current_activity.Replace(' ', '_');
                            this.tw.WriteLine(arffSample);
                            this.label8.Text = Extractor.DiscardedLossRateWindows.ToString();
                        }
                    }
                    //if we are waiting for the activity to be trained
                    else
                        this.trainingLabel.Text = "Training " + current_activity + " in " + ((int)(this.startActivityTime - Environment.TickCount) / 1000) + " secs";

                }
                else // Manual Training
                {
                }
            }



            #endregion Train in realtime and generate ARFF File

            #region Classifying activities

#if (PocketPC)
            if (isClassifying == true)
            {
                double lastTimeStamp = Extractor.StoreMITesWindow();
                if ((this.sensors.HasBuiltinSensors) && (polledData != null))
                {
                    //aMITesLoggerPLFormat.SaveRawMITesBuiltinData(polledData);
                    //store it in Extractor Buffers as well
                    lastTimeStamp = Extractor.StoreBuiltinData(polledData);
                }

                if (Extractor.GenerateFeatureVector(lastTimeStamp))
                {
                    Instance newinstance = new Instance(instances.numAttributes());
                    newinstance.Dataset = instances;
                    for (int i = 0; (i < Extractor.Features.Length); i++)
                        newinstance.setValue(instances.attribute(i), Extractor.Features[i]);
                    double predicted = classifier.classifyInstance(newinstance);
                    string predicted_activity = newinstance.dataset().classAttribute().value_Renamed((int)predicted);

                    int currentIndex = (int)labelIndex[predicted_activity];
                    labelCounters[currentIndex] = (int)labelCounters[currentIndex] + 1;
                    classificationCounter++;

                    if (classificationCounter == Extractor.Configuration.SmoothWindows)
                    {
                        classificationCounter = 0;
                        int mostCount = 0;
                        string mostActivity = "";
                        for (int j = 0; (j < labelCounters.Length); j++)
                        {
                            if (labelCounters[j] > mostCount)
                            {
                                mostActivity = activityLabels[j];
                                mostCount = labelCounters[j];
                            }
                            labelCounters[j] = 0;
                        }

                        pieChart.SetActivity(mostActivity);
                        if (this.aList.getEmptyPercent() == 1)
                            this.aList.reset();
                        else
                            this.aList.increment(mostActivity);

                        if (previousActivity != mostActivity)
                        {
                            this.activityTimer.stop();
                            this.activityTimer.reset();
                            currentCalories = 0;
                        }
                        else
                        {
                            if (this.activityTimer.isRunning() == false)
                                this.activityTimer.start();
                        }

                        if (mostActivity == "standing")
                        {
                            currentCalories += 1;
                            totalCalories += 1;
                        }
                        else if (mostActivity == "walking")
                        {
                            currentCalories += 2;
                            totalCalories += 2;
                        }
                        else if (mostActivity == "brisk-walking")
                        {
                            currentCalories += 4;
                            totalCalories += 4;
                        }
                        else
                        {
                            currentCalories += 1;
                            totalCalories += 1;
                        }
                        pieChart.SetCalories(totalCalories, currentCalories);
                        pieChart.Data = this.aList.toPercentHashtable();
                        pieChart.Invalidate();
                        previousActivity = mostActivity;
                    }
                }
            }

#endif


            #endregion Classifying activities

            #region Storing CSV data for the grapher (PC Only)
#if (!PocketPC)

            if (isCollectingDetailedData == true)
            {
                if (activityCountWindowSize > Extractor.Configuration.QualityWindowSize) //write a line to CSV and initialize
                {
                    DateTime now = DateTime.Now;
                    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    TimeSpan diff = now.Subtract(origin);
                    string timestamp = diff.TotalMilliseconds + "," + now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK");
                    string master_csv_line = timestamp;
                    string hr_csv_line = timestamp;
                    //to restore the date
                    //DateTime restored = origin.AddMilliseconds(diff.TotalMilliseconds);
                    if (this.overallTimer.isRunning())
                    {
                        foreach (Button button in this.categoryButtons)
                            master_csv_line += "," + button.Text;
                    }
                    else
                    {
                        foreach (Button button in this.categoryButtons)
                            master_csv_line += ",";
                    }

                    foreach (Sensor sensor in this.sensors.Sensors)
                    {
                        string csv_line1 = timestamp;
                        string csv_line2 = timestamp;
                        string csv_line3 = timestamp;


                        int sensor_id = Convert.ToInt32(sensor.ID);
                        if (sensor_id > 0) //No HR
                        {
                            if (acCounters[sensor_id] > 0)
                            {
                                csv_line2 += "," + MITesDataFilterer.MITesPerformanceTracker[sensor_id].LastSamplingRate;

                                csv_line1 += "," + ((double)(averageX[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ",";
                                csv_line1 += ((double)(averageY[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ",";
                                csv_line1 += ((double)(averageZ[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00");

                                csv_line3 += "," + ((int)(averageRawX[sensor_id] / acCounters[sensor_id])) + ",";
                                csv_line3 += ((int)(averageRawY[sensor_id] / acCounters[sensor_id])) + ",";
                                csv_line3 += ((int)(averageRawZ[sensor_id] / acCounters[sensor_id]));



                                master_csv_line += "," + MITesDataFilterer.MITesPerformanceTracker[sensor_id].LastSamplingRate;
                                master_csv_line += "," + ((int)(averageRawX[sensor_id] / acCounters[sensor_id])) + ",";
                                master_csv_line += ((int)(averageRawY[sensor_id] / acCounters[sensor_id])) + ",";
                                master_csv_line += ((int)(averageRawZ[sensor_id] / acCounters[sensor_id]));
                                master_csv_line += "," + ((double)(averageX[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ",";
                                master_csv_line += ((double)(averageY[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ",";
                                master_csv_line += ((double)(averageZ[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00");


                            }
                            else
                            {
                                csv_line1 += ",,,,";
                                csv_line3 += ",,,,";
                                csv_line2 += ",0";
                                master_csv_line += ",0,,,,,,";
                            }

                            this.activityCountCSVs[sensor_id].WriteLine(csv_line1);
                            this.samplingCSVs[sensor_id].WriteLine(csv_line2);
                            this.averagedRaw[sensor_id].WriteLine(csv_line3);
                        }

                        averageX[sensor_id] = 0;
                        averageY[sensor_id] = 0;
                        averageZ[sensor_id] = 0;
                        averageRawX[sensor_id] = 0;
                        averageRawY[sensor_id] = 0;
                        averageRawZ[sensor_id] = 0;
                        prevX[sensor_id] = 0;
                        prevY[sensor_id] = 0;
                        prevY[sensor_id] = 0;
                        acCounters[sensor_id] = 0;
                    }


                    if (hrCount > 0)
                    {
                        this.hrCSV.WriteLine(hr_csv_line + "," + (int)(sumHR / hrCount));
                        this.masterCSV.WriteLine(master_csv_line + "," + (int)(sumHR / hrCount));
                    }
                    else
                    {
                        this.hrCSV.WriteLine(hr_csv_line + ",");
                        this.masterCSV.WriteLine(master_csv_line + ",");
                    }

                    hrCount = 0;
                    sumHR = 0;
                    activityCountWindowSize = 0;
                }

                activityCountWindowSize += 10; //add 10 milliseconds
            }

#endif

            #endregion Storing CSV data for the grapher (PC Only)

            #region Calibration and CSV Calculateion Code
            if ((isCalibrating) || (isCollectingDetailedData == true))
            {

                //store sum of abs values of consecutive accelerometer readings
                for (int i = 0; (i < this.masterDecoder.someMITesDataIndex); i++)
                {
                    if ((this.masterDecoder.someMITesData[i].type != (int)MITesTypes.NOISE) &&
                          (this.masterDecoder.someMITesData[i].type == (int)MITesTypes.ACCEL))
                    {
                        int channel = 0, x = 0, y = 0, z = 0;
                        channel = (int)this.masterDecoder.someMITesData[i].channel;
                        x = (int)this.masterDecoder.someMITesData[i].x;
                        y = (int)this.masterDecoder.someMITesData[i].y;
                        z = (int)this.masterDecoder.someMITesData[i].z;


                        #region Calibration Calculation
                        if (isCalibrating)
                        {
                            if (this.calSensor == -1)
                            {
                                if (this.currentCalibrationSensorIndex < this.sensors.Sensors.Count)
                                {
                                    this.calX = new int[Constants.CALIBRATION_SAMPLES];
                                    this.calY = new int[Constants.CALIBRATION_SAMPLES];
                                    this.calZ = new int[Constants.CALIBRATION_SAMPLES];
                                    this.calSensor = Convert.ToInt32(((Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID);
                                    this.calSensorPosition = Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION;

                                    int receiver_id = Convert.ToInt32(((Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).Receiver);
                                    int[] channels = new int[6];
#if (PockectPC)                          
                                    if (this.calSensor != PhoneAccelerometers.Constants.BUILT_IN_ACCELEROMETER_CHANNEL_ID)
                                    {
#endif
                                    channels[0] = this.calSensor;
                                    this.mitesControllers[receiver_id].SetChannels(1, channels);
#if (PockectPC)  
                                    }
#endif
                                }
                                else //all sensors are calibrated
                                {
                                    TextWriter tw = new StreamWriter("SensorData.xml");
                                    tw.WriteLine(this.sensors.toXML());
                                    tw.Close();
                                    MessageBox.Show("Calibration... Completed");
#if (PocketPC)
                                    Application.Exit();
                                    System.Diagnostics.Process.GetCurrentProcess().Kill();
#else
                                    Environment.Exit(0);
#endif
                                }

                            }

                            if (channel == this.calSensor)
                            {
                                if (this.calSensorPosition == Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION)
                                {
                                    this.calX[this.calCounter] = x;
                                    this.calY[this.calCounter] = y;
                                    this.calCounter++;
                                }
                                else //vertical
                                {
                                    this.calZ[this.calCounter] = z;
                                    this.calCounter++;
                                }

                                // if all required samples are collected
                                if (this.calCounter == Constants.CALIBRATION_SAMPLES)
                                {

                                    if (this.calSensorPosition == Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION)
                                    {

                                        this.calSensorPosition = Constants.CALIBRATION_SIDE_VERTICAL_POSITION;
                                        double meanX = 0.0, meanY = 0.0;
                                        double stdX = 0.0, stdY = 0.0;
                                        this.label17.Text = "Calibration Completed! Please place the sensor " + ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID + " vertical on a flat surface then click start.";
                                        this.pictureBox2.Image = this.verticalMITes;
                                        this.button2.Enabled = true;
                                        for (int j = 0; (j < this.calCounter); j++)
                                        {
                                            meanX += (double)this.calX[j];
                                            meanY += (double)this.calY[j];
                                        }
                                        meanX = meanX / this.calCounter;
                                        meanY = meanY / this.calCounter;

                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).XMean = meanX;
                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).YMean = meanY;
                                        for (int j = 0; (j < this.calCounter); j++)
                                        {
                                            stdX += Math.Pow(this.calX[j] - meanX, 2);
                                            stdY += Math.Pow(this.calY[j] - meanY, 2);
                                        }
                                        stdX = Math.Sqrt(stdX / (this.calCounter - 1));
                                        stdY = Math.Sqrt(stdY / (this.calCounter - 1));

                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).XStd = stdX;
                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).YStd = stdY;
                                    }
                                    else
                                    {


                                        if (this.currentCalibrationSensorIndex < this.sensors.Sensors.Count)
                                        {
                                            this.label17.Text = "Calibration Completed! Please place the sensor " + ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID + " horizontal on a flat surface then click start.";
                                            this.pictureBox2.Image = this.horizontalMITes;
                                            this.button2.Enabled = true;
                                        }
                                        this.calSensorPosition = Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION;
                                        double meanZ = 0.0;
                                        double stdZ = 0.0;

                                        for (int j = 0; (j < this.calCounter); j++)
                                            meanZ += (double)this.calZ[j];
                                        meanZ = meanZ / this.calCounter;
                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ZMean = meanZ;

                                        for (int j = 0; (j < this.calCounter); j++)
                                            stdZ += Math.Pow(this.calZ[j] - meanZ, 2);
                                        stdZ = Math.Sqrt(stdZ / (this.calCounter - 1));
                                        ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ZStd = stdZ;
                                        this.currentCalibrationSensorIndex++;
                                        this.calSensor = -1;
                                    }

                                    this.isCalibrating = false;
                                    this.calCounter = 0;


                                }
                            }

                        }
                        #endregion Calibration Calculation

                        #region CSV values calculation (PC Only)
#if (!PocketPC)
                        else if (isCollectingDetailedData)
                        {

                            if (channel <= this.sensors.MaximumSensorID) //if junk comes ignore it
                            {
                                if ((prevX[channel] > 0) && (prevY[channel] > 0) && (prevZ[channel] > 0) && (x > 0) && (y > 0) && (z > 0))
                                {
                                    averageX[channel] = averageX[channel] + Math.Abs(prevX[channel] - x);
                                    averageRawX[channel] = averageRawX[channel] + x;
                                    averageY[channel] = averageY[channel] + Math.Abs(prevY[channel] - y);
                                    averageRawY[channel] = averageRawY[channel] + y;
                                    averageZ[channel] = averageZ[channel] + Math.Abs(prevZ[channel] - z);
                                    averageRawZ[channel] = averageRawZ[channel] + z;
                                    acCounters[channel] = acCounters[channel] + 1;
                                }

                                prevX[channel] = x;
                                prevY[channel] = y;
                                prevZ[channel] = z;
                            }

                        }
#endif
                        #endregion CSV values calculation (PC Only)
                    }
                }
            }
            #endregion Calibration and CSV Calculateion Code

            //Remove data with any values =0 or 1022
            aMITesDataFilterer.RemoveZeroNoise();

            this.masterDecoder.UpdateSamplingRate(aMITesDataFilterer.CountNonNoise());

            if (printSamplingCount > 500)
            {
                //((System.Windows.Forms.Label)this.sensorLabels["SampRate"]).Text = "Samp: " + this.mitesDecoders[0].GetSamplingRate();
                ((System.Windows.Forms.Label)this.sensorLabels["SampRate"]).Text = "Samp: ttt";//+this.masterDecoder.GetSamplingRate();
                //textBoxRate.Text = "Samp: " + aMITesDecoder.GetSamplingRate();
                //aMITesLogger.WriteLogComment(textBoxUV.Text);
                printSamplingCount = 0;
            }
            else
                printSamplingCount++;



            // Check HR values
            int hr = aMITesHRAnalyzer.Update();
#if (PocketPC)

#else
            if (hr > 0)
            {
                sumHR += hr;
                hrCount++;
            }
#endif



            //Compute/get Activity Counts
            for (int i = 0; (i < this.sensors.Sensors.Count); i++)
            {
                int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID);
                if (sensor_id > 0)
                    ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).UpdateActivityCounts();
                //else if (sensor_id == 0)
                //    aMITesHRAnalyzer.Update();
            }


            for (int i = 0; (i < this.sensors.Sensors.Count); i++)
            {
                int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID);
                if (sensor_id > 0)
                    ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).PrintMaxMin();

            }

            if (((MITesActivityCounter)this.aMITesActivityCounters[this.sensors.FirstAccelerometer]).IsNewEpoch(1000))
            {
                aMITesHRAnalyzer.ComputeEpoch(30000);
                //if (this.tabControl1.TabIndex == 0)
                //  ReportHR();

                for (int i = 0; (i < this.sensors.Sensors.Count); i++)
                {
                    int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID);
                    if (sensor_id > 0)
                        ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).ComputeEpoch();
                }



                if (!isWrittenKey) // Write the key once at the top of the file
                {
                    isWrittenKey = true;
                    aMITesActivityLogger.StartReportKeyLine();
                    for (int i = 0; (i < this.sensors.Sensors.Count); i++)
                    {
                        int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID);
                        if (sensor_id > 0)
                            aMITesActivityLogger.AddKeyLine(((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]));
                    }

                    aMITesActivityLogger.AddKeyLine(aMITesHRAnalyzer);
                    aMITesActivityLogger.SaveReportKeyLine();
                }
                aMITesActivityLogger.StartReportLine();

                for (int i = 0; (i < this.sensors.Sensors.Count); i++)
                {
                    int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID);
                    if (sensor_id > 0)
                        aMITesActivityLogger.AddReportLine(((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]));
                }

                aMITesActivityLogger.AddReportLine(aMITesHRAnalyzer);
                aMITesActivityLogger.SaveReportLine();
            }
           

            #region Store the sensor data



            if (flushTimer == 0)
                aMITesLoggerPLFormat.FlushBytes();
            if (flushTimer > FLUSH_TIMER_MAX)
                flushTimer = -1;
            flushTimer++;

            #endregion Store the sensor data


            // Graph accelerometer data for multiple recievers
#if (PocketPC)
            if (isPlotting)
                GraphAccelerometerValues(polledData);
#endif


#if (PocketPC)
            if (polledData != null)
            {
                this.builtinData = null;
                this.unprocessedBuiltin = false;
            }
#endif

        }
        private void pollingData()
        {
            while (true)
            {
                if ((unprocessedBuiltin==false) && (Environment.TickCount - pollingTime >= 60))
                {

                    this.builtinData = this.htcDecoder.PollBuiltInSensors();
                    pollingTime = Environment.TickCount;
                    unprocessedBuiltin = true;
                }
                Thread.Sleep(50);
            }
        }
        private void GraphAccelerometerValues(GenericAccelerometerData data)
        {
            //if (isStartedReceiver)
                aMITesPlotter.SetAccelResultsData();

            if (this.sensors.IsHR)
                aMITesPlotter.setPlotVals(data, this.sensors.Sensors.Count - this.sensors.TotalBuiltInSensors-1);
            else
                aMITesPlotter.setPlotVals(data, this.sensors.Sensors.Count - this.sensors.TotalBuiltInSensors);            
        }