<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/Readings.php");

function getReadings($email){ //get a patients handshake result
    $check = null;

    return retrieveResults($email);
}

function getWeight($email){ //get a patients weight result
    $check = null;

    return retrieveWeight($email);
}
 
function getBPM($email){ //get a patients blood pressure result
    $check = null;

    return retrieveBPM($email);
}

function getTemp($email){ //get a patients temperature result
    $check = null;

    return retrieveTemp($email);
}

function getSys($email){ //get a patients systolic bp result
    $check = null;

    return retrieveSys($email);
}

function getDys($email){ //get a patients dstolic bp result
    $check = null;

    return retrieveDys($email);
}

?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php'); //check the user is logged in
}
?>

<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>

            <div class="header">
                <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
                <h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice">Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
            </div>
            

            
        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
<!-- Start of page content -->

<div class="container my-3" role="main">
  <h1>Register</h1>
  <p>Please fill in this form to register a new account or <a class="link" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login">login as an existing user</a> if you already have an account.</p>
  <hr>
  <div id="response"></div> <!-- Response will go here -->
  <form method = "post">
    <label for="email">Email</label>
    <input class="form-control" type="text" placeholder="Enter Email" pattern="^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" title="Please ensure the email address is valid." name="email" required>
    <label for="name">Name</label>
    <input class="form-control" type="text" placeholder="Enter Name" name="name" required>
    
    <label for="password">Password</label>
    <input class="form-control" type="password" placeholder="Enter Password" pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number." name="password" required>
    <label for="confirm">Confirm Password</label>
    <input class="form-control" type="password" placeholder="Confirm Password" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number." name="confirm" required>
    <button id="submit" type="submit" class="form-control btn btn-success mt-3">Register</button>
  </form>
</div>


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data

  include("../Controller/registerMedical.php");
  
  $login = registerUsersM( $_POST['email'], $_POST['password'], $_POST['name']);

  if ($login != "success"){
    echo "Success";
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
  }
  else {
    echo $login;
  }
    
}
?>

<?php include("templates/footer.php"); ?>
    </body>
</html>
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/Advice.php");

$check = null;

$email = $_POST["email"];

echo adviceDatabase($email); //returns all the advice for that patient based in their email

?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/User.php");

$check = null;

$email = $_POST["user_name"];
$password = $_POST["password"]; //recieve data from  mobile



$check = Login($email, $password); //perform login function


echo $check;


?>

<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/User.php");

function registerUsersM($email, $password, $name){ //register a new medical professional


    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

    if (!preg_match($email_exp, $email))
        $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
    if (strlen($password) < 8)
        $error_message .= 'You have entered too weak a password, please ensure the password is 8 characters and contains at least one letter and number. <br />';
    if (!preg_match("#[0-9]+#", $password))
        $error_message .= 'Password must include at least one number. <br />';
    if (!preg_match("#[a-zA-Z]+#", $password))
         $error_message .= 'Password must include at least one letter. <br />'; 

    if(strlen($error_message) > 0){
        return $error_message;
    }

    else{
        $check = registerUser($email, $password, $name);

        if ($check != null){ //if the registration has succeeeded 
            return $check;
        }
        else {
            return "invalid entry";
        }  
    }
}
?><file_sep>

/*
 ============================================================================
 Name        : piiotest.c
 Author      : CMP408 - <NAME> 1600964
 Version     : 0.1
 Copyright   : See Abertay copyright notice
 Description : Test App for PIIO Drivers
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h> 
#include <time.h> 
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include"piio.h"
#include "readings.c"

gpio_pin apin;
lkm_data lkmdata;
#define BUFFER_SIZE 1024

        int printRandoms(int lower, int upper, int count){ 
        int i; 
                for (i = 0; i < count; i++) { 
                        int num = (rand() % 
                        (upper - lower + 1)) + lower; 
                        return num; 

                }
        } 
  

        int getRandHR(int fd){
                int lower = 60, upper = 100, count = 1; 
                int val = printRandoms(lower, upper, count);
                return val;     
        }

        int getRandSYS(int fd){
                int count = 1; 
                return printRandoms(100, 140, count);     
        }

        int getRandDYS(int fd){
                int count = 1; 
                return printRandoms(20, 80, count);     
        }

        int getRandTemp(int fd){
                int count = 1; 
                return printRandoms(36, 40, count);     
        }
        int getRandShake(int fd){
                int count = 1; 
                return printRandoms(50, 100, count);     
        }

        int main(int argc, char *argv[]) {
        srand(time(0)); 

        int fd, ret;
        char *msg = "Message passed by ioctl\n";

        fd = open("/dev/dev/dAaronStones", O_RDWR);
        if (fd < 0) {
                printf("Can't open device file: %s\n", DEVICE_NAME);
                exit(1);
        }


        if (argc > 1) {
                if (!strncmp(argv[1], "getRandHR",8)) {
                        printf("%d",getRandHR(fd));

                }

                if (!strncmp(argv[1], "getRandSYS", 9)) {
                        printf("%d",getRandSYS(fd));
                }
                if (!strncmp(argv[1], "getRandDYS", 9)) {
                        printf("%d",getRandDYS(fd));
                }
                if (!strncmp(argv[1], "getRandTemp", 9)) {
                        printf("%d",getRandTemp(fd));
                }
                if (!strncmp(argv[1], "getRandShake", 9)) {
                        printf("%d",getRandShake(fd));
                }             
        }


        close(fd);
        return 0;
}

<file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

package com.example.honoursproject;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import static android.view.View.VISIBLE;


public class TakeTest extends AppCompatActivity implements SensorEventListener{

    private SensorManager senSensorManager;
    private Sensor senAccelerometer;
    private long lastUpdate = 0;
    private float last_x, last_y, last_z;
    private static final int SHAKE_THRESHOLD = 25; //set threshold and initilaise differetn sensors

    String doctorName;
    String email;

    FormVerfication formCheck = new FormVerfication(this); //include the form checker

    int count = 0;
    int SYS;
    int DYS;
    int Weight;
    int Temp; //setup globals


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_test);

        doctorName = getIntent().getStringExtra("doctor");
        email = getIntent().getStringExtra("email"); //get the emsil and doctor from previous functions




        senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //get permission from the user to use the camera
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor mySensor = sensorEvent.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) { //make sure we are getting readings from the accelerometer
            float x = sensorEvent.values[0];
            float y = sensorEvent.values[1];
            float z = sensorEvent.values[2]; //retrieve the x,y and z coordinate

            long curTime = System.currentTimeMillis();

            if ((curTime - lastUpdate) > 100) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;

                float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) { //is the calculated speed is greater than the threshold increase the counter by one
                    count++;
                }

                last_x = x;
                last_y = y;
                last_z = z; //replot the x,y and z coordinate

            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    protected void onPause() {
        super.onPause();
        senSensorManager.unregisterListener(this);
    }

    protected void onResume() {
        super.onResume();
        senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }


    public void Begin(View view){
        showWeights(); //ask the user for their weight
    }

    void showWeights(){
        EditText editText = findViewById(R.id.editText11);
        editText.setVisibility(VISIBLE);

        Button button = findViewById(R.id.button13);
        button.setVisibility(VISIBLE); //set the weights to visible
    }

    public void Weight(View view){ //get weight from user and ensure it meets the check then reveal next field
        EditText editText = findViewById(R.id.editText12);
        editText.setVisibility(VISIBLE);

        Button button = findViewById(R.id.button14);
        button.setVisibility(VISIBLE); 

        editText = findViewById(R.id.editText11);
        if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){
            Weight = Integer.parseInt(editText.getText().toString());
        }
        else{
            formCheck.errorFormat();
        }
    }

    public void Temp(View view){ //get Temperature from user and ensure it meets the check then reveal next field
        EditText editText = findViewById(R.id.editText13);
        editText.setVisibility(VISIBLE);

        Button button = findViewById(R.id.button15);
        button.setVisibility(VISIBLE);

        editText = findViewById(R.id.editText12);
        if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){

        Temp =  Integer.parseInt(editText.getText().toString());
        }
        else{
            formCheck.errorFormat();
        }
    }

    public void BP(View view) throws JSONException { //get BP from user and ensure it meets the check then reveal next field
        EditText editText = findViewById(R.id.editText13);

        String bp = editText.getText().toString();
        if (Boolean.toString(formCheck.intCheck(editText.getText().toString())).equals("false")){

            SYS = Integer.parseInt(bp.substring(0, 3));
            DYS = Integer.parseInt(bp.substring(4));
        }
        else{
            formCheck.errorFormat();
        }
        HR();
    }

    public void HR() throws JSONException { //get HR from user and ensure it meets the check then reveal next field
        Intent intent;
        intent = new Intent(getApplicationContext(), Measure.class);

        JSONObject obj=new JSONObject();
        obj.put("email", email);
        obj.put("doctor", doctorName);
        obj.put("weight", Weight);
        obj.put("count", count);
        obj.put("temperature", Temp);
        obj.put("sys", SYS);
        obj.put("dys", DYS); //pack the reuslts into a JSON object

        if (Boolean.toString(formCheck.simpleCheck(Integer.toString(Weight))).equals("true") || //final check on the data
                Boolean.toString(formCheck.simpleCheck(Integer.toString(Temp))).equals("true") ||
                Boolean.toString(formCheck.simpleCheck(Integer.toString(SYS))).equals("true")||
                Boolean.toString(formCheck.simpleCheck(Integer.toString(DYS))).equals("true"))
        {
            formCheck.error();
        }
        else {
            intent.putExtra("email", obj.toString()); //else send it to the next acrivity
            startActivity(intent);
        }
    }


}
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/Messages.php");

function getMessages($email){
    $check = null;

    return retrieveMessages($email); //retrieve all the messages between a doctor and a patient based on that email
}

?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/User.php");

$check = null;

$email = $_POST["email"];
$doctor = $_POST["doctor"];

$checkDoctor = doctorCheck($doctor); //check the doctor exists

if ($checkDoctor != 1){
    echo "This doctor does not exist";
}

else {

    $check = doctorChange($email, $doctor); //doctor exists proceed with the change
    echo $check;
}
?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

	include("../Model/conn.php");
	$db = new dbObj();
	$conn =  $db->getConnstring();

    
function adviceDatabase($email) //function to get all the advice from the database based on a user's email
{
    global $conn;
    $sql = $conn->prepare("SELECT * from Advice where email=? ORDER BY Timestamp DESC");
    $sql->bind_param("s", $email);
    $sql->execute();
    $sql->bind_result($email, $advice, $doctor, $time);

    $count = 0;
    while ($sql->fetch()) {
        $json[$count] =  array(
            'advice' => $advice,
            'doctor' => $doctor,
            'time' => $time);
        $count++;
    }
    return json_encode($json);

}

function sendAdvice($email, $name, $advice){ //function to store the advice that has been sent to the server
    global $conn;
    $sql = $conn->prepare("INSERT INTO Advice (email, Advice, Doctor) VALUES(?,?,?)");
    $sql->bind_param("sss", $email, $advice, $name);
    $sql->execute();
    
    $affectedRows = $sql->affected_rows;

    if ($affectedRows == 1) {
        return "Success";
    } 
    else {
        return null;
    }
}


?><file_sep><title>Honours Project - 1600964</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <link rel="icon" href="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.freepnglogos.com%2Fuploads%2Fs-letter-logo-png-15.png">
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php'); //check the user is logged in
}
?>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?> <!--Include the templates  -->

            <div class="header">
                <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Patient Advice</h1></a>
                <h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing">Home</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
            </div>

            <h4>Select a patient to give advice</h4>
            <form method="post"> <!--Form to go patient advice  -->

                <label for="email">Email</label>
            <input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>   
            <button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button>

            </form>
            <?php
            if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data

                include("../Controller/getAdviceM.php");
                $email = $_POST['email'];
                $_SESSION['email'] = $_POST['email'];
                $advice = getAdvice($_SESSION['email']);
                $advice = json_decode($advice);

                if ($advice == null){
                  echo "Invalid Entry";
                }
                
                else {
                    $_SESSION['setAdvice'] = true;
                    for ($i=0; $i<sizeof($advice);$i++){
                        echo $advice[$i]->advice . "  " . $advice[$i]->time . "</br></br>";
                    }
                }
                if (isset($_SESSION['setAdvice'])){
                    $var = json_decode($_SESSION['userData']);

                    echo "<form method=post id='adviceSend'>
    
                        <label for=email>Enter Advice</label>
                        <input class='form-control' type='text' placeholder='Enter Advice' name='advice' required>   
                        <input name=docName type=hidden value='" . $var->name . "'>
                        <input name=patientEmail type=hidden value='" . $email . "'>
                        <button id='postMessage' type='submit' class='form-control btn btn-success mt-3'>Send Advice</button>
        
                        </form>
                    ";
                }
            }
            ?>

            <script>
                $("#postMessage").click(function(){        
                    $.post("../Controller/sendAdvice.php", $("#adviceSend").serialize(),function(data){
                        alert(data);
                    });
                });
            </script>
        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>

            <div class="header">
                <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
                <h3><NAME> | BSc Computing | Abertay University</h3> <!-- A simple page where the user is directed to view the website-->
            </div>

        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

	include("../Model/conn.php");
	$db = new dbObj();
	$conn =  $db->getConnstring();

    
function retrieveMessages($email) //retrieve all the messages in ascending order based on a user's email
{
    global $conn;
    $sql = $conn->prepare("SELECT * from Messages where email=? ORDER BY Timestamp ASC");
    $sql->bind_param("s", $email);
    $sql->execute();
    $sql->bind_result($email, $doctor, $message, $time);

    $count = 0;
    while ($sql->fetch()) {
        $json[$count] =  array(
            'message' => $message,
            'doctor' => $doctor,
            'time' => $time);
        $count++;
    }
    return json_encode($json);
    $conn->close;


}

function sendMessageP($email, $message){ //send a messade to the database to be later processed by the server
    global $conn;
    $value = 0;
    $sql = $conn->prepare("INSERT INTO Messages (email, Doctor, Message) Values(?,?,?)");
    $sql->bind_param("sis", $email, $value, $message);
    $sql->execute();

    $affectedRows = $sql->affected_rows;

    if ($affectedRows == 1) {
        return "Success";
    } 
    else {
        return null;
    }

    $conn->close;

}

?><file_sep>include ':app'
rootProject.name='Honours project'
<file_sep>/*
 ============================================================================
 Name        : piiotest.c
 Author      : CMP408 - <NAME> 1600964
 Version     : 0.1
 Copyright   : See Abertay copyright notice
 Description : Test App for PIIO Drivers
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h> 
#include <time.h> 
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
//Include eHealth library (it includes arduPi)
#include "eHealth.h"

gpio_pin apin;
lkm_data lkmdata;
#define BUFFER_SIZE 1024

 

        int getHR(int fd){
                return getBPM() // Returns the heart beats per minute.

        }

        int getSYS(int fd){
            getSystolicPressure(i)    // Returns the  value of the systolic pressure number i.
   
        }

        int getDYS(int fd){
            getDiastolicPressure(i)   // Returns the  value of the diastolic pressure number i.

        }

        int getTemp(int fd){
            int getTemperature() // Returns the corporal temperature.
   
        }
<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests


    $email = $_GET["email"];
    $count = $_GET["count"];
    $weight = $_GET["weight"];
    $temp = $_GET["temperature"];
    $hr = $_GET["hr"];
    $dys = $_GET["dys"];
    $sys = $_GET["sys"];
    $doctor = $_GET["doctor"]; //recieve data from iot device

    
    include("../Model/Readings.php");

    if(!is_numeric($weight) && !is_numeric($temp) && !is_numeric($count)  && !is_numeric($hr)  && !is_numeric($dys)  && !is_numeric($sys)){  // return **TRUE** if it is numeric
        echo "Inavlid Inputs";
    }

    else{
        recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys);
    }



?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests of the different patients

include("../Model/User.php");

$check = null;
$email = $_POST["user_name"];
$password = $_POST["password"];
$json = $_POST["json"];
$doctor = $_POST["doctor"];

$checkDoctor = doctorCheck($doctor);

if ($checkDoctor != 1){
    echo "This doctor does not exist";
}

$emailCheck = emailCheck($email);

if ($emailCheck == 1){
    echo "This email has already been taken";
}

    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

    if (!preg_match($email_exp, $email))
        $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
    if (strlen($password) < 8)
        $error_message .= 'You have entered too weak a password, please ensure the password is 8 characters and contains at least one letter and number. <br />';
    if (!preg_match("#[0-9]+#", $password))
        $error_message .= 'Password must include at least one number. <br />';
    if (!preg_match("#[a-zA-Z]+#", $password))
         $error_message .= 'Password must include at least one letter. <br />'; 

    if(strlen($error_message) > 0){
        echo $error_message;
    }

    else{
        $check = Signup($email, $password, $json, $doctor);
        echo $check;
    }

?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>
<!-- Start of page content -->

<div class="container d-flex h-100 w-100" role="main">
	<div class="row align-items-center h-100 w-100">
		<div class="span6 text-center mx-auto mt-5">
			<p>Uh oh, looks like something went wrong...</p> <!--There is an error and the user will be directed here-->
			<p><a class="btn btn-success" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index">Go to Home page</a> or <a class="btn btn-success" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/support">Go to Support page</a></p>
		</div>
	</div>
</div>
<!-- End of page content -->
<?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

	include("conn.php");
	$db = new dbObj();
	$conn =  $db->getConnstring();


    function recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys){ //store a reading indexed by a user's email
        global $conn;
        $value = 0;
        $sql = $conn->prepare("INSERT INTO Results (email, Doctor, Result, HR, Weight, Temperature, Sys, Dys) Values(?,?,?,?,?,?,?,?)");
        $sql->bind_param("ssiiiiii", $email, $doctor, $count, $hr, $weight, $temp, $sys, $dys);
        $sql->execute();

        $affectedRows = $sql->affected_rows;

            if ($affectedRows == 1) {
                return "Test Complete!";
            } 
            else {
                return null;
            }
    }

    function retrieveResults($email){ //get all the handshake results from a table based on the user's email
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $Result,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }

    function retrieveAll($email){ //retrieve all the results from a server 
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'result' => $Result,
                'hr' => $BPM,
                'weight' => $weight,
                'temp' => $Temp,
                'sys' => $Sys,
                'dys' => $Dys,
                'time' => $time);
            $count++;
        }
        return json_encode($json);
    }

    function retrieveBPM($email){ //retrieve all the heart rate measures
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $BPM,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }

    function retrieveWeight($email){ //retrieve all the weight measures
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $weight,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }

    function retrieveTemp($email){ //retrieve all the temperature measures
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $Temp,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }

    function retrieveSys($email){ //retireve all the systolic bp readings 
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $Sys,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }
    function retrieveDys($email){ //retireve all the dystolic bp readings 
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $json[$count] =  array(
                'y' => $Dys,
                'label' => $time);
            $count++;
        }
        return json_encode($json);
    }

?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

	include("../Model/conn.php");
	$db = new dbObj();
	$conn =  $db->getConnstring();

    
function Login($email, $pass) //function to validate a user's login details
{
    global $conn;
    $sql = $conn->prepare("SELECT * from Patients where email=? LIMIT 1");
    $sql->bind_param("s", $email);
    $sql->execute();
    $sql->bind_result($key, $email, $password, $json, $doctor, $time);

    if ($email == null){
        return "Incorrect credentials, please try again";
    }    
    while ($sql->fetch()) {
        if (password_verify($pass, $password) != false){
            return json_encode(array(
                'id' => $key,
                'email' => $email,
                'json' => json_decode($json),
                'doctor' => $doctor));
        }
        else {
            return "Incorrect credentials, please try again";
        }
    }

}

function retriveAccountResults($email){ //retrieves the results for the handshake test only 
        global $conn;
        $sql = $conn->prepare("SELECT * from Results where email=? ORDER BY Timestamp DESC");
        $sql->bind_param("s", $email);
        $sql->execute();
        $sql->bind_result($email, $doctor, $Result, $BPM, $weight, $Temp, $Sys, $Dys, $time);

        $count = 0;
        while ($sql->fetch()) {
            $array[$count] = array(
                'result' => $Result,
                'time' => $time);
            $count++;
        }
        return json_encode($array);
        
}

function LoginM($email, $pass){ //login section for the medical professionals
    global $conn;
    $sql = $conn->prepare("SELECT * from Medical where email=? LIMIT 1");
    $sql->bind_param("s", $email);
    $sql->execute();
    $sql->bind_result($email, $name, $password);

    if ($email == null){
        return "Incorrect credentials, please try again";
    }    

    while ($sql->fetch()) {
        if (password_verify($pass, $password) != false){
            return json_encode(array(
                'email' => $email,
                'name' => $name,
                'password' => $password));
        }
        else {
            return "Incorrect credentials, please try again";
        }
    }
}

function Name($email, $file) //function to update a user's name
{
    $file = json_encode($file);
    global $conn;
    $sql = $conn->prepare("UPDATE Patients SET jsonData=? WHERE email=?");
    $sql->bind_param("ss", $file, $email);
    $status = $sql->execute();

    if ($status === false) {
        return "fail";
    }

    else {
        return "success";
    }
}

function Signup($email, $password, $json, $doctor){ //sign up function 

    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    global $conn;
    $sql = $conn->prepare("INSERT INTO Patients (email, password, jsonData, Doctor) Values(?,?,?,?)");
    $sql->bind_param("ssss", $email, $passwordHash, $json, $doctor);
    $sql->execute();

    $affectedRows = $sql->affected_rows;
    if ($affectedRows == 1) {
        return "Success";
    } 
    else {
        return "fail";
    }
}



function checkEmail($email){ //a check to ensure the email has not been used prior to registrations
    global $conn;
    $sql = $conn->prepare("SELECT Primary_Key from Patients where email=? LIMIT 1");
    $sql->bind_param("s", $email);

    if (mysqli_num_rows($sql->execute()) > 0) {
        return true;
    }

}

function doctorChange($email, $doctor){ //function to change the user's doctor 
    global $conn;
    $sql = $conn->prepare("UPDATE Patients SET Doctor=? WHERE email=?");
    $sql->bind_param("ss", $doctor, $email);
    $status = $sql->execute();

    if ($status === false) {
        return "fail";
    }

    else {
        return "success";
    }
}

function doctorCheck($doctor){ //check to ensure the doctor exists 
    global $conn;
    $sql = $conn->prepare("SELECT * from Medical where name=?");
    $sql->bind_param("s", $doctor);
    $sql->execute();

    $count = 0;
    while ($sql->fetch()) {
        $count++;
    }
    if ($count > 0){
        return 1;
    }
    else{
        return 0;
    }
}

function emailCheck($email){ //check to see if the email is already in use 
    global $conn;
    $sql = $conn->prepare("SELECT * from Patients where email=?");
    $sql->bind_param("s", $email);
    $sql->execute();

    $count = 0;
    while ($sql->fetch()) {
        $count++;
    }
    if ($count > 0){
        return 1;
    }
    else{
        return 0;
    }
}

    
function registerUser($email, $password, $name){ //registers a medical professional
    global $conn;
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);

    $sql = $conn->prepare("INSERT INTO Medical (email, name, password) Values(?,?,?)");
    $sql->bind_param("sss", $email, $name, $passwordHash);
    $sql->execute();

    $affectedRows = $sql->affected_rows;
    if ($affectedRows == 1) {
        return "Success";
    } 
    else {
        return null;
    }
        
}


?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests


$advice = $_POST["advice"];
$docName = $_POST["docName"];
$patientEmail = $_POST["patientEmail"]; //recieve the mobile data

include("../Model/Advice.php");

$response = sendAdvice($patientEmail, $docName, $advice); //post advice to the server

echo $response;

?><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/User.php");

$check = null;

$email = $_POST["email"];
$file = $_POST["file"]; //recieve data from mobile

$check = Name($email, $file); //change a user's name
echo $check;

?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>
<!-- Start of page content -->

<div class="container my-3" role="main">
    <div class="row">
        <div class="col-md-6 col-sm-12">
            <h2>Frequently Asked Questions</h2>

            <h3>How will my data be stored?</h3>
            <p class="small">
            Your data will be securely stored in the university's MySQL database on the 
            Mayar server.
            </p>

            <h3>Does this application ue 'real life' data/results?</h3>
            <p class="small">
            No all data/reuslts are fabricated or taken from willing volunteersto prove the 
            concept works. No patient data is ever used. 
            </p>

            <h3>Where is this project being developed?</h3>
            <p class="small">
            This project is being developed within the Univeristy of Abertay Dundee's campus.
            </p>

            <h3>What technologies does the project utilise?</h3>
            <p class="small">
            To develop this website the technologies used are the LAMP (or Linux Apache MySQL and PHP)
            stack with HTML, CSS and JavaScript to suppliment the website. 
            </p>
            <h3>What else is being developed to couple with this website?</h3>
            <p class="small">
            A mobile device to test patients Parkinson's/Dementia state and an IoT device to read a subject's
            vital signs. 
            </p>
            <h3>My question isn't answered here what should I do?</h3>
            <p class="small">
            Please fill out the form on this page and it will send an email to a member of the development team
            who will answer your query in no time.
            </p>
        </div>
        <div class="col-md-6 col-sm-12">
            <h2>Contact Us</h2>
            <form action="../Controller/contact.php" method="POST">
                <label for="subject">Subject</label>
                <select class="form-control" name="subject">
                    <option value="Feedback">Feedback</option>
                    <option value="Report">Bug Report</option>
                    <option value="Complaint">Complaint</option>
                    <option value="Other">Other</option>
                </select>
                <label for="email">Email Address</label>
                <input class="form-control" type="email" name="email" required pattern="^(?=.{5,80}$)[\S]+@[\S]+\.[\S]+$">
                <label for="message">Message</label>
                <textarea class="form-control" name="message" rows="6" required pattern="^.{1,1200}$"></textarea>
                <input class="form-control btn btn-success mt-3" type="submit" value="Submit">
            </form>
        </div>
    </div>
</div>

<!-- End of page content -->
<?php include("templates/footer.php"); ?>
</body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/Advice.php");

function getAdvice($email){

    return adviceDatabase($email); //get advoce for the medical practitioners 
}

?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<?php
session_start();
if (isset($_SESSION['userData']) == false){
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}

$Details = json_decode($_SESSION['userData']);  //get and decode the sessions data
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>
        <div class="container my-3" role="main">
        <h1>My Account</h1>
        <p>Here you can view and modify the your account details.</p> 
        <hr>
        
        <h2 class="mt-5">Change Email</h2>
        <div id="responseChangeEmail"></div> <!-- Response will go here -->
        <form id="formChangeEmail" method="post">
            <label for="password">Current Password</label>
            <input name="password" class="form-control" type="password" placeholder="Enter Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
            <label for="newEmail">New Email</label>
            <input name="newEmail" class="form-control" type="text" placeholder="Enter Email" required pattern="^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$" title="Please ensure the email address is valid.">
            <button id="submitChangeEmail" type="submit" class="form-control btn btn-success mt-3">Change Account Email</button>
        </form>

        <h2 class="mt-5">Change Password</h2>
        <div id="responseChangePassword"></div> <!-- Response will go here -->
        <form id="formChangePassword" method="post">
            <label for="password">Current Password</label>
            <input name="password" class="form-control" type="password" placeholder="Enter Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
            <label for="newPassword">New Password</label>
            <input name="newPassword" class="form-control" type="password" placeholder="Enter New Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
            <label for="newConfirm">Confirm New Password</label>
            <input name="newConfirm" class="form-control" type="password" placeholder="Confirm New Password" required pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,80}$" title="Please ensure the password is 8 characters and contains at least one letter and one number.">
            <button id="submitChangePassword" type="submit" class="form-control btn btn-success mt-3">Change Account Password</button>
        </form>

        <h2 class="mt-5">Change Name</h2>
        <div id="responseChangePassword"></div> <!-- Response will go here -->
        <form id="formChangePassword" method="post">
            <label for="password">New Name</label>
            <input name="name" class="form-control" type="text" placeholder="Enter Name">
            <button id="submitChangePassword" type="submit" class="form-control btn btn-success mt-3">Change Account Name</button>
        </form>

        </div>

        <!-- Start of AJAX script -->

        <script>
        // Change email form
        $('#formChangeEmail').on('submit', function(e)
        {
            e.preventDefault(); // Prevent default form behaviour so we can override it

            $('#submitChangeEmail').prop('disabled', true); // Disable submit button to prevent multiple submissions

            $.post('../Controller/change_email.php', $('#formChangeEmail').serialize(), function(data)
            {
            let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
            $('#responseChangeEmail').html(response); // Display response message
            $('#submitChangeEmail').prop('disabled', false);
            }, 'json');
        });

        // Change password form
        $('#formChangePassword').on('submit', function(e)
        {
            e.preventDefault(); // Prevent default form behaviour so we can override it

            $('#submitChangePassword').prop('disabled', true); // Disable submit button to prevent multiple submissions
            
            $.post('../controller/change_password.php', $('#formChangePassword').serialize(), function(data)
            {
            let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
            $('#responseChangePassword').html(response); // Display response message
            $('#submitChangePassword').prop('disabled', false);
            }, 'json');
        });

        // Delete user form
        $('#formDeleteAccount').on('submit', function(e)
        {
            e.preventDefault(); // Prevent default form behaviour so we can override it

            if (window.confirm("Are you sure you want to permanently delete your account?"))
            {
            $('#submitDeleteAccount').prop('disabled', true); // Disable submit button to prevent multiple submissions

            $.post('../controller/delete_user.php', $('#formDeleteAccount').serialize(), function(data)
            {
                let response = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + '">' + data.message + '</div>';
                $('#responseDeleteAccount').html(response); // Display response message
                $('#submitDeleteAccount').prop('disabled', false);
                if (data.success)
                setTimeout(function () { location.href = 'index' }, 1500);  
            }, 'json');
            }
        });
        </script>

        <!-- End of AJAX script -->


        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/header.php"); ?>
</head>
    <body>
        <?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/nav.php"); ?>

            <div class="header">
                <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Honours Project</h1></a>
                <h3><NAME> | BSc Computing | Abertay University</h3> <!-- A simple page where the user is directed to view the website-->
            </div>
<h1>Enter Your Test Results</h1>
<div class="container my-3">
  <form method="post">

    <label for="email">Email</label>
    <input class="form-control" type="text" placeholder="Enter Email" name="email" required>

    <label for="doctor">Doctor</label>
    <input class="form-control" type="text" placeholder="Enter Doctor" name="doctor" required>

    <label for="hr">Heart Rate</label>
    <input class="form-control" placeholder="Enter your HR" name="hr" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandHR');?>"required>

    <label for="sys">Systolic Blood Pressure</label>
    <input class="form-control" placeholder="Enter your Systolic BP" name="sys" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandSYS');?>"required>

    <label for="dys">Dystolic Blood Pressure</label>
    <input class="form-control" placeholder="Enter your Dystolic BP" name="dys" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandDYS');?>"required>

    <label for="weight">Weight</label>
    <input class="form-control" placeholder="Enter your Weight" name="weight" required>

    <label for="bp">Temperature</label>
    <input class="form-control" placeholder="Enter your temperature" name="temperature" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandTemp');?>"required>

    <input class="form-control" type="hidden" name="count" value="<?=shell_exec('sudo /home/pi/Submission2/Driver_Test_App/a.out getRandShake');?>"required>

    

    <button type="submit" class="form-control btn btn-success mt-3">Enter Results</button>
  </form>
</div>
<?php


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["email"])){
    $var = "https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/Controller/iotRecorder.php?email=". $_POST['email'] . "&count=" . $_POST['count'] . "&doctor=" . $_POST['doctor'] . "&hr=" . $_POST['hr'] . "&sys=" . $_POST['sys'] . "&dys=" . $_POST['dys'] . "&weight=" . $_POST['weight'] . "&temperature=" . $_POST['temperature'];
    $var = str_replace(" ", "%20", $var);


    include($var);


}

?>

<?php include("https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/templates/footer.php"); ?>
    </body>
</html>
<file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

package com.example.honoursproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class UpdateInformation extends AppCompatActivity {
    String doctorName;
    String email;
    String json;
    String Name;
    String Mobile;
    Boolean Parkinsons;
    Boolean Other;
    Boolean Dementia; //setup globals

    FormVerfication formCheck = new FormVerfication(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_information);

        setupFields(); //set the fields
    }


    private Void setupFields(){


        doctorName = getIntent().getStringExtra("doctor");
        email = getIntent().getStringExtra("email");
        json = getIntent().getStringExtra("json"); //get data from previous activity

        EditText doctor = findViewById(R.id.editText6);
        doctor.setText(doctorName); //set the doctor field

        try { //decode the JSON
            JSONObject userJson = new JSONObject(json);

            Mobile = userJson.getString("Mobile");
            Name = userJson.getString("name");
            Parkinsons = userJson.getBoolean("Parkinsons");
            Dementia = userJson.getBoolean("Dementia");
            Other = userJson.getBoolean("Other");

            EditText Phone = findViewById(R.id.editText9);
            Phone.setText(Mobile);

            EditText patientName = findViewById(R.id.editText3);
            patientName.setText(Name);
        }

        catch (Exception e) {
            Log.d("fail",json);
            Log.d("fail","fail");
        }




        return null;
    }

    public void nameChange(View v ){ //change the name for a user

        try {
            EditText editText = findViewById(R.id.editText3);

            Name = editText.getText().toString();
            if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
                formCheck.errorFormat();
            }
            else {
                JSONObject jsonObject = new JSONObject(json);
                jsonObject.remove("name");
                jsonObject.put("name", Name);
                json = jsonObject.toString();
            }
        }
        catch (JSONException e){
            formCheck.error();
            e.printStackTrace();
        }
        String file = json;

        String type = "Json";
        if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
            formCheck.error();
        }
        else {
            UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);
            backgroundWorker.execute(type, file, email, "nameChange");
        }
    }
    public void doctorChange(View v ){ //change the doctor for a user
        String type = "Doctor";
        EditText editText = findViewById(R.id.editText6);
        String doctorName = editText.getText().toString();
        if (Boolean.toString(formCheck.mobileCheck(Mobile)).equals("true")){
            formCheck.errorFormat();
        }
        else {
            if (Boolean.toString(formCheck.simpleCheck(doctorName)).equals("true")) {
                formCheck.error();
            } else {
                UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);
                backgroundWorker.execute(type, doctorName, email, "doctorChange");
            }
        }
    }

    public void mobileChange(View v ){ // change a user's mobile number
        try {
            EditText editText = findViewById(R.id.editText9);
            Mobile = editText.getText().toString();

            if (Boolean.toString(formCheck.intCheck(Mobile)).equals("true")){
                formCheck.errorFormat();
            }
            else {

                JSONObject jsonObject = new JSONObject(json);
                jsonObject.remove("Mobile");
                jsonObject.put("Mobile", Mobile);
                json = jsonObject.toString();
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        String file = json;
        String type = "Json";

        if (Boolean.toString(formCheck.simpleCheck(Mobile)).equals("true")){
            formCheck.error();
        }
        else {
            UpdateInformationWorker backgroundWorker = new UpdateInformationWorker(this);

            backgroundWorker.execute(type, file, email, "mobileChange");
        }

    }
}
<file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>

<!-- Start of page content -->

<div class="container my-3">
  <h1>Login</h1>
  <p>Please enter your details on this page to login to your account or <a class="link" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/signup">register as a new user</a> if you do not already have an account.</p>
  <hr>
  <div id="response"></div> <!-- Response will go here -->
  <form method="post">

    <label for="email">Email</label>
    <input class="form-control" type="text" placeholder="Enter Email" name="email" required>

    <label for="password">Password</label>
    <input class="form-control" type="password" placeholder="Enter Password" name="password" required>

    <button type="submit" class="form-control btn btn-success mt-3">Login</button>
  </form>
  <?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data

  include("../Controller/medicalLogin.php");


  $login = LoginMedical( $_POST['email'], $_POST['password']);

  if ($login == null){
    echo "Invalid Entry";
  }
  else {
    session_start();
    $_SESSION['userData'] = $login;
    
    echo "Success";

    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing');
  }
    
}
?>
</div>

<!-- End of page content -->
<?php include("templates/footer.php"); ?>

<!-- Start of AJAX script -->



<!-- End of AJAX script -->
</body>
</html>
<file_sep>package com.example.honoursproject;

import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.util.regex.Pattern;

public class FormVerfication {

    Context context; //get the context


    FormVerfication(Context ctx){

        context = ctx;
    }


    public Boolean simpleCheck(String value){ //checks for special characters
        Pattern regex = Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");

        if (regex.matcher(value).find()) {
            Log.e("TTT", "SPECIAL CHARS FOUND");
            return true;
        }
        else{
            return false;
        }
    }

    public Boolean stringCheck(String value){ //checks for integer characters

        Pattern regex = Pattern.compile("[0-9]");

        if (regex.matcher(value).find()) {
            Log.e("TTT", "SPECIAL CHARS FOUND");
            return true;
        }
        else{
            return false;
        }
    }

    public Boolean intCheck(String value){ //checks for string characters
        Pattern regex = Pattern.compile("[a-zA-Z]");

        if (regex.matcher(value).find()) {
            Log.e("TTT", "SPECIAL CHARS FOUND");
            return true;
        }
        else{
            return false;
        }
    }

    public Boolean mobileCheck(String value){ //checks for a correct mobile number
        if (value.length() != 11 || intCheck(value)){

            errorFormat();

            return true;
        }
        else return false;
    }

    public void error(){ //general error messages
        Toast.makeText(context, "Error in your data entry",Toast.LENGTH_SHORT).show();

    }

    public void errorFormat(){ //incorrect format error message
        Toast.makeText(context, "Error in the format of your data",Toast.LENGTH_SHORT).show();

    }

}
<file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
$data = json_decode($_SESSION['userData']);
$email = $data->email;
$name = $data->name;

?>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>

            <div class="header">
                <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index"><h1>Patient Messenger</h1></a>
                <h2>Dr <?=$name?></h2>
                <h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/results.php">View Patient Results</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice.php">Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing.php">Home</a></h3>
            </div>
            <h4>Select a patient to message</h4>
            <form method="post">

                <label for="email">Email</label>
            <input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>   
            <button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button>

            </form>
            <?php
            if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data

                include("../Controller/getMessagesM.php");
                
                $email = $_POST['email']; // required
              
                $message = getMessages($_POST['email']);
                $message = json_decode($message);

                if ($message == null){
                  echo "Invalid Entry";
                }
                
                else {
                    for ($i=0; $i<sizeof($message);$i++){
                        if ($message[$i]->doctor == 1){
                            echo "<b>Dr " . $name . ": </b>" . $message[$i]->message .  "</br></br>";
                        }
                        else{
                            echo "<b>Patient: </b>" . $message[$i]->message . "</br></br>";
                        }
                    }
                }
            }

            if (isset($message)){
                echo "<form method=post>

                <label for=email>Enter Message</label>
            <input class='form-control' type='text' placeholder='Enter Message' name='message' required>   
            <button id='submit' type='submit' class='form-control btn btn-success mt-3'>Send Message</button>

            </form>
                ";
            }

            ?>
        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

package com.example.honoursproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;

import org.json.JSONObject;

public class speakDoctor extends AppCompatActivity {
    String doctorName;
    String email;

    FormVerfication formCheck = new FormVerfication(this);



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speak_doctor);

        doctorName = getIntent().getStringExtra("doctor"); //retrieve the doctor and the user's email from the previous activity
        email = getIntent().getStringExtra("email");

        getMessages();
    }

    private void getMessages(){
        String type = "getMessages";

        messagesWorker backgroundWorker = new messagesWorker(this);
        backgroundWorker.execute(type, email, doctorName); //start the background worker to fetch the previous messages


    }

    public void sendMessage(View view){ //send a message to server
        String type = "sendMessage";
        EditText editText = findViewById(R.id.editText4);
        String Message = editText.getText().toString();

        if (Boolean.toString(formCheck.simpleCheck(Message)).equals("true")){ //check the message sent passes security checks
            formCheck.error();
        }
        else {
            messagesWorker backgroundWorker = new messagesWorker(this);
            backgroundWorker.execute(type, email, Message); //message passes send to the background worker

            getMessages(); //update the message thread
        }
    }
}
<file_sep>Link to Web App - https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/index

for system diagram use - https://www.draw.io/

Gantt Chart - created using project Libre (free and open source)

Email/password for Mobile App - <EMAIL>/password

email/password for web app - <EMAIL>/password
<file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<?php
session_start();
if (isset($_SESSION['userData']) == false){
    header('Location: '.'https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/login.php');
}
?>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index">
    <?php include("templates/header.php"); ?>
</head>
    <body>
        <?php include("templates/nav.php"); ?>

            <div class="header">
                <a href="index"><h1>Patient Results</h1></a>
                <h3><a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/landing">Home</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/advice" >Give Advice to Patients</a> | <a href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/messenger">Patient Chats</a></h3>
            </div>
            <h4>Select a patient to view their results</h4>
            <form method="post">

                <label for="email">Email</label>
            <input class="form-control" type="text" placeholder="Enter Email" title="Please ensure the email address is valid." name="email" required>   
            <button id="submit" type="submit" class="form-control btn btn-success mt-3">Select Patient</button> <!--Select a patient  -->

            </form>
            <?php
            if ($_SERVER["REQUEST_METHOD"] == "POST") { //get user data

                include("../Controller/getResultsM.php");
                
                $results = getReadings($_POST['email']);

                $heartRate = getBPM($_POST['email']);

                $weight = getWeight($_POST['email']);

                $temperature = getTemp($_POST['email']);

                $Sys = getSys($_POST['email']);

                $Dys = getDys($_POST['email']);


                if ($results == null){
                  echo "Invalid Entry";
                }
                
                else {
                    $dataPoints = json_decode($results);
                    $dataPoints2 = json_decode($heartRate);
                    $dataPoints3 = json_decode($Sys);
                    $dataPoints4 = json_decode($Dys);
                    $dataPoints5 = json_decode($weight);
                    $dataPoints6 = json_decode($temperature); //get all the different results
                }
            }

            ?>

            <script>
            window.onload = function () {
            
            var chart = new CanvasJS.Chart("chartContainer", {
                title: {
                    text: "Hand Shake test Results"
                },
                axisY: {
                    title: "Number of registered shakes"
                },
                data: [{
                    type: "line",
                    dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
                }]
            });
            chart.render();

                var chart = new CanvasJS.Chart("chartContainer1", {
                title: {
                    text: "Heart Rate"
                },
                axisY: {
                    title: "Bpm (Beats per Minute)"
                },
                data: [{
                    type: "line",
                    dataPoints: <?php echo json_encode($dataPoints2, JSON_NUMERIC_CHECK); ?> //Canvas.JS functions for displaying graphs of data
                }]
            });
            chart.render();
            var chart = new CanvasJS.Chart("chartContainer2", {
                title: {
                    text: "Patient's Weight"
                },
                axisY: {
                    title: "Kilograms"
                },
                data: [{
                    type: "line",
                    dataPoints: <?php echo json_encode($dataPoints5, JSON_NUMERIC_CHECK); ?>
                }]
            });
            chart.render();

            var chart = new CanvasJS.Chart("chartContainer3", {
                title: {
                    text: "Patient's Temperature"
                },
                axisY: {
                    title: "Degrees Celsius"
                },
                data: [{
                    type: "line",
                    dataPoints: <?php echo json_encode($dataPoints6, JSON_NUMERIC_CHECK); ?>
                }]
            });
            chart.render();
            
            var chart = new CanvasJS.Chart("chartContainer4", {
                title: {
                    text: "Blood Pressure"
                },
                axisX: {
                    valueFormatString: "MMM YYYY"
                },
                axisY2: {
                    title: "Millimeters of Hg"
                },
                toolTip: {
                    shared: false
                },
                legend: {
                    cursor: "pointer",
                    verticalAlign: "top",
                    horizontalAlign: "center",
                    dockInsidePlotArea: true,
                    itemclick: toogleDataSeries
                },
                data: [{
                    type:"line",
                    axisYType: "primary",
                    name: "Systolic",
                    showInLegend: true,
                    markerSize: 6,
                    dataPoints: <?php echo json_encode($dataPoints3, JSON_NUMERIC_CHECK); ?>
                },
                {
                    type: "line",
                    axisYType: "primary",
                    name: "Dystolic",
                    showInLegend: true,
                    markerSize: 6,
                    dataPoints: <?php echo json_encode($dataPoints4, JSON_NUMERIC_CHECK); ?>
                }]
            });
            chart.render();

            function toogleDataSeries(e){
                if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                    e.dataSeries.visible = false;
                } else{
                    e.dataSeries.visible = true;
                }
                chart.render();
            }
            }
            </script>
            </head>
            <body>
            <?php
            for ($i = 0; $i<5; $i++){
                if ($i == 0){
                    echo "<div id='chartContainer' style='height: 370px; width: 100%;'></div>";
                }
                else {
                    echo "<div id='chartContainer" . $i . "' style='height: 370px; width: 100%;'></div>";
                }
            }
            ?>
            <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
        <?php include("templates/footer.php"); ?>
    </body>
</html><file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

    $from = $_POST["email"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    // Validation
    if (!preg_match('/^(?=.{5,80}$)[\S]+@[\S]+\.[\S]+$/', $from)) // Validate email
    {
        header("location: ../View/error");
        exit;
    }

    if (!preg_match('/^.{1,1200}$/', $message)) // Validate message
    {
        header("location: ../View/error");
        exit;
    }

    // Send email to movie recommender address
    $to = "<EMAIL>";
    $fullMessage = wordwrap("Elderly Helper - From: $from\n\n$message");
    mail($to, 'Elderly Helper - ' . $subject, $fullMessage); //change


    // Send email to sender to confirm that the message was sent
    $fullMessage = wordwrap("You sent the following message to the Elderly Helper team under the subject \"$subject\":\n\n$message");
    mail($from, 'Thank you for your feedback', $fullMessage);
    header("location: ../View/messageSent");
?><file_sep><!-- 
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/View/css/index.css">
    <?php include("templates/header.php"); ?> <!--Include the header template  -->
</head>
    <body>
        <?php include("templates/nav.php"); ?> <!--Include the nav template  -->
        <h1 style="text-align:center;">About the Project</h1>
        <hr>
        <div class="about">
            <h3>Module Code : CMP400</h3>
            <h3>Project Name : Implementing improved methods of regional care through the use of IoT, Mobile Devices and Website Applications</h3> <!--About the website -->
            <h3>Developed By : <NAME></h3>
            <h3>Project Supervisor : Dr <NAME></h3>
                <p>Data entered into this site is purely for academical purposes and is never used within a medical environment.</p>
                <p>This website has been setup as a submission for the Developer's fourth year Honours Project.</p>


        </div>
        <hr>

        <div id = "boxes" class="center">  
            <h2>This project uses a blend of:</h2>
            <div id = "leftbox"> 
                <h3>Website Applications</h3> 
                    <img src="https://bbvaopen4u.com/sites/default/files/styles/big-image/public/img/new/bbva-open-web-apps-progressive.jpg" alt="Italian Trulli"> 
                        <p>Hominem eos hac religio tentabo ginabor. Laxissimas objectivam eo percipitur distinctum ii industriam. Mei scopo ideis horum vel factu rei. Initio ad vereor posita possum si possim eo bitavi. Re novi vero mens in me ipse. Ad nolo ac unam dico in me. Is odoratu fallant vi vestiri percipi ex et. Confirmari respondebo videbuntur voluntates dum per intelligat. Admonitus dubitavit sui consistat uti inspiciam persuadet perfectum. </p>
            </div>  
              
            <div id = "middlebox"> 
                <h3>IoT Devices</h3> 
                    <img src="https://images.idgesg.net/images/article/2019/01/industrial-iot-sensor-battery-100784076-large.jpg" alt="Italian Trulli"> 
                        <p>Pertinent lus infigatur una mox geometria distinguo. Apparet me nostris eo de probari. Manet omnis solis ea eo ipsis. Manibus si to dispari accepit me colligi. Debiliora potentiam una vis has componant terminari non. Perceptio habeantur sum naturalis hae objective eae ens. Cui permittere extensarum industriam iis excoluisse advertebam labefactat. Agi sed uno ponderibus materialis percurrere desiderant argumentis quapropter via. </p>
            </div> 
              
            <div id = "rightbox"> 
                <h3>Android Applications</h3> 
                    <img src="https://cdn.vox-cdn.com/thumbor/ZTg0bT74DkPQhtZeCsO_MfQD4Sg=/0x0:2040x1360/1200x800/filters:focal(857x517:1183x843)/cdn.vox-cdn.com/uploads/chorus_image/image/59347755/DSCF3188.0.jpg" alt="Italian Trulli"> 
                        <p>Potentiale manifestam procederet id si. Tria bere post addi tur est uti. Co esto gnum re modo more loco. Theologiae ea se an durationis describere substantia si. Mea ibi halitus reliqua hic adeoque. Deficere existimo ab assignem ad continet creditum. Has enim hic sua odor novi amen fuse lor meae. </p>
            </div> 
        </div> 
        <hr>


        <?php include("templates/footer.php"); ?> <!--Include the footer template  -->
    </body>
</html>


<style>  
    #leftbox { 
        float:left; 
        text-align:center; 
        width:33%; 
        height:280px; 
    } 
    #middlebox{ 
        float:left;  
        text-align:center; 
        width:33%; 
        height:280px; 

    } 
    #rightbox{ 
        float:right; 
        text-align:center; 
        width:33%; 
        height:280px; 

    } 
    #boxes{
        padding-bottom:400px;
    }

</style> <file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/Readings.php");


$check = null;

$email = $_POST["email"];
$count = $_POST["count"];
$weight = $_POST["weight"];
$temp = $_POST["temperature"];
$hr = $_POST["hr"];
$dys = $_POST["dys"];
$sys = $_POST["sys"];
$doctor = $_POST["doctor"]; //recieve data from mobile device

$check = recordReading($email, $doctor, $count, $weight, $temp, $hr, $dys, $sys); //record the result
echo $check;

?><file_sep>//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

package com.example.honoursproject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


public class TestResultsWorker extends AsyncTask<String,Void,String>{

    Context context;
    String Email;
    String type;
    String type2;


    List<String> Result;
    List<String> Time;
    List<String> HR ;
    List<String> Weight ;
    List<String> Temp ;
    List<String> Sys ;
    List<String> Dys; //setup global varibales


    TestResultsWorker(Context ctx){

        context = ctx;
    } //get the context from previous activity

    protected String doInBackground(String... params) {
        type = params[0];
        type2 = params[1];
        if (type.equals("getResults")){
            String urlAdvice = "https://mayar.abertay.ac.uk/~1600964/Honours-Project/Android/APIs/Controller/getResults.php"; //api location
            Email = params[2];
            try{
                URL url = new URL(urlAdvice);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod(("POST"));
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("email", "UTF-8")+"="+ URLEncoder.encode(Email, "UTF-8"); //encode the user's email

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result = "";
                String line="";
                while ((line = bufferedReader.readLine()) != null){ //retrieve the results
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) { //catch any errors
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onPostExecute(String result) {
        JSONArray obj = null;
        if (type2.equals("getResults")) { 
            try
            {
                obj = new JSONArray(result); // make a JSONArray out of the json results retruned by the server

            }
            catch (JSONException e)
            {
                Log.d("failed","json parser failed");
            }
            Result = new ArrayList<String>(obj.length());
            HR = new ArrayList<String>(obj.length());
            Weight = new ArrayList<String>(obj.length());
            Temp = new ArrayList<String>(obj.length());
            Sys = new ArrayList<String>(obj.length());
            Dys = new ArrayList<String>(obj.length());
            Time = new ArrayList<String>(obj.length()); //set the lists to the size of the JSON string returned

            for (int i = 0; i < obj.length(); ++i) {
                try {
                    JSONObject o = obj.getJSONObject(i);

                    Result.add((String) (o.getString("result")));
                    HR.add((String) (o.getString("hr")));
                    Weight.add((String) (o.getString("weight")));
                    Temp.add((String) (o.getString("temp")));
                    Sys.add((String) (o.getString("sys")));
                    Dys.add((String) (o.getString("dys")));
                    Time.add((String) (o.getString("time"))); //add each value individually 
                }
                catch (JSONException e) {
                }

            }

            setupMultiGraphs(); //setup the graphs



        }

        if (type2.equals("retrieveResults")) { //for the handshake test on the main account activity (uses same functionality as previous)
            try
            {
                obj = new JSONArray(result);

            }
            catch (JSONException e)
            {
                Log.d("failed","json parser failed");
            }
            Result = new ArrayList<String>(obj.length());
            List<String> HR = new ArrayList<String>(obj.length());
            List<String> Weight = new ArrayList<String>(obj.length());
            List<String> Temp = new ArrayList<String>(obj.length());
            List<String> Sys = new ArrayList<String>(obj.length());
            List<String> Dys = new ArrayList<String>(obj.length());
            Time = new ArrayList<String>(obj.length());

            for (int i = 0; i < obj.length(); ++i) {
                try {
                    JSONObject o = obj.getJSONObject(i);

                    Result.add((String) (o.getString("result")));
                    HR.add((String) (o.getString("hr")));
                    Weight.add((String) (o.getString("weight")));
                    Temp.add((String) (o.getString("temp")));
                    Sys.add((String) (o.getString("sys")));
                    Dys.add((String) (o.getString("dys")));
                    Time.add((String) (o.getString("time")));
                }
                catch (JSONException e) {
                }

            }
            LineChart lineChart = ((Activity)context).findViewById(R.id.lineChart);
            setupGraphs(lineChart, Result, "Hand Shake Test");


        }
    }

    private void setupMultiGraphs(){

        LineChart HeartR = ((Activity)context).findViewById(R.id.HeartR);
        LineChart Hand = ((Activity)context).findViewById(R.id.Hand);
        LineChart Weights = ((Activity)context).findViewById(R.id.Weight);
        LineChart Temperature = ((Activity)context).findViewById(R.id.Temp);
        LineChart Systolic = ((Activity)context).findViewById(R.id.Sys);
        LineChart Dystolic = ((Activity)context).findViewById(R.id.Dys); //find the locations of each graph

        setupGraphs(HeartR, HR, "Heart Rate BPM");
        setupGraphs(Hand, Result, "Hand Shake Result");
        setupGraphs(Weights, Weight, "Weight Kg");
        setupGraphs(Temperature, Temp, "Temperature Degrees Celsius");
        setupGraphs(Systolic, Sys, "Systolic BP");
        setupGraphs(Dystolic, Dys, "Dystolic BP"); //enter all data into the graphs




    }

    private void setupGraphs(LineChart linechart, List<String> list, String type){

        ArrayList<String> xAXES = new ArrayList<>();
        ArrayList<Entry> yAXEScos = new ArrayList<>(); //x and y value data structures

        int numDataPoints = list.size(); //get the size of the data for the graphs

        for(int i=0;i<numDataPoints;i++){
            Float cosFunction = Float.parseFloat(list.get(i));

            yAXEScos.add(new Entry(cosFunction,i));

            xAXES.add(i, Time.get(i)); //add the values to the x and y axes from the lists
        }


        String[] xaxes = new String[xAXES.size()];

        for(int i=0; i<xAXES.size();i++){
            xaxes[i] = String.valueOf(xAXES.get(i));
        } //convert the xaxes to strings (needed for these type of graphs)


        ArrayList<ILineDataSet> lineDataSets = new ArrayList<>();

        LineDataSet lineDataSet1 = new LineDataSet(yAXEScos,type);
        lineDataSet1.setDrawCircles(false);
        lineDataSet1.setColor(Color.BLUE); //set colours (blue historic colour of the nhs)


        lineDataSets.add(lineDataSet1);


        linechart.setData(new LineData(xaxes, lineDataSets));

        linechart.setVisibleXRangeMaximum(65f); //set the visibility
    }


    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}


<file_sep><?php
//Project: Honours Project 2020
//Author: <NAME>
//Date: 10/04/2020
//Purpose: to show the benefits of collecting lots of data about a patient
//using different devices and tests

include("../Model/User.php");

function LoginMedical($email, $password){ //login functionality for medical professionals


    $check = LoginM($email, $password);

    if ($check != null){
        return $check;
    }
    else {
        return null;
    }
}


?>

