-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCoap.js
80 lines (70 loc) · 1.86 KB
/
Coap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// This module holds the CoAP server and client, callable from any valid javascript module
'use strict';
// Server
module.exports.createServer = function(){
var coap = require('coap');
var server = coap.createServer();
server.on('request', function(req, res){
console.log("Request received");
var buf = req['_packet']['payload'];
buf = JSON.parse(JSON.stringify(buf));
var colour_r = buf['data'][0];
var colour_g = buf['data'][1];
var colour_b = buf['data'][2];
console.log("Colour R :: " + colour_r);
console.log("Colour G :: " + colour_g);
console.log("Colour B :: " + colour_b);
res.end("Response sent");
});
return {
server: server,
running: false,
isRuning: function(){
return this.running;
},
setRunning: function(status){
this.running = status;
},
run: function(f, interval){
var that = this;
this.server.listen(function(f, interval){
console.log("Listening @ :: " + 5683);
that.setRunning(true);
setTimeout(f, interval);
});
}
};
},
// Client request
module.exports.createRequest = function(params,value){
var coapOjb = require("coap");
var coapMsg = {
method: params.method,
//hostname: parsed_url.hostname,
//pathname: 'leds',
pathname: params.pathname,
confirmable: params.confirmable,
hostname: params.hostname
};
var coapVal=value;
var request = coapOjb.request(coapMsg);
var querystring = require('querystring');
var parsed = querystring.parse(coapVal);
var colour_r = parsed.r;
var colour_g = parsed.g;
var colour_b = parsed.b;
var buf = new Buffer(3);
buf.writeUInt8(parseInt(colour_r), 0);
buf.writeUInt8(parseInt(colour_g), 1);
buf.writeUInt8(parseInt(colour_b), 2);
request.write(buf);
request.on('response', function(res){
console.log("Response code :: " + res.code)
console.log("Response :: " + res)
});
return {
send: function(){
request.end();
}
}
}