Created
June 5, 2014 15:31
-
-
Save Pindar/4886e00496977f38d6c4 to your computer and use it in GitHub Desktop.
CoAP Observer Try
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/* | |
HOW TO: | |
1) install required tools | |
- npm install coap --save | |
- npm install coap-cli -g | |
2) run the server: chmod +x coap-server.js && ./coap-server.js | |
3) observe a resource | |
- coap get -o coap://localhost/message | |
4) publish a message | |
- echo -n 'hello world asdf' | coap put coap://localhost/message | |
*/ | |
/* | |
TO-DO | |
- proper client session handling: clean up closed observer connections etc. | |
*/ | |
const coap = require('coap'), | |
server = coap.createServer(), | |
requests = []; | |
function storeRequestConnection(req, res) { | |
requests.push({url: req.url, connection: res, writeClb: res.write, end: res.end}); | |
} | |
function isObserveRequest(req) { | |
return req.headers.Observe === 0; | |
} | |
server.on('request', function(req, res) { | |
if (isObserveRequest(req)) { | |
storeRequestConnection(req, res); | |
} | |
if (req.headers.Observe !== 0) { | |
console.log('no observe'); | |
res.end(''); | |
} | |
requests.filter(function(item) { | |
return item.url === req.url; | |
}).map(function (response) { | |
response.writeClb.call(response.connection, 'llt ' + req.payload.toString() + 'length ' + requests.length); | |
}); | |
if (req.payload.toString() === 'quit') { | |
requests.map(function (response) { | |
response.end.call(response.connection, 'quit'); | |
}); | |
res.end(''); | |
process.exit(0); | |
} | |
}); | |
// the default CoAP port is 5683 | |
server.listen(function () {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment