Hello everyone. i’am trying to send data from esp8266 to my ionic app throw mqtt server.
here’s my code
nodejs index.js
var Hapi = require(‘hapi’);
var mqtt = require(‘mqtt’);var server = new Hapi.Server();
var port = Number(process.env.PORT || 4444);server.connection({ port: port, routes: { cors: true } });
var client = mqtt.connect(‘mqtt://test.mosquitto.org:1883’);
var mqttPublish = function(topic, msg){
client.publish(topic, msg, function() {
console.log('msg sent: ’ + msg);
});
}//client.subscribe(“device/sensor”);
var mqttSubdcribe = function(topic, msg){
client.subscribe(topic, msg, function() {
console.log('msg received: ’ + msg);
});
}server.route([
{
method: ‘POST’,
path: ‘/device/control’,
handler: function (request, reply) {
var deviceInfo = ‘dev’ + request.payload.deviceNum + ‘-’ + request.payload.command;
reply(deviceInfo);
mqttPublish(‘device/control’, deviceInfo, {
‘qos’ : 2
});
}
}
]);server.route([
{
method: ‘GET’,
path: ‘/device/sensor’,
handler: function (request, reply) {
var deviceInfo = ‘dev222222222_hello world’;
reply(deviceInfo);
mqttSubdcribe(‘device/sensor’, deviceInfo, {
‘qos’ : 2
});
console.log(deviceInfo.toString())
}
}a
]);server.start();
ionic app
services.js
angular.module(‘starter.services’, )
.factory(‘Devices’, function($http) {
// Might use a resource here that returns a JSON arrayvar ipServer = ‘http://esp8266-relays.herokuapp.com’;
//var ipServer = ‘https://damp-harbor-45648.herokuapp.com’;return {
deviceCommand: function(data) {
console.log(data);
return $http.post(ipServer + ‘/device/control’, data);
},
all: function () {
return $http.get(ipServer + ‘/device/sensor’)
},
get: function () {
return $http.get(ipServer + ‘/device/sensor’)
}
};
});
controllers.js
angular.module(‘starter.controllers’, )
.controller(‘DashCtrl’, function($scope, $stateParams, Devices) {
$scope.powerOff = function (deviceNum) {
deviceControl(deviceNum, ‘off’);
}$scope.powerOn = function (deviceNum) {
deviceControl(deviceNum, ‘on’);
}function deviceControl(deviceNum, command){
var deviceInfo = {
deviceNum : deviceNum,
command : command
};Devices.deviceCommand(deviceInfo) .success(function (data) { console.log(data) }) .error(function (error) { console.log(error) });
}
})
.controller(‘AboutCtrl’, function($scope, $stateParams, Devices) {
Devices.all().success(function (response) {
$scope.friends = response;
})
});
aboutTab.html
> <ion-view view-title="About">
> <ion-content>
> <ion-list>
> <ion-item class="item-icon-right padding" ng-repeat="data in friends">
> <p>{{ data}}</p>
> <i class="icon ion-chevron-left icon-accessory"></i>
> </ion-item>
> </ion-list>
> </ion-content>
> </ion-view>
for post method it works but not with get method! it shows this error
GET http://esp8266-relays.herokuapp.com/device/sensor 404 (Not Found)
any idea PLEASE? what am’i doing wrong?