I'm working on NodeJS and I have this module:
Manager.js
with this code (this is not all the code...):
//
// Object Manager
function Manager(params) {
client = new ModbusRTU();
}
//connessione alla seriale per lettura modbus
Manager.prototype.connectClient = function(){
// try to connect
client.connectRTUBuffered ("/dev/ttyS3", { baudRate: 19200 })
.then(function()
{
mbsState = MBS_STATE_GOOD_CONNECT;
mbsStatus = "Connected, wait for reading...";
console.log(mbsStatus);
})
.catch(function(e)
{
mbsState = MBS_STATE_FAIL_CONNECT;
mbsStatus = e.message;
console.log("Error:"+e);
});
client.setTimeout (20);
}
//read data
Manager.prototype.readData = function(){
var self = this;
client.setID(2);
// try to read data
client.readCoils (0, 7, function(error,data){
if(!error){
self.checkEmergency();
}
});
}
//emergency
Manager.prototype.checkEmergency= function(){
}
exports.Manager=Manager;
client part of code is about a modbus application.
When I try to call "self.checkEmergency()" from readData, I have this error:
"self.checkEmergency() is not a function"
Why?
The method readData is called inside a method like this:
Manager.prototype.caller= function(){
var self = this;
self.readData();
}
I also have used self to pass the object to the callback...
Any idea?
Related
I'm fairly new to Node, and I'm trying to connect to a Clover Mini device through a websocket using the API provided by Clover.
I've tried modifying the example code below to work using only node, but when I open it in node nothing happens. (No errors, just nothing happens at all)
It works in Chrome just fine, so what's missing?
https://github.com/clover/remote-pay-cloud
var $ = require('jQuery');
var clover = require("remote-pay-cloud");
var log = clover.Logger.create();
var connector = new clover.CloverConnectorFactory().createICloverConnector({
"oauthToken": "1e7a9007-141a-293d-f41d-f603f0842139",
"merchantId": "BBFF8NBCXEMDV",
"clientId": "3RPTN642FHXTX",
"remoteApplicationId": "com.yourname.yourapplication:1.0.0-beta1",
"deviceSerialId": "C031UQ52340015",
"domain": "https://sandbox.dev.clover.com/"
});
var ExampleCloverConnectorListener = function(cloverConnector) {
clover.remotepay.ICloverConnectorListener.call(this);
this.cloverConnector = cloverConnector;
};
ExampleCloverConnectorListener.prototype = Object.create(clover.remotepay.ICloverConnectorListener.prototype);
ExampleCloverConnectorListener.prototype.constructor = ExampleCloverConnectorListener;
ExampleCloverConnectorListener.prototype.onReady = function (merchantInfo) {
var saleRequest = new clover.remotepay.SaleRequest();
saleRequest.setExternalId(clover.CloverID.getNewId());
saleRequest.setAmount(10000);
this.cloverConnector.sale(saleRequest);
};
ExampleCloverConnectorListener.prototype.onVerifySignatureRequest = function (request) {
log.info(request);
this.cloverConnector.acceptSignature(request);
};
ExampleCloverConnectorListener.prototype.onConfirmPaymentRequest = function (request) {
this.cloverConnector.acceptPayment(request.payment);
};
ExampleCloverConnectorListener.prototype.onSaleResponse = function (response) {
log.info(response);
connector.dispose();
if(!response.getIsSale()) {
console.error("Response is not an sale!");
console.error(response);
}
};
var connectorListener = new ExampleCloverConnectorListener(connector);
connector.addCloverConnectorListener(connectorListener);
connector.initializeConnection();
After getting into contact with the developers at clover, their documentation had some errors. For other users sake here is the link to that issue on their gitub as well as some example code.
link to github issue
const endpoint = "ws://yourip:yourport/remote_pay";
var webSocketFactory = function () {
let webSocketOverrides = {
createWebSocket: function () {
// To support self-signed certificates you must pass rejectUnauthorized = false.
// https://github.com/websockets/ws/blob/master/examples/ssl.js
let sslOptions = {
rejectUnauthorized: false
};
// Use the ws library by default.
return new WebSocket(endpoint, sslOptions);
}
}
return Object.assign(new clover.CloverWebSocketInterface(endpoint), webSocketOverrides);
};
var ExampleWebsocketPairedCloverDeviceConfiguration = function () {
clover.WebSocketPairedCloverDeviceConfiguration.call(this,
endpoint, // endpoint
"com.cloverconnector.javascript.simple.sample:1.4", // Application Id
"Javascript Simple Sample", // posName
"Register_1", // serialNumber
null, // authToken().get(
webSocketFactory,
new clover.ImageUtil());
};
I am using my custom yeoman generator programmatical in one of my nodejs module. I have written an Adapter to replace default TerminalAdapter.
The issues are,
When I am triggering custom event using emit method, I am not able
to listen for that event in my module. It is not getting fired.
Even end event listener also not getting fired.
Please let me know what I am missing here,
Below is my module code,
'use strict';
var fs = require('fs');
var path = require('path');
var MyOwnAdapter = require('./MyOwnAdapter');
var adapt = new MyOwnAdapter();
var env = require('./generator-myframewrk/node_modules/yeoman-generator')(null, {}, adapt);
env.register(path.resolve(__dirname, './generator-myframewrk'), 'myframewrk');
exports.run = function (options, answers) {
var obj = {};
adapt.setAnswers(answers);
process.chdir(options.projdir);
env.on("end", function(){
this.log("Even this is not getting called !!!"); //not coming here
}.bind(this));
env.on("alldone", function(){
this.log("Everything is done (including Bower install)"); //not coming here
obj.cb();
}.bind(this));
env.run('myframewrk', function(){
this.log('ran yo myframewrk, But bower install might be pending'); //coming here
});
return {
done: function (cb) {
obj.cb = cb;
}
};
};
Below is my Generator code,
var MyframewrkGenerator = yeoman.generators.Base.extend({
init: function () {
this.pkg = require('../package.json');
this.on('end', function () {
if (!this.options['skip-install']) {
this._installBower();
}
});
},
_installBower: function () {
this.log("Running bower install...");
/*reads bower.json and installs*/
bower.commands.install([], {}, {directory : "./"}).on('error', function (error) {
this.log("BOWER error::");
this.log(JSON.stringify(error));
}.bind(this)).on('log', function (log) {
this.log("BOWER LOG::"); // coming here
}.bind(this)).on('end', function (installed) {
this.log("BOWER END::"); // coming here
this.emit("alldone"); // my custom event
}.bind(this));
},
askFor: function () { ...
I took _installBower method out of this.on('end', function () {}); and made it a separate async func. This works fine. I don't need custom event anymore!
Thx...
bowerInstallHelper: function(){
if (!this.options['skip-install']) {
var cb = this.async();
this._installBower(cb);
}
}
I have the following reconnect method for Sockjs which almost is fully working:
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
clearInterval(connectRetry);
$('.connect-status')
.removeClass('disconnected')
.addClass('connected')
.text('Connected');
};
warbleSocket.onmessage = function(e) {
$('#warble-msg').text(e.data);
};
warbleSocket.onclose = function() {
clearInterval(connectRetry);
connectRetry = setInterval(connectToServer, 1000);
$('.connect-status')
.removeClass('connected')
.addClass('disconnected')
.text('Disconnected');
};
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
var connectRetry = setInterval(connectToServer, 1000);
})();
The error i am getting is when its trying to reconnect.
Error is:
SyntaxError: missing ] after element list
at this line:
connectRetry = setInterval(connectToServer, 1000);
Any ideas what im doing wrong here?
Your connectToServer variable is not a function, it's an object with a property send that is a function, so it doesn't make sense to say setInterval(connectToServer, 1000). Try this instead:
setInterval(connectToServer.send, 1000);
Why don't you simplify things a bit?
I would put connection stuff inside a specific function and call it from setInterval().
Something like this (use with care since I'm not testing this code, ok?):
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket;
function connect() {
warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
// ...
};
warbleSocket.onmessage = function(e) {
// ...
};
warbleSocket.onclose = function() {
// ...
}
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
// you probably will need to call the first connection
connectToServer();
// and than set connection retry
var connectRetry = setInterval(connectToServer.connect, 1000);
})();
I hope it helps you.
Regards,
Heleno
I am trying to create a data management application, but instead of a Windows-based solution or using WebSQL, i am using IndexedDB. I am pretty new to it but I believe I have covered the basis in this draft of code.
Anyway, my problem is, anytime I run the code, my openDB() function and the addeventListener() function both run and show on the console log at runtime but all other functions are said to be undefined when I try to run the code. What could the problem be?
In the HTML file, the jQuery script file is referenced.
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
var DB_STORE_NAME = 'visitors';
var db;
var current_view_pub_key;
//opens the IndexedDB database
function openDb() {
console.log("open Database......");
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onsuccess = function (evt) {
db = this.result;
console.log("Database Opened");
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
console.log("Event fired when DB is needed to be upgraded");
var store = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('name', 'name', { unique: false });
store.createIndex('date', 'date', { unique: false });
store.createIndex('whom_to_see', 'whom_to_see', { unique: false });
store.createIndex('arrival_time', 'arrival_time', { unique: false });
store.createIndex('reason', 'reason', { unique: false });
store.createIndex('departure_time', 'departure_time', { unique: false });
};
}
//used to create a transaction
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
//adds a Visitor to the IndexedDB
function addVisitor(name, date, to_see, arrival_time, reason, departure_time) {
console.log("Adding the following data to IndexedDB: ", arguments);
var obj = { name: name, date: date, whom_to_see: to_see, arrival_time: arrival_time, reason: reason, departure_time: departure_time };
if(typeof blob != undefined)
{
obj.blob = blob;
}
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req;
try
{
req = store.add(obj);
}
catch(e)
{
if(e.name == 'DataCloneError')
displayActionFailure("This engine does not know how to clone a Blob, use Firefox!");
throw(e);
}
req.onsuccess = function (evt) {
console.log("Insertion into DB was successful. You can heave a huge sigh of relief!");
displayActionSuccess();
};
req.onerror = function () {
console.error("Insertion into DB failed!");
displayActionFailure(this.error);
};
}
function displayActionSuccess() {
alert("Whatever the heck you were doing was successful. Congrats!");
}
function displayActionFailure() {
alert("Oh Oh! System Failure! System Failure!");
}
// listens for the submit button event
function addEventListeners() {
console.log("Event Listeners");
$('#addVisitor').click(function(evt) {
console.log("Add Visitors Submit button");
var name = document.getElementsByName("txtName").value;
var date = document.getElementsByName("txtDate").value;
var whom_to_see = document.getElementsByName("txtToSee").value;
var time_of_arrival = document.getElementsByName("txtArrivalTime").value;
var reason_for_visit = document.getElementsByName("txtReason").value;
var time_of_departure = document.getElementsByName("timeOfDep");
addVisitor(name, date, whom_to_see, time_of_arrival, reason_for_visit, time_of_departure);
});
}
//makes the database open at runtime
openDb();
addEventListeners();
})
();
syntax error - you need a closing round bracket at end.
i.e add
);
I think the problem is the fact that when your anonymous function is run the browser doesn't not know about the '#addVisitor' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
...
Instead of referencing the javascript code like before...
I removed all other functions from the javascript file leaving the openDB() function and placed them in the main html file. it worked automatically.
This code is running in my node.js server application:
io.sockets.on('connection', function (socket) {
var c = new Client(socket, Tools.GenerateID());
waitingClients.push(c);
allClients.push(c);
if (waitingClients.length === 2)
{
activeGames.push(new Game([waitingClients.pop(), waitingClients.pop()]));
}
});
function Client(socket, id)
{
this.Socket = socket;
this.ID = id;
this.Player = new Player();
this.Update = function(supply)
{
socket.emit('update', { Actions: this.Player.Actions, Buys: this.Player.Buys, Coins: this.Player.Coins, Hand: this.Player.Hand, Phase: this.Player.Phase, Supply: supply});
}
socket.on('play', function(data) {
console.log(data);
console.log(this.Player);
});
socket.emit('id', id);
}
The part I'm having trouble with is the event handler for the 'play' event. console.log(this.Player) outputs undefined. I sorta understand why it's wrong, because 'this' refers to something other than my client object (the socket? the anonymous function?) , but I don't know how to re-arrange the code to handle the 'play' event properly, and have full access to the members of the Client object.
You just need to store this in some other variable inside Client.
function Client(socket, id)
{
var self = this;
...
socket.on('play', function(data) {
self.Player.play();
});