Code Monkey home page Code Monkey logo

hcgateway's Introduction

HCGateway

HCGateway is a platform to let developers connect to the Health Connect API on Android via a REST API. You can view the documentation for the REST API here

The platform consists of two parts:

  • A REST API/server
  • A mobile application that pings the server periodically

How it Works

  • The mobile application pings the server every 2 hours to send data. The following data types are supported-
    • Active Calories Burned (activeCaloriesBurned)
    • Basal Body Temperature (basalBodyTemperature)
    • Basal Metabolic Rate (basalMetabolicRate)
    • Blood Glucose (bloodGlucose)
    • Blood Pressure (bloodPressure)
    • Body Fat (bodyFat)
    • Body Temperature (bodyTemperature)
    • Bone Mass (boneMass)
    • Cervical Mucus (cervicalMucus)
    • Distance (distance)
    • Exercise (exerciseSession)
    • Elevation Gained (elevationGained)
    • Floors Climbed (floorsClimbed)
    • Heart Rate (heartRate)
    • Height (height)
    • Hydration (hydration)
    • Lean Body Mass (leanBodyMass)
    • Menstruation Flow (menstruationFlow)
    • Menstruation Period (menstruationPeriod)
    • Nutrition (nutrition)
    • Ovulation Test (ovulationTest)
    • Oxygen Saturation (oxygenSaturation)
    • Power (power)
    • Respiratory Rate (respiratoryRate)
    • Resting Heart Rate (restingHeartRate)
    • Sleep (sleepSession)
    • Speed (speed)
    • Steps (steps)
    • StepsCadence (stepsCadence)
    • Total Calories Burned (totalCaloriesBurned)
    • VO2 Max (vo2Max)
    • Weight (weight)
    • Wheelchair Pushes (wheelchairPushes)

Support for more types is planned for the future.

  • Each sync takes approximatly 15 minutes
  • The server encrypts the data using Fernet encryption, then stores it in a database hosted on a custom instance of Appwrite.
  • The server exposes an API to let developers login and get the data for their users.

The platform is currently a one way sync. Any changes made to health connect data by other apps will not be synced. The ability to add/edit/delete data through the api is planned for the future.

Get Started

  • There is a live instance hosted at https://api.hcgateway.shuchir.dev/ that you can use. You can also host your own instance. To learn more on Self Hosting, skip down to the Self Hosting section.
  • You can install the mobile application through the APK file. You can find the latest APK file in the releases section of this repository, or by downloading the app-release.apk file from the root of this repository.
  • The minimum requirement for the APK file is Android Oreo (8.0)
  • Once you install the Android APK file, signup by entering a username and password
  • Once you see a screen showing your user id, you have successfully signed up. Your data will sync in 2 hours. This is customizable. You also have the option to force a sync any time through the application.

Database

Users Structure

users {
    name: string
    password: string
}

Parameters

  • name - The username of the user
  • password - The password of the user encrypted using Argon 2 format. The password is never stored as is, and cannot be retrieved through any API.

Database Structure

user_id: string {
    type: string {
        $id: string
        $createdAt: datetime
        $updatedAt: datetime
        $permissions: object
        $databaseId: string
        $collectionId: string
        data: string
        id: string
        start: datetime
        end: datetime
        app: string
    }
}

Parameters

  • $id - The ID of the object
  • $createdAt - The date and time the object was added to the database
  • $updatedAt - The date and time the object was last updated
  • $permissions - The permissions of the object- will always be []
  • $databaseId - The ID of the database
  • $collectionId - The ID of the collection
  • data - The data of the object encrypted using Fernet. When asked for through the API, the data will be decrypted for you using the user's password found from the user id.
  • id - The ID of the object- This is the same a $id.
  • start - The start date and time of the object
  • end - The end date and time of the object. Might not be present for some objects.
  • app - The app that the object was synced from.

REST API

This documentation is also available at https://hcgateway.shuchir.dev/

The REST API is a simple Flask application that exposes the following endpoints:

  • /api/login - Login a user and get the session ID.

    • Method: POST
    • Body Parameters:
      • username - The username of the user
      • password - The password of the user
    • Response:
      • sessid - The user ID of the user
  • /api/sync/<method> - Dump data into the database. This method is exclusive to the application, and should not be used otherwise.

    • Method: POST
    • Body Parameters:
      • user - The user ID of the user
      • data - The data to be dumped.
  • /api/fetch/<method> - Get data from the database.

    • Method: POST
    • URL Parameters:
      • method - The method to use. The methods are listed above, next to each supported data type under the How It Works section. For example, to get all blood glucose data, you would use /api/fetch/bloodGlucose.
    • Body Parameters:
      • userid - The user ID of the user
      • queries - This is an optional parameter. You can filter your response if you'd like. The format is an array of strings, where each string is a query. The following are examples of queries-
        • limit(num) - Limit the number of results to num, where num is an integer. num must be less than or equal to 100, otherwise all results will be returned.
        • equal("parameter", ["value"]) - parameter is the name of a parameter; all parameters are listed above, inside of the type structure. value is an array of values to filter by. For example, equal("id2", ["id1", "id2"]) will return all objects that have an id of id1 or id2.
        • notEqual("parameter", ["value"]) - value is an array of values to filter by. For example, notEqual("id2", ["id1", "id2"]) will return all objects that do not have an id of id1 or id2.
        • lessThan("parameter", ["value(s)"]) - value is the value to filter by. For example, lessThan("id", "id1") will return all objects that have an id less than id1.
        • greaterThan("parameter", ["value(s)"]) - value is the value to filter by. For example, greaterThan("id", "id1") will return all objects that have an id greater than id1.
        • lessThanEqual("parameter", ["value(s)"]) - value is the value to filter by. For example, lessThanEqual("id", "id1") will return all objects that have an id less than or equal to id1.
        • greaterThanEqual("parameter", ["value(s)"]) - value is the value to filter by. For example, greaterThanEqual("id", "id1") will return all objects that have an id greater than or equal to id1.
        • search("parameter", ["value"]) - value is the value to search for. For example, search("id", "id1") will return all objects that have an id that contains id1.
        • orderDesc("parameter") - This will order the results in descending order by the parameter. For example, orderDesc("id") will return all objects ordered by id in descending order.
        • orderAsc("parameter") - This will order the results in ascending order by the parameter. For example, orderAsc("id") will return all objects ordered by id in ascending order.
    • Response:
      • data - The data retrieved from the database

Mobile Application

The mobile application is a simple Android application that pings the server every 2 hours to send data. It starts a foreground service to do this, and the service will run even if the application is closed. The application is written in React Native.

Self Hosting

You can self host the server and database. To do this, follow the steps below:

  • You need Python 3 and NodeJS 18+ installed on your machine
  • Install appwrite and make sure your instance is accessible from the machine running the HCGateway server. You can find more at https://appwrite.io/
  • Clone this repository
  • cd into the api/ folder
  • run pip install -r requirements.txt
  • rename .env.example to .env and fill in the values
  • run python3 main.py to start the server
  • in another window/tab, cd into the app/ folder
  • run npm install
  • run npx patch-package to apply a patch to the foreground service library
  • run npm run android to start the application, or follow the instructions at https://medium.com/geekculture/react-native-generate-apk-debug-and-release-apk-4e9981a2ea51 to build an APK file.
    • It is also possible to now use eas build to build the APK file. You can find more at https://docs.expo.dev/build/eas-build/ NOTE: This must be a local build, since you need to run patch-package before building the APK file.

hcgateway's People

Contributors

coolcodersj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

hcgateway's Issues

Missing data

Great project first of all, wanted some kind of API so I could easily extract exercise data to analyse in python. I am able to extract all exercise data and they do indeed display times at which I performed exercises, but the exact details of the exercises are missing. Take swimming exercise for example (74 is the number for swimming), it does not display the statistics of each lap swum such as the time it took, amount of strokes etc.

I might think this error may be beyond your project as this data can also not be seen in HealthConnect (since your app retrieves data from it, it probably won't be able to display data which is not given by HC).

Example return exerciseSession object:
{
"$collectionId": "exerciseSession",
"$createdAt": "2023-11-08T11:06:19.659+00:00",
"$databaseId": "XXXXX",
"$id": "255a6937-79df-45c3-906d-3a9562536558",
"$permissions": [],
"$updatedAt": "2023-11-14T21:20:29.180+00:00",
"app": "com.sec.android.app.shealth",
"data": {
"exerciseRoute": {},
"exerciseType": 74,
"laps": [],
"notes": null,
"segments": [],
"title": null
}

Docker and Unraid support

Hello! I am interested in self-hosting and using ur solution but I prefer using the docker. I am not very skilled yet, so I want to try making a dockerfile for this project and that might be my first good issue :D

What do you think?

API returns 404 on use

Hello, for some reason logging in returns 404 and I think I made an account, but im not sure because the app just showed a blank dialog with a dismiss button. Im not sure if it was successful or not because of this, I also noticed just simply typing your api url into a web browser shows "further configuration is required"
Screenshot 2024-03-04 at 11 01 47 PM
Here is what I got while testing with curl:
Screenshot 2024-03-04 at 11 02 58 PM

Is there any solution or is this a bug?

I am having an issue with build and running the apk

I tried many times and it gives the same error

> [email protected] android
> react-native run-android

info Starting JS server...
info Installing the app...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings generic class cache for settings file 'D:\HCGateway\app\android\settings.gradle' (C:\Users\shree\.gradle\caches\7.5.1\scripts\51n967gkkf0rk9vrfb37h9dep).
> BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 65

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings generic class cache for settings file 'D:\HCGateway\app\android\settings.gradle' (C:\Users\shree\.gradle\caches\7.5.1\scripts\51n967gkkf0rk9vrfb37h9dep).
> BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 65

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 3s

    at makeError (D:\HCGateway\app\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at D:\HCGateway\app\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async runOnAllDevices (D:\HCGateway\app\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (D:\HCGateway\app\node_modules\@react-native-community\cli\build\index.js:142:9)
info Run CLI with --verbose flag for more details.

Not requesting permissions for READ to Health Connect properly

Seems like at some point the app stopped syncing to the server. Investigated the app in debug mode, it seems like it doesn't have adequate permissions but isn't trying to request them either. Creating issue to come back to later and for tracking.

Would love to help you

Hi Shuchir, I was looking for something like this and found that you're working on this. I'd love to help you out in any way possible. I have limited experience with android/mobile dev but have good experience with the backend.

Let me know if we can collaborate in any way :)

Feature Request: Set api server url on login page

Thank you for this project. I've been trying to find a easy way to get access to my health connect data and your project seems like the only viable option until Google implements a API of their own.

An idea that might help beginners, it would be useful if the default apk had a field on the login page to specify the url to the API server.

It would allow users to avoid rebuilding the apk to use self hosted servers.

Can't Create Login

I've downloaded the app and installed it however. When putting in a username and password it just shows a dialogue with just a 'DISMISS' button. Any advice as to how to proceed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.