I have created a RESTAPI in Node.js and trying it to invoke into my android application. But i am not able to make the request to the Node.js Rest API.
My code are as follows:
Node.js
var restify = require('restify');
var request = require('request');
var http = require('http');
var appContext = require('./config.js');
function labsAPI(jsonparseStr) {
return JSON.stringify(labsapi);
}
function searchbase(req, res, next){
var options = {
host: appContext.host,
path: appContext.path+req.params.name+appContext.queryString
};
cbCallback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
jsonparseStr = JSON.parse(str);
json_res = labsAPI(jsonparseStr);
res.writeHead(200,{'Content-Type':'application/json'});
res.end(json_res);
});
}
http.request(options, cbCallback).end();
}
var server = restify.createServer({name:'crunchbase'});
server.get('/search/:name',searchbase);
server.listen(appContext.port, function() {
console.log('%s listening at %s', server.name, server.url);
});
After running my code like : localhost:8084/search/name
I am able to return the output to the browser a valid Json.
Now i want to consume this web service into my android application , I am not able to figure out how to do it.
I tried some of the example
http://hmkcode.com/android-parsing-json-data/
In the above blog in MainActivity.java i changed my url to
new HttpAsyncTask().execute("http://127.0.0.1:8084/search/name");
but it is displaying nothing
127.0.0.1 is the IP address for localhost. From your browser localhost resolves to your computer, from your Android device localhost resolves to your Android device, but your node application isn't running on it.
You need to figure out what's your computer's remote address. LAN or WLAN would be enough as long as your on the same network as your Android device.
Also make sure firewall settings allow access to your computer.
Related
Trying to send esp32 chip wifi credentials from android app (built with ionic). Using Ionic capacitor/bluetooth-le plug in to write to esp32, using the write function:
await BleClient.write(device.deviceId, GATT Service ID, Characteristic ID, textToDataView('wifi_ssid,wifi_password'));
Code for BleClient.write:
async write(deviceId: string, service: string, characteristic: string, value: DataView): Promise<void> {
service = validateUUID(service);
characteristic = validateUUID(characteristic);
return this.queue(async () => {
if (!value?.buffer) {
throw new Error('Invalid data.');
}
let writeValue: DataView | string = value;
if (Capacitor.getPlatform() !== 'web') {
// on native we can only write strings
writeValue = dataViewToHexString(value);
}
await BluetoothLe.write({
deviceId,
service,
characteristic,
value: writeValue,
});
});
}
How to pass wifi credentials as value argument to the write function so it's correctly received by ESP32?
On the ESP32 side, I'm using the wifi_prov_mgr example code, which in turn uses google protocol buffer (I'm very new to protobuf and don't really understand how it works). ESP uses wifi_config.c (Espressif wifi_provisioning component). When I send wifi credentials from the app using BleClient.write, it shows up in wifi_config.c as inbuf with value wifi_ssid,wifi_password:��Z�?�Z�?
Here's the relevant code for wifi_config.c:
esp_err_t wifi_prov_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data)
{
ESP_LOGI(TAG ,"Wifi config payload inbuf value: %s", inbuf);
WiFiConfigPayload *req;
WiFiConfigPayload resp;
esp_err_t ret;
req = wi_fi_config_payload__unpack(NULL, inlen, inbuf);
if (!req) {
ESP_LOGE(TAG, "Unable to unpack config data");
return ESP_ERR_INVALID_ARG;
}
I'm having a very hard time understanding how wi_fi_config_payload_unpack processes the inbuf argument. This is where the code gets into protobuf code generated by the proto files. The proto file for wifi config data looks like this:
message CmdSetConfig {
bytes ssid = 1;
bytes passphrase = 2;
bytes bssid = 3;
int32 channel = 4;
}
message WiFiConfigPayload {
WiFiConfigMsgType msg = 1;
oneof payload {
CmdGetStatus cmd_get_status = 10;
RespGetStatus resp_get_status = 11;
CmdSetConfig cmd_set_config = 12;
RespSetConfig resp_set_config = 13;
CmdApplyConfig cmd_apply_config = 14;
RespApplyConfig resp_apply_config = 15;
}
}
So my question is - how do I pass the wifi credentials in BleClient.write so it is correctly recognized by wifi_config.c on the ESP32 side?
I thought about using the Android app developed by Espressif to pass wifi credentials to the ESP32 chip, but then I don't know how to integrate native Android code with ionic code, since I need my app to do more than just credential the ESP32.
Resolved this issue by using Google's protocol buffer code for javascript. Here's code that worked for me:
import * as goog from 'google-protobuf';
export class SetupPage implements OnInit {
messages = require('../../assets/proto-js/wifi_config_pb.js');
connectedDevice: BleDevice;
bleScan: any;
wifiSSID: Promise<any>;
scanResults: Promise<[]>;
wifiCredentials: string;
uint8String: Uint8Array;
buffer: Uint8Array;
ngOnInit() {
async getBLE(){
await BleClient.initialize();
var cmdSetMessage = new this.messages.CmdSetConfig();
var wifiConfigPayloadMessage = new this.messages.WiFiConfigPayload;
message.setSsid('wifiid');
message.setPassphrase('password');
wifiConfigPayloadMessage.setCmdSetConfig(cmdSetMessage);
wifiConfigPayloadMessage.setMsg(2); //this is ESP32 BLE specific
let bytesOfStuff = await wifiConfigPayloadMessage.serializeBinary();
this.connectedDevice = await BleClient.requestDevice();
await BleClient.connect(this.connectedDevice.deviceId);
BleClient.writeWithoutResponse(this.connectedDevice.deviceId, '021a9004-0382-
4aea-bff4-6b3f1c5adfb4', '021aff52-0382-4aea-bff4-6b3f1c5adfb4',
bytesOfStuff)
//After this, you need to send wifiConfigPayloadMessage.setMsg(4) to ESP32 to apply wifi credentials and connect to the selected wifi
}
}
Before this code can function, you need to install google-protobuf from npm or other package installer and protoc or another compiler for the proto files in order to generate pb.js files (since I'm working with javascript) for each proto file. In this example, the proto file is called wifi_config.proto, and the corresponding pb.js file (created by running protoc) is called wifi_config_pb.js.
Functions used to create the data to be transferred are defined in the pb.js files and correspond to objects defined in the proto files. The following references will help a lot if you don't have a good understanding of how this mechanism works:
https://developers.google.com/protocol-buffers/docs/proto3 (google protocol-buffer tutorial)
Protocol Buffers in Ionic (stack question)
I'm trying to access my web server hosted on http://localhost:8080 on an Angular App built with Cordova. I can access the server with a navigator on my emulator but I never receive any request from the application itself it's just failed with the following error: [objectProgressEvent].
My request is like this and works if I build the web application hosted on localhost:8081:
getToken(username, password) {
var req = { username: username, password: password };
this.http.post(this.urlToken, req).toPromise().then((data) => {
document.getElementById("loader").style.display = "none";
for (let key in data) {
this.token = data[key]
localStorage.setItem('token', this.token);
}
if (void this.getIfActiveUser(username) != 84) {
localStorage.setItem('user', username);
this.authService.login();
}
}).catch((err: HttpErrorResponse) => {
document.getElementById("loader").style.display = "none";
this.getIfActiveUser(username)
console.error('An error occurred:', err.error);
document.getElementById("warning").style.display = "block";
if (err.error["non_field_errors"])
document.getElementById("warning").innerHTML = err.error["non_field_errors"];
if (err.error["username"])
document.getElementById("warning").innerHTML = err.error["username"]
if (err.error["password"])
document.getElementById("warning").innerHTML = err.error["password"]
});
}
Android API doesn't allow clear text communication by default.
(CleartextTrafficPermitted)
You can check this answer to allow it.
I am posting the data from Android to the Node.js. I am successfully able to call the Node.js post method and using restify able to get the Post data.
But when doing through express I am not able to get the post body in Node.js. I tried for many approaches from SO post but it seems none are working may be I am missing something.
The snippets are like:
Node.js
var express = require('express')
var request = require('request')
var http = require('http')
var bodyParser = require('body-parser')
var app = express();
app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.urlencoded())
app.use(bodyParser.json())
app.post('/search/addcomplaint',addComplaint)
function addComplaint(req,res,next){
console.log(req.body);
if (!req.body) return res.sendStatus(400)
res.send(201,user)
}
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
})
at Android Site I am making a retrofit call like this:
#Multipart
#POST("/search/addcomplaint")
public User search(#Part("complaint") String complaint);
when I used restify in Node.js I was able to get req.body but using express I am not getting the request body.
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
I'm trying to find the best way to send my users a real-time status update of a process that's running on my server - this process is broken up into five parts. Right now I'm just 'pulling' the status using an Ajax call every few seconds to a PHP file that connects to MySQL and reads the status, but as you can imagine, this is extremely hard on my database and doesn't work so well with users that don't have a strong internet connection.
So I'm looking for a solution that will 'push' data to my client. I have APE push-engine running on my server now, but I'm guessing Socket.IO is better for this? What if they're on 3G and they miss a status update?
Thanks in advance :)
I guess my answer may match what you need.
1st: You Have to Get Node.js to run the socket.io
BELOW IS SAMPLE CODE FOR SERVER:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8800); //<---------Port Number
//If No Connection / Page Error
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
//If there is connection
io.sockets.on('connection', function (socket) {
//Set Varible
var UserID;
var Old_FieldContent = "";
socket.on('userid', function (data) {
if(data.id){
UserID = data.id;
StartGetting_FileName(UserID)
}
});
//Checking New Status
function StartGetting_FileName(UserID){
//Create Interval for continues checking from MYSQL database
var myInterval = setInterval(function() {
//clearInterval(myInterval);
//MySQL Connection
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : '3306',
user : 'root',
password : 'ABCD1234',
database : 'test',
});
//Setup SQL Query
var SQL_Query = "SELECT FileName FROM status WHERE UserID = '"+UserID+"'";
connection.connect();
connection.query(SQL_Query, function(err, rows, fields) {
//Do if old result is, different with new result.
if(Old_FieldContent !== rows[0].FileName){
if (err) throw err;
//Display at Server Console
console.log('------------------------------------------');
console.log('');
console.log('Fields: ', fields[0].name);
console.log('Result: ', rows[0].FileName);
console.log('');
console.log('------------------------------------------');
//Send Data To Client
socket.emit('news', { FieldName: fields[0].name });
socket.emit('news', { FieldContent: rows[0].FileName });
//Reset Old Data Variable
Old_FieldContent = rows[0].FileName;
}
});
connection.end();
}, 500 );
}
});
BELOW IS CLIENT HTML & JS:
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<!-- URL PATH TO LOAD socket.io script -->
<script src="http://15.17.100.165:8800/socket.io/socket.io.js"></script>
<script>
//Set Variable
var UserID = "U00001";
var socket = io.connect('http://15.17.100.165:8800');
var Field_Name = "No Data";
var Field_Content = "No Data";
// Add a disconnect listener
socket.on('connecting',function() {
msgArea.innerHTML ='Connecting to client...';
console.log('Connecting to client...');
//Once Connected Send UserID to server
//for checking data inside MYSQL
socket.emit('userid', { id: UserID });
});
// Get data that push from server
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
msgArea.innerHTML ='The client has disconnected!';
console.log('The client has disconnected!');
});
//Function to display message on webpage
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
// msgArea.innerHTML = msg.hello;
if(msg.FieldName !== undefined){
Field_Name = msg.FieldName;
}
if(msg.FieldContent !== undefined){
Field_Content = msg.FieldContent;
}
}else {
msgArea.innerHTML = msg;
}
msgArea.innerHTML = Field_Name +" = "+ Field_Content;
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
You should consider using push notifications, with the service provided for Android by Google as C2DM: https://developers.google.com/android/c2dm/
You will need to implement a PhoneGap plugin to handle the native notifications, and communicate them to your PhoneGap project that will then (and only then) query your server .
As K-ballo above points out, using a push notification plugin would be best.
Luckily, some good citizen on GitHub has done this already!
https://github.com/awysocki/C2DM-PhoneGap
Please note: the above C2DM plugin was built for PhoneGap v1.2, so if you are running a more up-to-date version you will have to tweak the native code a bit to get it working better.