<commit_before>package org.marco45.polarheartmonitor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.SimpleXYSeries;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


/**
 * This program connect to a bluetooth polar heart rate monitor and display data
 * @author Marco
 *
 */
public class MainActivity extends Activity  implements OnItemSelectedListener, Observer {

	private int MAX_SIZE = 60; //graph max size
	boolean searchBt = true;
	BluetoothAdapter mBluetoothAdapter;
	Set<BluetoothDevice> pairedDevices;
	boolean menuBool = false; //display or not the disconnect option
	private XYPlot plot;
	Tracker t;//Set the Tracker
	boolean h7 = false; //Was the BTLE tested
	boolean normal = false; //Was the BT tested
	private Spinner spinner1;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.i("Main Activity", "Starting Polar HR monitor main activity");
		DataHandler.getInstance().addObserver(this);		
		AdView mAdView = (AdView) findViewById(R.id.adView);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        AdRequest adRequest = new AdRequest.Builder().build();

        // Start loading the ad in the background.
        mAdView.loadAd(adRequest);
        
        //Verify if device is to old for BTLE
        if(	android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2){

    		Log.i("Main Activity", "old device H7 disbled");
        	h7=true;
        }
        
        //verify if bluetooth device are enabled
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if(DataHandler.getInstance().newValue){
			//Verify if bluetooth if activated, if not activate it
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
			if (!mBluetoothAdapter.isEnabled()) {
				new AlertDialog.Builder(this)
				.setTitle(R.string.bluetooth)
				.setMessage(R.string.bluetoothOff)
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) { 
						mBluetoothAdapter.enable();
						try {Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						listBT();
					}
				})
				.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) { 
						searchBt = false;
					}
				})
				.show();
			}
			else{
				listBT();
			}



			// Create Graph
			plot = (XYPlot) findViewById(R.id.dynamicPlot);
			if(plot.getSeriesSet().size()==0){
				Number[] series1Numbers = {};
				DataHandler.getInstance().setSeries1(new SimpleXYSeries(Arrays.asList(series1Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,"Heart Rate")); 
			}
			DataHandler.getInstance().setNewValue(false);

		}
		else
		{
			listBT();
			plot = (XYPlot) findViewById(R.id.dynamicPlot);

		}
		//LOAD Graph
		LineAndPointFormatter series1Format = new LineAndPointFormatter( Color.rgb(0, 0, 255), Color.rgb(200, 200, 200), null, null ); 
		series1Format.setPointLabelFormatter(new PointLabelFormatter());
		plot.addSeries(DataHandler.getInstance().getSeries1(), series1Format); 
		plot.setTicksPerRangeLabel(3);
		plot.getGraphWidget().setDomainLabelOrientation(-45);

		//ANALYTIC
		t = GoogleAnalytics.getInstance(this).newTracker("UA-51478243-1");
		t.setScreenName("Polar main page");
		t.send(new HitBuilders.AppViewBuilder().build());

	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		DataHandler.getInstance().deleteObserver(this);
	}

	public void onStart(){
		super.onStart();
	}

	/**
	 * Run on startup to list bluetooth paired device
	 */
	public void listBT(){
		Log.d("Main Activity", "Listing BT elements");
		if(searchBt){
			//Discover bluetooth devices
			List<String> list = new ArrayList<String>();
			list.add("");
			pairedDevices = mBluetoothAdapter.getBondedDevices();
			// If there are paired devices
			if (pairedDevices.size() > 0) {
				// Loop through paired devices
				for (BluetoothDevice device : pairedDevices) {
					// Add the name and address to an array adapter to show in a ListView
					list.add(device.getName() + "\n" + device.getAddress());
				}
			}
			//Populate drop down
			spinner1 = (Spinner) findViewById(R.id.spinner1);
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner1.setOnItemSelectedListener(this);
			spinner1.setAdapter(dataAdapter);
			
			if(DataHandler.getInstance().getID()!=0 && DataHandler.getInstance().getID() < spinner1.getCount())
				spinner1.setSelection(DataHandler.getInstance().getID());
		}
	}

	/**
	 * When menu button are pressed
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Log.d("Main Activity", "Menu pressed");
		if (id == R.id.action_settings) { //close connection		
			menuBool=false;
			Log.d("Main Activity", "disable pressed");
			if(spinner1!=null){
				spinner1.setSelection(0);
			}
			if(DataHandler.getInstance().getReader()==null)
			{
				Log.i("Main Activity", "Disabling h7");
				DataHandler.getInstance().getH7().cancel();<commit_msg>scanning device not paired with phone<commit_after>package org.marco45.polarheartmonitor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.SimpleXYSeries;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


/**
 * This program connect to a bluetooth polar heart rate monitor and display data
 * @author Marco
 *
 */
public class MainActivity extends Activity  implements OnItemSelectedListener, Observer {

	private int MAX_SIZE = 60; //graph max size
	boolean searchBt = true;
	BluetoothAdapter mBluetoothAdapter;
	List<BluetoothDevice> pairedDevices = new ArrayList<BluetoothDevice>();
	boolean menuBool = false; //display or not the disconnect option
	private XYPlot plot;
	Tracker t;//Set the Tracker
	boolean h7 = false; //Was the BTLE tested
	boolean normal = false; //Was the BT tested
	private Spinner spinner1;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.i("Main Activity", "Starting Polar HR monitor main activity");
		DataHandler.getInstance().addObserver(this);		
		AdView mAdView = (AdView) findViewById(R.id.adView);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
        AdRequest adRequest = new AdRequest.Builder().build();

        // Start loading the ad in the background.
        mAdView.loadAd(adRequest);
        
        //Verify if device is to old for BTLE
        if(	android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2){

    		Log.i("Main Activity", "old device H7 disbled");
        	h7=true;
        }
        
        //verify if bluetooth device are enabled
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if(DataHandler.getInstance().newValue){
			//Verify if bluetooth if activated, if not activate it
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
			if (!mBluetoothAdapter.isEnabled()) {
				new AlertDialog.Builder(this)
				.setTitle(R.string.bluetooth)
				.setMessage(R.string.bluetoothOff)
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) { 
						mBluetoothAdapter.enable();
						try {Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						listBT();
					}
				})
				.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) { 
						searchBt = false;
					}
				})
				.show();
			}
			else{
				listBT();
			}



			// Create Graph
			plot = (XYPlot) findViewById(R.id.dynamicPlot);
			if(plot.getSeriesSet().size()==0){
				Number[] series1Numbers = {};
				DataHandler.getInstance().setSeries1(new SimpleXYSeries(Arrays.asList(series1Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,"Heart Rate")); 
			}
			DataHandler.getInstance().setNewValue(false);

		}
		else
		{
			listBT();
			plot = (XYPlot) findViewById(R.id.dynamicPlot);

		}
		//LOAD Graph
		LineAndPointFormatter series1Format = new LineAndPointFormatter( Color.rgb(0, 0, 255), Color.rgb(200, 200, 200), null, null ); 
		series1Format.setPointLabelFormatter(new PointLabelFormatter());
		plot.addSeries(DataHandler.getInstance().getSeries1(), series1Format); 
		plot.setTicksPerRangeLabel(3);
		plot.getGraphWidget().setDomainLabelOrientation(-45);

		//ANALYTIC
		t = GoogleAnalytics.getInstance(this).newTracker("UA-51478243-1");
		t.setScreenName("Polar main page");
		t.send(new HitBuilders.AppViewBuilder().build());

	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		DataHandler.getInstance().deleteObserver(this);
	}

	public void onStart(){
		super.onStart();
	}

	/**
	 * Run on startup to list bluetooth paired device
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public void listBT(){
		Log.d("Main Activity", "Listing BT elements");
		if(searchBt){
			//Discover bluetooth devices
			final List<String> list = new ArrayList<String>();
			list.add("");
			pairedDevices.addAll(mBluetoothAdapter.getBondedDevices());
			// If there are paired devices
			if (pairedDevices.size() > 0) {
				// Loop through paired devices
				for (BluetoothDevice device : pairedDevices) {
					// Add the name and address to an array adapter to show in a ListView
					list.add(device.getName() + "\n" + device.getAddress());
				}
			}
			if(!h7){
				Log.d("Main Activity", "Listing BTLE elements");
				final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
				    @Override
				    public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
				    	if(!list.contains(device.getName() + "\n" + device.getAddress())){
				    		Log.d("Main Activity", "Adding "+device.getName());
				    		list.add(device.getName() + "\n" + device.getAddress());
				    		pairedDevices.add(device);
				    	}
				    }
				};
				
				
				  Thread scannerBTLE = new Thread(){
					    public void run(){
				    		Log.d("Main Activity", "Starting scanning for BTLE");
					    	mBluetoothAdapter.startLeScan(leScanCallback);
					     try {
							Thread.sleep(5000);
				    		Log.d("Main Activity", "Stoping scanning for BTLE");
							mBluetoothAdapter.stopLeScan(leScanCallback);
						} catch (InterruptedException e) {
						}
					    }
					  };

					  scannerBTLE.start();
			}

			//Populate drop down
			spinner1 = (Spinner) findViewById(R.id.spinner1);
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner1.setOnItemSelectedListener(this);
			spinner1.setAdapter(dataAdapter);
			
			if(DataHandler.getInstance().getID()!=0 && DataHandler.getInstance().getID() < spinner1.getCount())
				spinner1.setSelection(DataHandler.getInstance().getID());
		}
	}

	/**
	 * When menu button are pressed
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Log.d("Main Activity", "Menu pressed");
		if (id == R.id.action_settings) { //close connection		
			menuBool=false;
			Log.d("Main Activity", "disable pressed");
			if(spinner1!=null){
				spinner1.setSelection(0);
			}
			if(DataHandler.getInstance().getReader()==null)
			{
				Log.i("Main Activity", "Disabling h7");
				DataHandler.getInstance().getH7().cancel();
{'fraction_non_alphanumeric': 0.1187680191266437, 'fraction_numerical': 0.0096336403909711, 'mean_word_length': 3.9211072664359863, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1883431', 'n_tokens_mistral': 4957, 'n_tokens_neox': 4226, 'n_words': 955}