Skip to content

Instantly share code, notes, and snippets.

@daserge
Created November 13, 2014 11:51
Show Gist options
  • Select an option

  • Save daserge/a4ac1f2bd5dd58bb35f2 to your computer and use it in GitHub Desktop.

Select an option

Save daserge/a4ac1f2bd5dd58bb35f2 to your computer and use it in GitHub Desktop.
Cordova Windows plugin: Winmd + callback from JS
cordova.define("org.apache.cordova.battery-status.Battery", function (require, exports, module) { /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var NOOP_TIMEOUT = 10000;
var stopped;
function handleResponse(successCb, errorCb, jsonResponse) {
var info = JSON.parse(jsonResponse);
if (info.hasOwnProperty("exceptionMessage")) {
errorCb(info.exceptionMessage);
return;
}
successCb(info, { keepCallback: true });
}
var Battery = {
start: function (win, fail, args, env) {
stopped = false;
try {
if (WinJS.Utilities.isPhone === true) {
function noop() {
if (stopped) {
return;
}
setTimeout(noop, NOOP_TIMEOUT);
}
function batteryLevelChangeCallback(jsonResult) {
if (stopped) {
return;
}
handleResponse(win, fail, jsonResult);
}
// Issue: we never get into batteryLevelChangeCallback event
handleResponse(win, fail, BatteryStatus.BatteryStatus.start(batteryLevelChangeCallback));
// So that we don't leave this module (does this impact the behavior at all?)
noop();
} else {
fail("The operation is unsupported by this platform.");
}
} catch (e) {
fail(e);
}
},
stop: function () {
stopped = true;
BatteryStatus.BatteryStatus.stop();
}
};
require("cordova/exec/proxy").add("Battery", Battery);
});
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Windows.Phone.Devices.Power;
namespace BatteryStatus
{
public delegate void BatterStatusChangeCallback(string jsonResult);
public sealed class BatteryStatus
{
private static Battery battery = Battery.GetDefault();
private static BatterStatusChangeCallback _changeCallback;
public static string Start(BatterStatusChangeCallback callback)
{
var currentStatus = GetBatteryStatus();
Subscribe(callback);
return currentStatus;
}
public static void Stop()
{
Unsubscribe();
}
private static void Subscribe(BatterStatusChangeCallback callback)
{
_changeCallback = callback;
battery.RemainingChargePercentChanged += BatteryOnRemainingChargePercentChanged;
}
private static void Unsubscribe()
{
battery.RemainingChargePercentChanged -= BatteryOnRemainingChargePercentChanged;
_changeCallback = null;
}
private static void BatteryOnRemainingChargePercentChanged(object sender, object o)
{
if (_changeCallback != null)
_changeCallback(GetBatteryStatus());
}
public static string GetBatteryStatus()
{
try
{
return Serialize(typeof(BatteryInfo), new BatteryInfo
{
Level = battery.RemainingChargePercent
});
}
catch (Exception ex)
{
return Serialize(typeof(ExceptionInfo), new ExceptionInfo { Message = ex.Message });
}
}
private static string Serialize(Type type, object obj)
{
using (var stream = new MemoryStream())
{
var jsonSer = new DataContractJsonSerializer(type);
jsonSer.WriteObject(stream, obj);
stream.Position = 0;
return new StreamReader(stream).ReadToEnd();
}
}
[DataContract]
private class BatteryInfo
{
[DataMember(Name = "level")]
public int Level;
// Not supported by native API
[DataMember(Name = "isPlugged")]
public string IsPlugged;
};
[DataContract]
private class ExceptionInfo
{
[DataMember(Name = "exceptionMessage")]
public string Message = string.Empty;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment