Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

openScale cordova plugin #119

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions android_plugins/openscale/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "openscale",
"version": "1.0.0",
"description": "openScale cordova plugin",
"cordova": {
"id": "openscale",
"platforms": [
"android"
]
},
"keywords": [
"ecosystem:cordova",
"cordova-android"
],
"author": "olie.xdev",
"license": "GPL-3.0"
}
16 changes: 16 additions & 0 deletions android_plugins/openscale/plugin.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version='1.0' encoding='utf-8'?>
<plugin id="openscale" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>openscale</name>
<js-module name="openscale" src="www/openscale.js">
<clobbers target="cordova.plugins.openscale" />
</js-module>
<platform name="android">
<config-file parent="/*" target="res/xml/config.xml">
<feature name="openscale"><param name="android-package" value="openscale.openscale" /></feature>
</config-file>
<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="com.health.openscale.READ_WRITE_DATA" />
</config-file>
<source-file src="src/android/openscale.java" target-dir="src/openscale/openscale" />
</platform>
</plugin>
196 changes: 196 additions & 0 deletions android_plugins/openscale/src/android/openscale.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/* Copyright (C) 2018 olie.xdev <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package openscale;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;

import org.apache.cordova.BuildConfig;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

public class openscale extends CordovaPlugin {
private final int REQUEST_CODE = 1;

private final String APP_ID = "com.health.openscale";
private final String AUTHORITY = APP_ID + ".provider";
private final String REQUIRED_PERMISSION = APP_ID + ".READ_WRITE_DATA";

private final Uri metaUri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(AUTHORITY)
.path("meta")
.build();

private final Uri usersUri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(AUTHORITY)
.path("users")
.build();

private final Uri measurementsUri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(AUTHORITY)
.path("measurements")
.build();

private CallbackContext requestCallbackContext;

@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}

@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
if (requestCode == REQUEST_CODE) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
requestCallbackContext.error("openScale permission denied");
}
else {
requestCallbackContext.success("openScale permission granted");
}
}
}

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

if (action.equals("requestPermission")) {
requestCallbackContext = callbackContext;

if (cordova.hasPermission(REQUIRED_PERMISSION)) {
callbackContext.success("openScale permission granted");
} else {
cordova.requestPermission(this, REQUEST_CODE, REQUIRED_PERMISSION);
}
}

if (cordova.hasPermission(REQUIRED_PERMISSION)) {
if (action.equals("exportWaistlineData")) {
long timestamp = args.getLong(0);
float calories = (float) args.getDouble(1);

cordova.getThreadPool().execute(new Runnable() {
public void run() {
updateOpenScaleData(timestamp, calories, callbackContext);
}
});
}

if (action.equals("importOpenScaleData")) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
importOpenScaleData(callbackContext);
}
});
}
} else {
callbackContext.error("openScale permission denied, please request first the openScale permission");
return false;
}

return true;
}

private void updateOpenScaleData(long datetime, float calories, CallbackContext callbackContext) {
Date date = new Date(datetime);
ContentValues updateValues = new ContentValues();

updateValues.put("datetime", datetime);
updateValues.put("calories", calories);

int updateCount = cordova.getContext().getContentResolver().update(measurementsUri, updateValues, null, null);

if (updateCount == 0) {
callbackContext.error("couldn't update openScale measurement; no measurement with timestamp " + datetime + " found");
} else {
callbackContext.success("update waistline measurement to openScale with datetime: " + date + " calories: " + calories);
}
}

private void importOpenScaleData(CallbackContext callbackContext) {
try {
Cursor cursor = cordova.getContext().getContentResolver().query(
metaUri, null, null, null, null);

try {
while (cursor.moveToNext()) {
int apiVersion = cursor.getInt(cursor.getColumnIndex("apiVersion"));
int versionCode = cursor.getInt(cursor.getColumnIndex("versionCode"));

System.out.println("openScale version " + versionCode + " with content provider API version " + apiVersion);
}
} finally {
cursor.close();
}

cursor = cordova.getContext().getContentResolver().query(
usersUri, null, null, null, null);

try {
while (cursor.moveToNext()) {
long userId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
Cursor m = cordova.getContext().getContentResolver().query(
ContentUris.withAppendedId(measurementsUri, userId),
null, null, null, null);

JSONArray values = new JSONArray();

try {
while (m.moveToNext()) {
long datetime = m.getLong(m.getColumnIndex("datetime"));
float weight = m.getFloat(m.getColumnIndex("weight"));

JSONObject object = new JSONObject();
object.put("timestamp", datetime);
object.put("weight", weight);

values.put(object);

System.out.println("imported openScale measurement datetime " + datetime + " weight " + weight);
}
} finally {
callbackContext.success(values);
m.close();
}
}
} finally {
cursor.close();
}
}
catch (Exception e) {
callbackContext.error("openScale content provider error: " + e.getMessage());
}
}
}


13 changes: 13 additions & 0 deletions android_plugins/openscale/www/openscale.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var exec = require('cordova/exec');

exports.requestOpenScalePermission = function (success, error) {
exec(success, error, 'openscale', 'requestPermission', []);
};

exports.exportWaistlineData = function (arg0, success, error) {
exec(success, error, 'openscale', 'exportWaistlineData', [arg0]);
};

exports.importOpenScaleData = function (success, error) {
exec(success, error, 'openscale', 'importOpenScaleData', []);
};
1 change: 1 addition & 0 deletions config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<plugin name="cordova-plugin-splashscreen" spec="^5.0.2" />
<preference name="SplashScreenDelay" value="0" />
<preference name="FadeSplashScreenDuration" value="0" />
<plugin name="openscale" spec="android_plugins/openscale" />
<engine name="android" spec="^7.1.2" />
<engine name="browser" spec="^5.0.4" />
</widget>
54 changes: 54 additions & 0 deletions www/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,67 @@ var app = {
},
};

window.requestOpenScalePermission = function(callback) {
cordova.exec(callback, function(errMsg) {
console.log(errMsg);
}, "openscale", "requestPermission", []);
};

window.exportDataToOpenScale = function(timestamp, calories, callback) {
cordova.exec(callback, function(errMsg) {
console.log('error exporting waistline data to openScale (' + errMsg +')');
}, "openscale", "exportWaistlineData", [timestamp, calories]);
};

window.importOpenScaleData = function(callback) {
cordova.exec(callback, function(errMsg) {
console.log('error importing openScale data to waistline (' + errMsg +')');
}, "openscale", "importOpenScaleData", []);
};

ons.ready(function() {
console.log("Cordova Ready");
navigator.camera.cleanup(function(){console.log("Camera cleanup success")}); //Remove any old camera cache files
app.initialize()
.then(function(){
console.log("App Initialized");

console.log("openScale Initializing");

window.requestOpenScalePermission(function(msg) {
console.log(msg);
});

window.importOpenScaleData(function(values) {
for (var i =0; i<values.length; i++) {
console.log("imported openScale data timestamp: " + values[i].timestamp + " weight: " + values[i].weight);
}
});

dbHandler.getObjectStore("log").openCursor().onsuccess = function(e)
{
var cursor = e.target.result;

if (cursor)
{
if (cursor.value.nutrition != undefined && cursor.value.nutrition.calories != undefined)
{
var date = cursor.value.dateTime;
date.setUTCHours(0); //Get date, ignoring time

if (date != undefined) {
//console.log(date + " weight " + cursor.value.weight + " callo " + cursor.value.nutrition.calories);

window.exportDataToOpenScale(date.getTime(), cursor.value.nutrition.calories, function(echoValue) {
console.log(echoValue);
});
}
}

cursor.continue();
}
};

if (app.storage.getItem("disable-animation") == "true") ons.disableAnimations(); //Disable all animations if setting enabled
var homescreen = app.storage.getItem("homescreen");
nav.resetToPage("activities/"+homescreen+"/views/"+homescreen+".html");
Expand Down