一个简单的想法。 我想在计算机的范围内,显示的蓝牙设备在网络浏览器(使用通过蓝牙串行端口包的NodeJS蓝牙适配器)时调用了AJAX担任了。
我遇到的问题是,与下面的脚本,我不能continiously扫描设备,并在同一时间成为了网站。 你能解释一下在这个工作流程以及为什么/这将是一个很好的方向,以纠正这个问题?
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 8888,
btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
btSerial.inquire();
// Get the devices
var devices = [];
btSerial.on('found', function(address, name) {
if(typeof devices[address] === 'undefined'){
devices.push({'address': address,'name': name});
console.log("Device Found: "+address+" which is named: "+name);
}
});
// Keep searching
btSerial.on('finished', function() {
console.log("Done searching");
console.log(devices);
//btSerial.inquire();
});
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname,
filename = path.join(process.cwd(), uri);
if (uri == '/devices') {
response.writeHead(200, {"Content-Type": "application/json"});
response.write(JSON.stringify(devices));
response.end();
return;
}
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += 'public/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
解决的办法是要简单得多超过预期。
首先,我创建了一个打开插座,并在每个设备的发现提供了更新的结果到服务器服务蓝牙扫描仪服务(与运行下去)。 我设置了setTimeout函数为1秒(1000毫秒),否则结果将不会被传递到监听的服务器。
var port = 9838,
devices = {},
socket = require('socket.io-client')('http://localhost:'+port);
btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
var onFinishedFoundDevice = function(message){
// Add new device to object array
if(typeof message.address !== 'undefined' && typeof message.name !== 'undefined')
devices[message.address] = {'address': message.address,'name': message.name};
console.log("Sent new device", message);
};
var sendMessage = function(type, message, callback){
this.message = message;
socket.emit(type, message);
if(callback)
callback(message);
};
var findBluetooths = function () {
// Scan for BT devices in range
btSerial.on('found', function(address, name) {
if(typeof devices[address] === 'undefined'){
var message = {'address': address, 'name': name}; // prepare message
sendMessage('add-device', message, onFinishedFoundDevice); // actually send message to server
console.log("Device Found: "+address+" which is named: "+name);
}
});
// Keep searching
btSerial.on('finished', function() {
console.log("Received Finished... cont'd");
setTimeout(function(){btSerial.inquire();}, 1000);
});
// Scan for devices
console.log("Begin scanning");
btSerial.inquire();
}
// Do the magic
findBluetooths();
比我创建,使HTTP服务器的服务器服务(天长地久以及运行)以及用于socket.io事件侦听器。 这需要从蓝牙扫描仪以及index.html页面事件。
var app = require('http').createServer(handler),
io = require('socket.io')(app),
fs = require('fs'),
port = 9838,
devices = [];
app.listen(port);
function handler (req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('devices', devices);
socket.on('add-device', function(device) {
devices.push({'address': device.address,'name': device.name});
socket.broadcast.emit('device-added', device); // send device to browsers
console.log("Device Found: "+device.address+" which is named: "+device.name);
});
socket.on('get-devices', function(payload){
n });
});
最后,我创建了一个公用/ index.html文件显示扫描结果以及发出请求从服务器的详细信息。
<!DOCTYPE html>
<html>
<head>
<title>Bluetooth Scanner</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var port = 9838;
var hostname = window.location.hostname;
var socket = io(hostname+':'+port);
socket.on('welcome', function (message) {
console.log(message);
});
socket.on('device-added', function (device) {
$("#no-devices").hide();
$('<li>', {
html: "Device named "+device.name+" with MAC "+ device.address+" is online."
}).appendTo('#devices');
});
socket.on('devices', function(devices){
if(devices.length > 0) $("#no-devices").hide();
$.each(devices, function(key, device){
$('<li>', {
html: "Device named <b>"+device.name+"</b> with MAC <b>"+ device.address+"</b> is online."
}).appendTo('#devices');
});
});
</script>
</head>
<body>
<div>
<span id="no-devices">No devices yet...</span>
<ul id="devices"></ul>
</div>
</body>
</html>
谢谢大家的帮助。 它缺乏必要的功能,真正使它可用,但它是一个好的开始为我的项目
定期扫描在后台设备,使用setInterval
:
setInterval(btSerial.inquire, 10000);
这将调用btSerial.inquire
每10秒一次。 您需要为您的应用程序的最佳刷新间隔决定。 权衡的是,你可以用更短的时间间隔获得更多先进的最新设备的数据,但是,它为HTTP请求更短的时间你的服务器。