converting buffer message to readable utf8 using node - android

Question:
how can I make my sensor data come in as proper x,y,z coordinates or something more human readable??
Background:
I have packets of sensor data (eg. Gravity, Rotation etc..) coming from my android phone
Ok so I've a UDP server using nodeJS. It is open and listening for a message data.
server.js
var PORT = 33333;
var HOST = '0.0.0.0';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log(message);
});
server.bind(PORT, HOST);
This message is formatted as a buffer((?) what is it really called binary?).
This is what happens when i do console.log(message.toString("utf8"));

Related

Cordova ble.write i can't send data (Android)

I have an Android App build in Apache Cordova, it works with Bluetooth 4.0(BLE) the plugin GitHub repostory indicates this shape for send information to a ble device (in my case a HM10 module):
this function writes data to a characteristic.
ble.write(device_id, service_uuid, characteristic_uuid, data, success, failure);
Description
Function write writes data to a characteristic.
Parameters:
device_id: UUID or MAC address of the peripheral
service_uuid: UUID of the BLE service
characteristic_uuid: UUID of the BLE characteristic
data: binary data, use an ArrayBuffer
success: Success callback function that is invoked when the connection is successful. [optional]
failure: Error callback function, invoked when error occurs. [optional]
I have tried to send data for this way but failure function is called immediately
function startBed() {
var UiidS="FFE0"; //UUID SERVICE: AT+UUID? => 0xFFE0
var UiidC="FFE1"; //UUID CHARACTERISTICS AT+CHAR? => 0xFFE1
var data = new Uint8Array(1);
data[0] = 1;
setTimeout(ble.write(hMac,UiidS,UiidC,data.buffer,success,failure),2000);
function success() {
document.getElementById("btstate1").innerHTML = "Dato enviado!!!";
}
function failure() {
document.getElementById("btstate1").innerHTML = "Dato NO enviado!!!";
var time=2000;
navigator.vibrate(time);
}
}
if I take the text box value and send it directly, the HM10 receives an unrecognized characters like Ó.
var UiidS="FFE0";
var UiidC="FFE1";
var dato =document.getElementById("btstate6").value;
setTimeout(ble.write(hMac,UiidS,UiidC,dato,success,failure),2000);
In conclution
I don't know why the module not receive the data correctly or in other cases the data isn't send. Maybe is for something of UUID.
I'm still trying to solve my problem, I confirmed that the UUID is correct, but I have the doubt about whether I am sending the data well as ArrayBuffer
Using a different plugin (https://github.com/randdusing/cordova-plugin-bluetoothle)
I used the following
var encodedString = bluetoothle.bytesToEncodedString([145,0,14,0,255]);
bluetoothle.write(this.writeSuccess.bind(this), this.writeError.bind(this), {
"value": encodedString,
"service": this.serviceUuid,
"characteristic": this.serviceCharacteristic,
"type": "noResponse",
"address": this.currentConnectedDevice
});
Where
// From plugin source:
encodedStringToBytes: function(string) {
var data = atob(string);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < bytes.length; i++)
{
bytes[i] = data.charCodeAt(i);
}
return bytes;
},
bytesToEncodedString: function(bytes) {
return btoa(String.fromCharCode.apply(null, bytes));
},
I hope this helps

NodeJS HTTP POST receive an Image with Express

I am using Bluemix to develop a 'HTTP POST listener' with NodeJS. This server should be the link between an Android Application and a Watson Bluemix Service
This is my code
/*eslint-env node*/
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
/* 'BODY PARSER - NOT WORKING' */
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); //Assuming JSON ENCODED INPUT
app.use(express.bodyParser({uploadDir:'/images'}));
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
app.post('/handle',function(request,response){
var image64=request.body.encoded_String;
var imageName=request.body.image_name;
/*OK LOG THIS (Encoded Base64 image)*/
console.log("IMG RECEIVED: " + imageName); //OK
console.log("ENCODED: " + image64); // = undefined (chunk problems?)
response.writeHead(200, { "Content-Type": "text/plain" });
response.write('Hello World - Example...\n');
response.end();
});
});
How can I receive a base64 encoded image and save it to a folder?
Thanks for you help!
String with image received in base64 has usually it's format written at the beginning which has to be removed (or at least I used to remove it).
var base64Data = str.replace(/^data:image\/png;base64,/, ""); // str - string with image
Then you have to save it with fs:
fs.writeFile("../dir/to/save/image.png", base64Data, 'base64', function(err) {});
And that's basically all.

as3 air Upload issue with Android Upload file more than 400 KB

i am trying to upload a zip file using FTP, on Android when the file size less than 400 KB it is uploaded correctly, when it is more than 400 KB only 414 KB got uploaded and the result file is corrupted.
I tried same code from Windows and it is working with all sizes.
here is my code:
public function uploadZipFile() {
//Socket instance which will be used to connect to ftp server
s.addEventListener(IOErrorEvent.IO_ERROR,onIOERR);
s.addEventListener(ProgressEvent.SOCKET_DATA, onReturnData);
s.addEventListener(Event.CONNECT, onConnectHandler);
s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
//
//Socket instance which will be used to connect to receive data sent by ftp server
r.addEventListener(ProgressEvent.SOCKET_DATA, onServData);
r.addEventListener(Event.CONNECT, onPasvConn);
r.addEventListener(IOErrorEvent.IO_ERROR,onIOERR);
dtimer = new Timer(10,1);
dtimer.addEventListener(TimerEvent.TIMER_COMPLETE,function(){checkForStream();});
this.addEventListener('dataReceived',onDataReceived);
var file:File = new File("XXX.zip");
initUpload(file)
}
private function onReturnData(evt:ProgressEvent)
{
var d = s.readUTFBytes(s.bytesAvailable);
trace(d);
//check here for complete list of return codes and their meaning
//- http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes
// the return message will have a 3 digit return code followed by a space and related message
// if the 3 digit return code is followed by "-" the it will be a multiline message
//-wait until the line with 3 digit code followed by space is delivered
if(d.indexOf("220 ")>-1){
//connected to ftp server send user name to server
s.writeUTFBytes("USER "+ftp_username+"\n");
s.flush()
}
if(d.indexOf("331 ")>-1){
//Username accepted now send password to server
s.writeUTFBytes("PASS "+ftp_password+"\n");
s.flush()
}
if (d.indexOf("230") > -1 && d.indexOf("OK.") > -1)
{
//Password accepted - lets enter passive mode and retrieve a list of files from a directory
//first enter passive mode
trace("Log in successful!");
s.writeUTFBytes("PASV \n");
s.flush();
}
var a = d.indexOf('227');
if (a > -1)
{
//Entering passive mode message will be returned along with it details of ip and port address will be returned
//-we have to connect to that address to receive the data
//format of the message will be: 227 Entering Passive Mode (209,190,85,253,148,206)
//the data inside brackets is the ip and port address, first four numbers represent IP and last 2 PORT
//the port value have to be calculated by multiplying the 5th number with 256 and adding the 6th number to it
//here in this example IP is 209.190.85.253 , PORT is (148*256)+206 = 38094
var st = d.indexOf("(",a);
var en = d.indexOf(")",a);
var str;
str = d.substring(st + 1,en);
var a2 = str.split(",");
var p1 = a2.pop();
var p2 = a2.pop();
var ip:String = a2.join(".");
var port:int=(p2*256)+(p1*1);
r.connect(ip, port);
}
if(d.indexOf("226 ")>-1){
//Data Transfer completely lets disconnect from server
if (process=='download')
{
trace("DOWNLOAD_COMPLETE");
}
if (process=='upload')
{
trace("UPLOAD_COMPLETE");
informServer();
}
dispatchEvent(new Event("dataReceived"))
}
if(d.indexOf("221 ")>-1){
//LOGGED OUT from server
}
if (d.indexOf("150 ") > -1)
{
if (process == 'upload')
{
//Once data connection is established we can start sending the data to the server
startSendingData();
}
}
}
private function onConnectHandler(evt:Event)
{
trace("CONNECTED TO FTP SERVER");
//Client has connected to ftp server
//you can also send multiple commands at same time like below or send step by step based on return code
//-!
//s.writeUTFBytes("USER username\n");
//s.writeUTFBytes("PASS password\n");
//s.flush();
}//
private function onPasvConn(evt:Event):void
{
trace("CONNECTED TO DATA PORT");
//Now send LIST command to retrieve directory listings
if (process == 'getDirList')
{
//To retrive directory listings send following command
s.writeUTFBytes("LIST "+remoteFolderStr+"\n");
}
else if (process=='download')
{
//To Download a file send following command
//RETR is the command followed by a space and path to file in remote server
s.writeUTFBytes("RETR "+remoteFolderStr+"/"+remoteFile+"\n");
}
else if (process=='upload')
{
//To Upload a file send following command
//STOR is the command followed by a space and path wher to store the file in remote server
//-with the name of the file to be saved as..you can provide any name with extension
s.writeUTFBytes("STOR /"+localFile.name+"\n");
}
s.flush();
}
private function onServData(evt:ProgressEvent):void
{
//DATA RECEIVED FROM SERVER THRO DATA PORT
var d = r.readUTFBytes(r.bytesAvailable);
if (process == 'getDirList')
{
d = r.readUTFBytes(r.bytesAvailable);
trace(d);
}
else if (process=='download')
{
//As the data connection is established start writing the data to the fileStream
fileData = new ByteArray();//temporary bytearray object to write the incoming data
r.readBytes(fileData, 0, r.bytesAvailable);//write data to the temp bytearray
fileStream.writeBytes(fileData, 0, fileData.bytesAvailable);//now write the bytearray to file stream
//instead you can directly write the data to file stream drom socket
}
}
private function onIOERR(evt:IOErrorEvent):void
{
trace(evt.errorID+":"+evt.text);
}
private function checkForStream():void
{
//this function is used to check if the incoming data is fully written to the filestream and then close the filestream
//-even if the ftp server dispatches that the file has been transfered...you application cn be still writing them to the filestream
if(!r.connected){
fileStream.close()
}else{
//if the file is still been writing restart the timer
dtimer.reset()
dtimer.start()
}
}
//
public function initUpload(fileToUpload:File):void
{
//called when upload event is triggered
localFile = fileToUpload;
if (localFile.exists)
{
// this.remoteFolderStr=remote_folder.text
startUploadProcess();
}
}
private function startUploadProcess():void
{
//create and open a fileStream
fileStream=new FileStream();
fileStream.open(localFile, FileMode.READ);
process = "upload";
fileData = new ByteArray();
//You need to pass this command 'TYPE I' to set data transfer mode as binary
s.writeUTFBytes("TYPE I\n");
s.writeUTFBytes("PASV \n");
s.flush();
}
private function startDownloadProcess():void
{
localFile = localFolder.resolvePath(remoteFile);
fileStream=new FileStream();
fileStream.open(localFile, FileMode.WRITE);
process = "download";
fileData = new ByteArray();
s.writeUTFBytes("TYPE I\n");
s.writeUTFBytes("PASV \n");
s.flush();
}
private function startSendingData():void
{
interval = setInterval(sendData,300);
}
private function sendData():void
{
//file to be uploaded is sent as binary data
if (fileStream.bytesAvailable <= 0)
{
clearInterval(interval);
r.close();
return;
}
if (fileStream.bytesAvailable < bufferSize)
{
bufferSize = fileStream.bytesAvailable;
}
var ba:ByteArray = new ByteArray();
fileStream.readBytes(ba, 0, bufferSize);
r.writeBytes(ba, 0, ba.bytesAvailable);
r.flush();
}
private function onDataReceived(evt:Event):void
{
if(process=='download'){
dtimer.start();
}
}
If anyone have this issue, i solved it by using small bufferSize, i set it to 100KB,
i found it is attempt to close the connection before all data is sent when the buffer is big.
You can add event OutputProgressEvent.OUTPUT_PROGRESS to check the number of bytes that has been written in the dataChannelConnection.

Create websocket server using nodejs that can be used to communicate with Android App

I have created a websocket server from my localhost machine that can be used to communicate with an android app.
The server is written in Node.js and hosted on my machine
var HOST = "192.168.0.15";
var PORT = 6969;
var Sock = net.Socket();
net.createServer(function(sock) {
Sock = sock;
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
var jsonStr = JSON.stringify(data);
sock.write(jsonStr);
var buffer = "";
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
Sock.emit("data", data);
});
});
And my Android app uses Java Websocket with
socket = new Socket("192.168.0.15", 6969);
commsThread = new CommsThread(socket);
commsThread.start();
My Android device used to test my app and my server runs in the same network so they work fine.
However, when I deploy it in Heroku, it gives me an error.
NOTE: I have tried changing the HOST address and PORT address but to no avail.
I was told that Heroku doesn't support TCP socket server.
I am not sure if the example above is an TCP socket server.
If not, why are some of the alternatives I can use.
Cheers,
Dennis
Why don't you use socket.io-java-client along with the socket.io module for Node.js?
Did you enable websockets in Heroku?
$ heroku labs:enable websockets

air for android - Cant upload to FTP

I'm trying to upload a simple text file to ftp, the code works on the pc.
On android the app connects successfully to the ftp but when I try to upload the file I get "2031:Error #2031: Socket Error."
Any ideas?
The code (from http://suzhiyam.wordpress.com/2011/04/) is:
import flash.events.ProgressEvent;
import flash.events.Event;
import flash.net.Socket;
import flash.events.IOErrorEvent;
import flash.errors.IOError;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.events.MouseEvent;
msg.text="Wait! Connecting to ftp server!"
//
var ftp_host:String = "*"; //FTP settings are correct in the original code...
var ftp_port:Number = 21;
var ftp_username:String = "*";
var ftp_password:String = "*";
//
//in this demo we will be manually entering the remote servers folder from which upload or download should happen
var remoteFolderStr:String;
var localFolderStr:String;
var remoteFile:String;
//Socket instance which will be used to connect to ftp server
var s = new Socket(ftp_host,ftp_port);
s.addEventListener(IOErrorEvent.IO_ERROR,onIOERR);
s.addEventListener(ProgressEvent.SOCKET_DATA, onReturnData);
s.addEventListener(Event.CONNECT, onConnectHandler);
//
//Socket instance which will be used to connect to receive data sent by ftp server
var r:Socket = new Socket();
r.addEventListener(ProgressEvent.SOCKET_DATA, onServData);
r.addEventListener(Event.CONNECT, onPasvConn);
r.addEventListener(IOErrorEvent.IO_ERROR,onIOERR);
//For every command the client sends to ftp server the server returns message with return codes
function onReturnData(evt:ProgressEvent)
{
var d = s.readUTFBytes(s.bytesAvailable);
trace(d);
//check here for complete list of return codes and their meaning
//- http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes
// the return message will have a 3 digit return code followed by a space and related message
// if the 3 digit return code is followed by "-" the it will be a multiline message
//-wait until the line with 3 digit code followed by space is delivered
if (d.indexOf("220 ") > -1)
{
msg.text="Logging in to ftp server!"
//connected to ftp server send user name to server
s.writeUTFBytes("USER "+ftp_username+"\n");
s.flush();
}
if (d.indexOf("331 ") > -1)
{
//Username accepted now send password to server
s.writeUTFBytes("PASS "+ftp_password+"\n");
s.flush();
}
if (d.indexOf("230") > -1 && d.indexOf("OK.") > -1)
{
msg.text="Log in successful!"
//Password accepted - lets enetr passive mode and retrive a list of files from a directory
//first enetr passive mode
//s.writeUTFBytes("PASV \n");
//s.flush();
}
var a = d.indexOf('227');
if (a > -1)
{
//Entering passive mode message will be returned along with it details of ip and port address will be returned
//-we have to connect to that address to receive the data
//format of the message will be: 227 Entering Passive Mode (209,190,85,253,148,206)
//the data inside brackets is the ip and port address, first four numbers represent IP and last 2 PORT
//the port value have to be calculated by multiplying the 5th number with 256 and adding the 6th number to it
//here in this example IP is 209.190.85.253 , PORT is (148*256)+206 = 38094
var st = d.indexOf("(",a);
var en = d.indexOf(")",a);
var str;
str = d.substring(st + 1,en);
var a2 = str.split(",");
var p1 = a2.pop();
var p2 = a2.pop();
var ip:String = a2.join(".");
var port:int=(p2*256)+(p1*1);
r.connect(ip, port);
}
if (d.indexOf("226 ") > -1)
{
//Data Transfer completed
//s.writeUTFBytes("QUIT \n");
//s.flush();
if (process=='download')
{
msg.text="DOWNLOAD_COMPLETE"
}
if (process=='upload')
{
msg.text="UPLOAD_COMPLETE"
}
dispatchEvent(new Event("dataReceived"))
}
if (d.indexOf("221 ") > -1)
{
//LOGGED OUT from server
}
//Response code 150 will be sent by server whenever a data connection is established after we send 'PASV' command
if (d.indexOf("150 ") > -1)
{
if (process == 'upload')
{
//Once data connection is established we can start sending the data to the server
startSendingData();
}
}
}
function onConnectHandler(evt:Event)
{
msg.text="CONNECTED TO FTP SERVER!"
trace("CONNECTED TO FTP SERVER");
//Client has connected to ftp server
}
function onPasvConn(evt:Event):void
{
trace("CONNECTED TO DATA PORT");
//s.writeUTFBytes("LIST /your/folder/path\n");
if (process=='upload')
{
//To Upload a file send following command
//STOR is the command followed by a space and path wher to store the file in remote server
//-with the name of the file to be saved as..you can provide any name with extension
s.writeUTFBytes("STOR /test.txt\n");
}
s.flush();
}
function onServData(evt:ProgressEvent):void
{
//DATA RECEIVED FROM SERVER THRO DATA PORT
}
function onIOERR(evt:IOErrorEvent)
{
trace(evt.errorID+":"+evt.text);
}
//
var process:String = "";// variable to store what action is being performed
var writeToStream:Boolean;//not used here
var localFile:File;//local file which it to be uploaded
var localFolder:File;// local folder to which the downloaded file to be stored
var interval:Number;
var bufferSize:int;
//
BTN_Upload.addEventListener(MouseEvent.CLICK,initUpload);
function initUpload(evt:MouseEvent=null):void
{
//called when upload event is triggered
startUploadProcess();
}
function startUploadProcess():void
{
process = "upload";
//You need to pass this command 'TYPE I' to set data transfer mode as binary
s.writeUTFBytes("TYPE I\n");
s.writeUTFBytes("PASV \n");
s.flush();
}
function startSendingData():void
{
var textToUpload:String = "This is a test";
bufferSize = textToUpload.length;
var ba:ByteArray = new ByteArray();
//Store the info you want to upload in ByteArray HERE
ba.writeMultiByte(textToUpload, "iso-8859-1");
r.writeBytes(ba, 0, ba.bytesAvailable);
r.flush();
}

Categories

Resources