Bluetooth LE Suported app in PhoneGap/Cordova - android

I am using "randdusing/cordova-plugin-bluetoothle" plugin in PhoneGap/Cordova App to create a Bluetooth application. I am using a simple example which is given on GitHub page of the plugin. but I am not getting any device listed but getting a message Scanning for devices (will continue to scan until you select a device)...
Below is the Code I am using
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
bluetoothle.initialize({
request: true,
statusReceiver: false
}, initializeSuccess, handleError);
}
function initializeSuccess(result) {
if (result.status === "enabled") {
log("Bluetooth is enabled.");
log(result);
} else {
document.getElementById("start-scan").disabled = true;
log("Bluetooth is not enabled:", "status");
log(result, "status");
}
}
function handleError(error) {
var msg;
if (error.error && error.message) {
var errorItems = [];
if (error.service) {
errorItems.push("service: " + (uuids[error.service] || error.service));
}
if (error.characteristic) {
errorItems.push("characteristic: " + (uuids[error.characteristic] || error.characteristic));
}
msg = "Error on " + error.error + ": " + error.message + (errorItems.length && (" (" + errorItems.join(", ") + ")"));
} else {
msg = error;
}
log(msg, "error");
if (error.error === "read" && error.service && error.characteristic) {
reportValue(error.service, error.characteristic, "Error: " + error.message);
}
}
var foundDevices = [];
function startScan() {
log("Starting scan for devices...", "status");
document.getElementById("devices").innerHTML = "";
document.getElementById("services").innerHTML = "";
document.getElementById("output").innerHTML = "";
if (window.cordova.platformId === "windows") {
bluetoothle.retrieveConnected(retrieveConnectedSuccess, handleError, {});
} else {
bluetoothle.startScan(startScanSuccess, handleError, {
services: []
});
}
}
function startScanSuccess(result) {
log("startScanSuccess(" + result.status + ")");
if (result.status === "scanStarted") {
log("Scanning for devices (will continue to scan until you select a device)...", "status");
} else if (result.status === "scanResult") {
if (!foundDevices.some(function (device) {
return device.address === result.address;
})) {
log('FOUND DEVICE:');
log(result);
foundDevices.push(result);
addDevice(result.name, result.address);
}
}
}
function retrieveConnectedSuccess(result) {
log("retrieveConnectedSuccess()");
log(result);
result.forEach(function (device) {
addDevice(device.name, device.address);
});
}
function addDevice(name, address) {
var button = document.createElement("button");
button.style.width = "100%";
button.style.padding = "10px";
button.style.fontSize = "16px";
button.textContent = name + ": " + address;
button.addEventListener("click", function () {
document.getElementById("services").innerHTML = "";
connect(address);
});
document.getElementById("devices").appendChild(button);
}
function log(msg, level) {
level = level || "log";
if (typeof msg === "object") {
msg = JSON.stringify(msg, null, " ");
}
console.log(msg);
if (level === "status" || level === "error") {
var msgDiv = document.createElement("div");
msgDiv.textContent = msg;
if (level === "error") {
msgDiv.style.color = "red";
}
msgDiv.style.padding = "5px 0";
msgDiv.style.borderBottom = "rgb(192,192,192) solid 1px";
document.getElementById("output").appendChild(msgDiv);
}
}
This is my first Bluetooth LE Project in Cordova. Please help me and suggest any other plugin better than this with good documentation.
Thanks.

If you are testing your app on Android 6+ you need to request permission first in order to use the Bluetooth functionality of the device. Otherwise your app will silently fail and you won't see any devices discovered. You can use the built-in method of the Bluetooth LE plugin for this
bluetoothle.requestPermission().then(success, fail)
Or you can add cordova-plugin-android-permissions, should you need to request other permissions as well.

Related

getToken() -> BAD_AUTHENTICATION. Account

Hi in the below code getting an issues Bad Authentication. trying to configuring device but not getting any response.and loader also just dismiss.
Am try to configuring a device using Bluetooth but save data into locally not getting any response .
08-23 11:58:33.185 2112-2459/? E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:743227095>, App: com.android.vending, Service: androidmarket
gai: Long live credential not available.
at gaj.b(:com.google.android.gms#12685008#12.6.85 (020306-197041431):20)
at gaj.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):50)
at fyt.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):38)
at hpk.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):8)
at hpk.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):189)
at hok.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):2)
at hoh.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):17)
at hoh.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at cyz.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):25)
at cyz.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):82)
at fvp.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at fvo.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):2)
at fvo.e(:com.google.android.gms#12685008#12.6.85 (020306-197041431):6)
at fvn.a(:com.google.android.gms#12685008#12.6.85 (020306-197041431):1)
at fxk.getAuthToken(:com.google.android.gms#12685008#12.6.85 (020306-197041431):7)
at android.accounts.AbstractAccountAuthenticator$Transport.getAuthToken(AbstractAccountAuthenticator.java:196)
at android.accounts.IAccountAuthenticator$Stub.onTransact(IAccountAuthenticator.java:113)
at android.os.Binder.transact(Binder.java:380)
at dbf.onTransact(:com.google.android.gms#12685008#12.6.85 (020306-197041431):3)
at android.os.Binder.execTransact(Binder.java:446)
can any one please help me
#OnClick(R.id.saveConfig)
public void onClick() {
sendCommandToBleService();
}
private void sendCommandToBleService() {
String pollNumber = mPollNumber.getText().toString();
String geoLocation = mGeoLocation.getText().toString();
String luminairePower = mLuminourPower.getText().toString();
String projectName = mProjectName.getText().toString();
String battAh = mBatteryAh.getText().toString();
String pannelWatt = mPannelWatt.getText().toString();
if (TextUtils.isEmpty(pollNumber)) {
Toast.makeText(LightConfigurationActivity.this, R.string.poll_number_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(geoLocation) || geoLocation.equalsIgnoreCase("SET")) {
Toast.makeText(LightConfigurationActivity.this, R.string.geoLocation_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(luminairePower) || luminairePower.equalsIgnoreCase("SET")) {
Toast.makeText(LightConfigurationActivity.this, R.string.luminour_power_empty, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(projectName)) {
Toast.makeText(LightConfigurationActivity.this, R.string.project_name_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(battAh)) {
Toast.makeText(LightConfigurationActivity.this, R.string.battery_ah_blank, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(pannelWatt)) {
Toast.makeText(LightConfigurationActivity.this, R.string.pannel_watt_blank, Toast.LENGTH_SHORT).show();
return;
}
makeDefaultValues(pollNumber, geoLocation, luminairePower, projectName, battAh, pannelWatt);
if (battAh.length() == 1) {
battAh = "00" + battAh;
} else if (battAh.length() == 2) {
battAh = "0" + battAh;
}
if (pannelWatt.length() == 1) {
pannelWatt = "00" + pannelWatt;
} else if (pannelWatt.length() == 2) {
pannelWatt = "0" + pannelWatt;
}
sendCommandsToBleService(battAh, pannelWatt);
}
private void resendconfig() {
sendCommandToBleService();
}
private void sendCommandsToBleService(String batAhValue, String pannellwattValue) {
showProgressDialog();
String command = mSolarController.generatePacket("pol " + mPollNumber.getText().toString(), "00");
String longCmd = mPref.getString(Constants.LAT_COMMAND, "");
String latCmd = mPref.getString(Constants.LONG_COMMAND, "");
String firstTimerCmd = mPref.getString(Constants.TIMER_ONE_CMD, "");
String secondTimerCmd = mPref.getString(Constants.TIMER_TWO_CMD, "");
String projectCmd = mSolarController.generatePacket("pro " + mProjectName.getText().toString(), "00");
String batAh = mSolarController.generatePacket("battah " + batAhValue, "00");
String pannelWatt = mSolarController.generatePacket("panelw " + pannellwattValue, "00");
String wattCommand = mPref.getString(Constants.BRIGHTNESS_CMD, "");
String luminaryWatt = mPref.getString(Constants.LUMINOURE_WATT_COMMAND, "");
mBleService.addCommandToQue(command);
mBleService.addCommandToQue(longCmd);
mBleService.addCommandToQue(latCmd);
mBleService.addCommandToQue(firstTimerCmd);
mBleService.addCommandToQue(secondTimerCmd);
mBleService.addCommandToQue(projectCmd);
mBleService.addCommandToQue(batAh);
mBleService.addCommandToQue(pannelWatt);
mBleService.addCommandToQue(wattCommand);
mBleService.addCommandToQue(luminaryWatt);
mBleService.sendCommandToBle();
}

ionic framework + cordova. WebSocket is not working in the android release version, but the debug version works correctly

With this logs:
WebSocket connection to 'wss://xxxxxx.net/' failed: WebSocket opening handshake was canceled"
"TransportWebSocket.errorHandler - Error {}"
"TransportWebSocket.closeHandler - Error {"code":1006,"text":""}"
Please help with this problem.
sp.external.TransportWebSocket = function () {
var self = this;
var socket = null;
var isOpen = false;
var listSendMsg = [];
this.openHandler = null;
this.closeHandler = null;
this.messageHandler = null;
this.errorHandler = null;
this.serverURL = '';
this.send = function (_data, _highPrioritetFlag) {
utils.logger.debug('TransportWebSocket', 'send', 'Open status:' + isOpen);
_highPrioritetFlag = _highPrioritetFlag || false;
if (isOpen) {
if (_data && typeof _data === 'object') {
try {
socket.send(JSON.stringify(_data));
}
catch (error) {
throw new Error('Invalid JSON stringify');
}
}
else {
throw new Error('The data sent must be an object');
}
}
else {
if (_highPrioritetFlag) {
listSendMsg.unshift(_data);
}
else {
listSendMsg.push(_data);
}
openSocket();
}
};
this.reopen = function () {
utils.logger.debug('TransportWebSocket', 'reopen');
openSocket();
};
this.close = function (_code) {
utils.logger.debug('TransportWebSocket', 'close');
socket.close(_code);
};
function procListMsg() {
utils.logger.debug('TransportWebSocket', 'procListMsg', 'Processing buffer messages, items:' + listSendMsg.length);
if (listSendMsg.length > 0) {
self.send(listSendMsg.shift());
setTimeout(procListMsg, 20);
}
}
function openHandler() {
utils.logger.debug('TransportWebSocket', 'openHandler', 'WebSocket.readyState:' + socket.readyState);
if (socket.readyState === WebSocket.OPEN) {
isOpen = true;
procListMsg();
if (self.openHandler) {
self.openHandler();
}
}
}
function closeHandler(error) {
utils.logger.debug('TransportWebSocket', 'closeHandler', 'Error', {code: error.code, text: error.reason});
isOpen = false;
if (socket.readyState === WebSocket.CLOSED) {
if (self.closeHandler) {
self.closeHandler(error);
}
}
}
function errorHandler(error) {
utils.logger.debug('TransportWebSocket', 'errorHandler', 'Error', {code: error.code, text: error.reason});
isOpen = false;
if (self.errorHandler) {
self.errorHandler(error);
}
}
function messageHandler(e) {
var msg = null;
if (self.messageHandler) {
try {
msg = JSON.parse(e.data);
}
catch (error) {
throw new Error('Invalid JSON format in response: ' + e.data);
}
self.messageHandler(msg);
}
}
function openSocket() {
utils.logger.debug('TransportWebSocket', 'openSocket', 'Opening');
socket = new WebSocket(self.serverURL);
socket.onopen = openHandler;
socket.onclose = closeHandler;
socket.onmessage = messageHandler;
socket.onerror = errorHandler;
}
};
I don't know if you have solved this issue, but for people encountering the same trouble and who find this thread, you may check this cordova "release" behaves differently to "debug" regarding SSL
In short, modify the file that is making the behavior different between debug and release:
platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java
Comment out the content of the method onReceivedSslError and replace it with
handler.proceed();
return;

Node.js- Comapring items from AWS DynamoDB- only lowercases

I want to get Items from my AWS DynamoDB, via Lambda, which satisfy condition:
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = "contains (#nm, :keyWord)";
}
I send string (keyWord) from my android app, then call toLowerCase function on it and compare it with #nm from DB. My question is, how can I call similar function (toLowerCase) on #nm before comparing them? My whole code:
var AWS = require('aws-sdk');
var db = new AWS.DynamoDB();
exports.handler = function(event, context) {
var params = {
TableName: "Events", //"StreamsLambdaTable",
// ProjectionExpression: "locationLat, locationLon",
ProjectionExpression: "ID, description, endDate, imagePath, locationLat, locationLon, #nm, #tp" //specifies the attributes you want in the scan result.
ExpressionAttributeNames: {
"#nm": "name",
"#tp": "type",
},
ExpressionAttributeValues: {
":lower_lon": {"N": event.low_lon},
":higher_lon": {"N": event.high_lon},
":lower_lat": {"N": event.low_lat},
":higher_lat": {"N": event.high_lat}
}
};
if (typeof event.keyWord != "undefined") {
var str = event.keyWord;
str = str.toLowerCase();
params.ExpressionAttributeValues[":keyWord"] = {"S": str};
params.FilterExpression = params.FilterExpression + " and contains (#nm, :keyWord)";
}
db.scan(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
}
else {
data.Items.forEach(function(record) {
console.log(
record.name.S + "");
});
context.succeed(data.Items); // data.Items
}
});
};

asp.net web forms gives error in mobile browsers

I have a asp.net web forms site which runs well in PC. However when I try to access it from mobile it gives an object reference error. The site is asp.net 4.5.1 and used normal asp.net server controls.
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginView lView = (LoginView)this.Master.FindControl("LoginView1");
lView.Visible = false;
if (Request.QueryString["exp"] != null)
{
string msg = "Session expired please login.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
ManchesterContext context = new ManchesterContext();
if (Membership.ValidateUser(txtUserId.Text, txtPassword.Text))
{
MembershipUser user = Membership.GetUser(txtUserId.Text);
aspnet_Users dbUser = context.aspnet_Users.Where(u => u.UserName.Equals(user.UserName)).FirstOrDefault();
if (dbUser.PassUpdated)//This means user has already changed default password. Perform login.
{
SetAuthenticationCookie(user);
aspnet_Users dbEntry = context.aspnet_Users.Where(u => u.UserName == user.UserName).FirstOrDefault();
SessionInfo.InitSession(dbEntry.UserId, dbEntry.UserName);
Session.Add("USR_KEY", dbEntry.UserId);
FormsAuthentication.RedirectFromLoginPage(user.UserName,false);
}
else //User has not updated default password.
{
Session.Add("TEMP_USR", txtUserId.Text);
Session.Add("TEMP_PASS", txtPassword.Text);
Response.Redirect("ChangePassword.aspx");
}
}
else
{
string msg = "Invalid User Id or Password.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
public void SetAuthenticationCookie(MembershipUser user)
{
Response.Cookies.Clear();
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
Expires = System.DateTime.Now.AddDays(-1),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
return;
}
}

Node Server with Android and Browser Client

EDIT:
I want to implement a quiz-application on Android and Browser via Web Interface.
I'm looking for a way to communicate between the server and the clients. I tried socket.io but couldn't get it working with android.
I'm using a node.js server hosted on nodester (nodester.com).
I tried some libs but couldn't get it working.
I'm now working with einaros/ws from https://github.com/einaros/ws
The server code is:
var clients = [],
numClients = 0;
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 20083});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log(wss.clients);
console.log('received: %s', message);
incomingMessage(message, ws)
});
/*
ws.on('eigenesEvent', function(message) {
console.log('eigenes Event ausgelöst: ' + message);
});
*/
});
function incomingMessage(msg, ws) {
//console.log(wss.clients);
var obj = JSON.parse(msg);
if(obj.type == "connect") {
for(var i=0;i<clients.length;i++) {
if(clients[i] == obj.id) {
ws.send(JSON.stringify({
to: obj.id,
message: "name vergeben"
}));
return;
}
}
clients[numClients] = obj.id;
numClients++;
for(var i=0;i<clients.length;i++) {
console.log("Client" + i + ": " + clients[i]);
}
ws.send(JSON.stringify({
to: "all",
message: obj.id + " connected"
}));
}
if(obj.type == "disconnect") {
for(var i=0;i<clients.length;i++) {
if(clients[i] == obj.id) {
clients.splice(i, 1);
numClients--;
for(var i=0;i<clients.length;i++) {
console.log("Client" + i + ": " + clients[i]);
}
}
}
ws.send(JSON.stringify({
to: "all",
message: obj.id + " disconnected"
}));
return;
}
if(obj.type == "answer") {
if("id" in obj) {
if(obj.answer == "a") {
ws.send(JSON.stringify({
to: obj.id,
message: "a is correct"
}));
} else {
ws.send(JSON.stringify({
to: obj.id,
message: "answer is incorrect"
}));
}
}
}
if(obj.type == "something") {
if("id" in obj) {
ws.send(JSON.stringify({
to: obj.id,
message: "received: " + obj.message
}));
}
}
}
From a HTML-Site i can connect to the server via:
connect = function() {
var host = "ws://einaros.nodester.com";
try{
socket = new WebSocket(host);
console.log('WebSocket - status ' + socket.readyState);
socket.onopen = function(msg) {
console.log("Welcome - status " + this.readyState);
socket.send(JSON.stringify({
id: model.getClientName(),
type: "connect"
}));
model.setConnectionStatus(true);
};
socket.onmessage = function(msg) {
console.log("onmessage - msg: " + msg.data);
checkMessage(msg.data);
};
socket.onclose = function(msg) {
console.log("Disconnected - status " + this.readyState);
model.setConnectionStatus(false);
};
}
catch(ex){
console.log(ex);
}
},
On the Android-Client side i'm using AutobahnAndroid from: http://autobahn.ws/android
The client code for android is:
package ps.mediengestaltung;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
public class MainActivity extends Activity {
public final WebSocketConnection mConnection = new WebSocketConnection();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String wsuri = "ws://einaros.nodester.com";
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d("TAG", "Status: Connected to " + wsuri);
mConnection.sendTextMessage("Hello Server!");
}
#Override
public void onTextMessage(String payload) {
Log.d("TAG", "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d("TAG", "Connection lost.");
}
});
} catch (WebSocketException e) {
Log.d("TAG", e.toString());
}
}
}
In LogCat i get:
08-01 08:48:13.017: D/TAG(704): Status: Connected to ws://einaros.nodester.com
08-01 08:48:13.167: D/TAG(704): Connection lost.
What am i doing wrong? Any hints?
The reason could be: Weberknecht only implements the (outdated) Hixie-76 version of WebSocket.
You might try AutobahnAndroid, which implements the final RFC6455 version of WebSocket.
Another things: the WebSocket server you are using is no longer maintained (as far as I know). It also only implements Hixie-76 - which is no longer supported by Chrome/Firefox.
Try one of these:
https://github.com/einaros/ws
https://github.com/Worlize/WebSocket-Node
Disclaimer: I am the author of Autobahn and work for Tavendo.
You are asking your phone to connect to the localhost. You aren't running node on the phone right? :)
URI url = new URI("ws://127.0.0.1:8080/test");
This should instead be pointing to your nodester address/port.

Categories

Resources