This is probably more of a javascript question but I dont really know javascript in general, so im hoping its a simple fix.
So basically I am using two libraries that I want to work together. The beacon class listens for a bluetooth LE signal on a raspberry pi, at which point the onAdvertisement fucntion is called from the node-beacon-scanner library.
When this happens I want to publish a message to a message broker using MQTT (the other library), which should be a case of just calling client.publish(topic, message).
THe publish function works when I use it outside of the scanner functions, however if I call it inside one of the scanner functions such as onAdvertisement, it doesnt work, but also doesnt throw any errors.
I think it is an issue of me not understanding encapsualtion in node.js regarding modules.
Basically I want to know is there somthign im missing when calling the client.publish function from within the scanner.onadvertisement function? In the code below the publish call has been put in a function called pubBe.
Thankyou in advance!
const noble = require('@abandonware/noble');
const BeaconScanner = require("node-beacon-scanner");
const mqtt = require('mqtt');
var client = mqtt.connect('http://localhost:1883');
var scanner = new BeaconScanner();
var ledOn = false
client.on('connect', function () {
client.subscribe('led', function (err) {
if (!err) {
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
scanner.onadvertisement = (advertisement) => {
var beacon = advertisement["rssi"]
}
scanner.startScan().then(() => {
console.log("Scanning has started...")
pubBe(-10)
}).catch(error => {
console.error(error);
})
function pubBe(rssi){
if( rssi > -40 && !ledOn){
console.log('Turn LED on')
ledOn = true
payload = {"level": 100}
client.publish('led', JSON.stringify(payload))
}else if ( rssi < -40 && ledOn){
console.log('Turn LED off')
ledOn = false
payload = {"level": 0}
client.publish('led', JSON.stringify(payload))
}
}
question from:
https://stackoverflow.com/questions/65906331/calling-a-class-function-from-within-another-class-function-js-newb 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…