Should I build chrome from source to jump over the select device prompt?
https://googlechrome.github.io/samples/web-bluetooth/
try {
log('Requesting Bluetooth Device...');
log('with ' + JSON.stringify(options));
const device = await navigator.bluetooth.requestDevice(options);
log('> Name: ' + device.name);
log('> Id: ' + device.id);
log('> Connected: ' + device.gatt.connected);
} catch(error) {
log('Argh! ' + error);
}
Chrome's current implementation of Web Bluetooth does not have a way for websites to get a list of permitted devices. With the upcoming Bluetooth.getDevices() method, a list of BluetoothDevice objects that the current origin has been granted permission to use by the user will be returned. See https://googlechrome.github.io/samples/web-bluetooth/get-devices.html for an example.
log('Getting existing permitted Bluetooth devices...');
navigator.bluetooth.getDevices()
.then(devices => {
console.log('> Got ' + devices.length + ' Bluetooth devices.');
for (const device of devices) {
console.log(' > ' + device.name + ' (' + device.id + ')');
}
})
.catch(error => {
console.log('Argh! ' + error);
});
Related
I'm working with Firebase Realtime Database and am a fairly new developer. I'm working on a chat application and need to detect which thread to put a message in that comes to a firebase function. The function gets the fromID (sender) and the userID (receiver) and needs to detect which thread belongs to the users.
Issue: The problem is that it successfully detects the thread the first time the message comes in, but then continues afterward - creating a new thread as if the relationship doesn't exist.
Structure:
users
- uid
- threads
- $threadKey
threadMembers
- $threadKey
- members
- $fromID_$userID
Code:
const db2 = admin.database();
db2.ref('users/' + userId + '/threads').once('value').then(snapshot => {
if (!snapshot.exists()) {
console.log("User does not have any threads")
return functions.logger.log('User doesnt have a Thread.');
}
snapshot.forEach((doc) => {
console.log("SNAP : " + doc.key)
checkThreads(doc.key)
})
return functions.logger.log('Finished checking user/uid/threads');
})
function checkThreads(threadId){
const threadRef = db2.ref('threadMembers/' + threadId);
threadRef.once('value', (snapshot) => {
const members = snapshot.child("members").val()
console.log("Members Val: " + members)
if(members == `${fromId}_${userId}` || members == `${userId}_${fromId}`){ //ISSUES WITH REPEATING
console.log("Both users are in the thread")
console.log("Key for thread: " + snapshot.key)
setThread(snapshot.key)
return functions.logger.log('Found membership and set thread');
} else {
const newThreadKey = db2.ref('threads').push().key;
const userThreadRef = db2.ref('users');
userThreadRef.child(fromId + '/threads/' + newThreadKey).set({
timestamp: DBTimestamp.TIMESTAMP
});
userThreadRef.child(userId + '/threads/' + newThreadKey).set({
timestamp: DBTimestamp.TIMESTAMP
});
const threadMembersRef = db2.ref('threadMembers');
threadMembersRef.child(newThreadKey + '/' + userId).set(true);
threadMembersRef.child(newThreadKey + '/' + fromId).set(true);
threadMembersRef.child(newThreadKey + '/members').set(userId + "_" + fromId);
setThread(newThreadKey)
return functions.logger.log('Created membership and set thread');
}
})
}
This is shown in the lab environment:
check the manual that corresponds to your MySQL server version for the right syntax to use near '0, intensity = 0 WHERE id = 1' at line 1.
I don't know why it keeps showing me this error, no matter what I do to try to "update my device"
below is the table:
below is the devices that can't be updated, other devices that I have can be updated, for these that can't it keep showing the same error, whether or not it has anything to do with intensity,
when edit device is click, will be redirected to the update page
but, when i click edit this device on this page, the error will show.
app.post("/backend-update", function (req, res) {
let sqlquery = "UPDATE myDevices SET status = '" + req.body.status + "', state = '" + req.body.state + "', temperature = " + req.body.temperature + ", volume = " + req.body.volume + ", speed = " + req.body.speed + ", intensity = " + req.body.intensity + " WHERE id = " + req.body.id;
const html = "<html><body><br><form action='/showDeviceStatus'><input type='submit' value='Back'></form></body></html>"
db.query(sqlquery, (err, update) => {
if (err) {
// return res.send("<html><p><b>ERROR!!!</b> Click Back to try again.</p></html>" + html);
return console.error(err.message)
}
else {
return res.send("<html><p>Your device have been successfully <b>updated</b>! Click Back to continue.</p></html>" + html);
}
});
});
I am facing same issue as mentioned in this question
Node.js TCP socket waits seconds before polling? (net.createServer)
I tried the answer marked as correct here but not able to understand how it is helpful. By adding that line "sock.write(data);" inside the "sock.on('data', function(data)" event, my "TELLER" goes into infinite loop.
Can anyone please help me understand what I am doing wrong?
Here is my code,
server.on('connection', function (sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.setNoDelay(true);
sock.on('error', function (err) {
console.log("ERROR : " + err.toString());
});
sock.on('data', function (data) {
console.log(moment().format("HH:mm:ss") + ' DATA : ' + sock.remoteAddress + ': ' + data);
data = data.toString().trim();
if (data.indexOf("MY_DATA_DELIMITER") > -1) {
console.log(moment().format("HH:mm:ss") + ' sending a command');
sock.write("MY_COMMAND");
////////// I get a response of this write after 5 seconds
}
});
sock.on('close', function (data) {
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
sock.on('end', function () {
console.log('ENDED : ' + sock.remoteAddress + ' ' + sock.remotePort);
});
});
In the data event, when I receive a string containing MY_DATA_DELIMITER, I send a COMMAND (just a string not more than 50 characters). The client, as a response to this COMMAND, sends a REPLY. I get this REPLY exactly after 5 seconds.
Turned out to be the way it is handled in CLIENT program. I do not have control over the CLIENT program hence it took much time to debug & figure out what is causing the delay.
The CLIENT expects a line ending with each message as the delimiter.
Though the example code I shared here uses line ending with message, I missed sending that in my actual code.
Hence the CLIENT kept waiting to detect end of message & this waiting took 5 seconds.
Now when I send the line ending character with each message, it is working without any delay.
Thank you for your time to look at it.
I have been looking for a way to execute a set of commands after the completion of a transaction I sent.
In short, I have been testing small Node.js scripts with Web3.js to post thermometer readings to a smart contract and after the transaction is mined to get back the last 5 values posted.
I haven't found a specific Web3 method to do so, so I coded a .on method in Node.js. I am now looking for more optimised ways of doing it and together to query if there is a way of doing it using any of the Web3 methods.
PS - I suppressed the smart contract and parts of the Node script to save space on the post.
Cheers,
// Transaction
web3.eth.getTransactionCount(account1, (err, txCount) => {
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(100000),
gasPrice: web3.utils.toHex(web3.utils.toWei('1', 'gwei')),
to: contractAddress,
data: contract.methods.postTemperature((Date.now() / 1000 | 0), temp).encodeABI()
}
const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTx = tx.serialize()
const raw = '0x' + serializedTx.toString('hex')
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
txH = txHash;
console.log('err:', err, 'txHash:', txHash)
}).on('receipt', receipt =>
contract.methods.seeTemperatures().call((err, result) => {
const tempDisplay = 'The last five temperature submissions were: \n' +
(result[1].slice(-10))[8].toString() + 'ºC at ' + timeConverter((result[1].slice(-10))[9]).toString() + '\n' +
(result[1].slice(-10))[6].toString() + 'ºC at ' + timeConverter((result[1].slice(-10))[7]).toString() + '\n' +
(result[1].slice(-10))[4].toString() + 'ºC at ' + timeConverter((result[1].slice(-10))[5]).toString() + '\n' +
(result[1].slice(-10))[2].toString() + 'ºC at ' + timeConverter((result[1].slice(-10))[3]).toString() + '\n' +
(result[1].slice(-10))[0].toString() + 'ºC at ' + timeConverter((result[1].slice(-10))[1]).toString();
console.log(tempDisplay)
contract.methods.seeBill().call((err, result) => {console.log('Your current bill is at ' + result + ' (currency)')})
})
)
})
Require the modules
var net = require("net");
Store the users and the connections number
var count = 0,
users = {};
Creates the server
var server = net.createServer(function (conn){
Stores the current nickname and set the utf8 encoding
var nickname;
conn.setEncoding('utf8');
Shows a message on the shell when you stablish a connection
conn.write(' > welcome to \033[92mnode-chat\033[39m!'
+ '\n > ' + count + ' other people are connected at this time.'
+ '\n > please write your name and press enter: ');
The number of connections++
count++;
When recives data it checks if there is a user in the storage with that name shows a message and return. Else shows a welcome message. Otherwise, if you input a message or any data (after have registered your nickname) shows it on the shell.
conn.on('data', function (data){
data = data.replace('\r\n', '');
if(!nickname) {
if(users[data]) {
conn.write('\033[93m > nickname already in use. Try again:\033[39m ');
return;
} else {
nickname = data;
users[nickname] = conn;
for(var i in users) {
users[i].write('\033[90m > ' + nickname + ' joined the room\033[39m\n');
}
}
} else {
for(var i in users) {
if(i != nickname) {
users[i].write('\033[96m > ' + nickname + ':\033[39m ' + data + '\n');
}
}
}
});
When you close or end the connection deletes your nickname from the storage, number of connections-- and shows a message.
conn.on('close', function(){
count--;
delete users[nickname];
conn.write('\033[90 > ' + nickname + ' left the room\033[39m\n');
});
});
Server on port 3000
server.listen(3000, function (){
console.log('\033[96m server listening on *:3000\033[39m');
});
I have a bug in my chat. I stablish two telnet connections using de shell. But when I close one the other one close two, and shows me a error message. What is wrong with my code?
You're trying to write to a closed connection, which will fail since writing to a closed Writable stream throws an error.
conn.on('close', function(){
count--;
delete users[nickname];
conn.write('\033[90 > ' + nickname + ' left the room\033[39m\n');
});
What you want is to broadcast the message to all other users either using Object.keys or a for-in loop.
conn.on('close', function() {
count --;
delete users[nickname];
Object.keys(users).forEach(function (user) {
users[user].write(nickname + ' left the room');
});
}
You also don't need a separate count variable to track connected users.
Object.keys(users).length;
But when I close one the other one close two, and shows me a error
message
It is because you're not listening for an error event and, by default, an EventEmitter throws an error if an error occurs and no error listener is attached.
conn.on('error', console.log);