Skip to content

Commit

Permalink
feat: update simple example with observations
Browse files Browse the repository at this point in the history
Updates simple example to demonstrate observations with OTA and RPC.

Signed-off-by: Daniel Mangum <georgedanielmangum@gmail.com>
  • Loading branch information
hasheddan committed Jul 20, 2023
1 parent 343bc4b commit 7408faa
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ endif
# Targets

build: setup
@xk6 build --with github.com/golioth/xk6-coap=.
@xk6 build --with github.com/golioth/xk6-coap=. --with github.com/grafana/xk6-timers
60 changes: 52 additions & 8 deletions examples/simple.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
import { fail } from 'k6';
import { setTimeout } from "k6/x/timers"
import { Client } from 'k6/x/coap';


export default function() {
// Create new client and connect.
let client;
try {
client = new Client("coap.golioth.io:5684");
client = new Client("coap.golioth.dev:5684");
} catch (e) {
console.log(e);
fail(e);
}

// Verify connection.
try {
let res = client.get("/hello", 10);
console.log(String.fromCharCode(...res.body));
} catch (e) {
console.log(e);
fail(e);
}

// Send data.
try {
let res = client.post("/.s", "application/json", '{"hello": "world"}', 10);
console.log(res.code);
} catch (e) {
console.log(e);
fail(e);
}

// Get JSON data.
Expand All @@ -31,13 +34,54 @@ export default function() {
let json = JSON.parse(String.fromCharCode(...res.body));
console.log(json.sequenceNumber);
} catch (e) {
console.log(e);
fail(e);
}

// Start RPC observation.
try {
client.observe("/.rpc", 15, (req) => {
let json;
try {
json = JSON.parse(String.fromCharCode(...req.body));
} catch (e) {
// First message is acknowledgement of
// observation.
console.log(e);
return;
}
try {
console.log(json);
client.post("/.rpc/status", "application/json", '{"id": "' + json.id + '", "statusCode": 0, "detail":"ack"}', 10);
} catch (e) {
fail(e);
}
});
} catch (e) {
fail(e);
}

// Close connection.
// Start OTA observation.
try {
client.close();
client.observe("/.u/desired", 15, (req) => {
let json;
try {
json = JSON.parse(String.fromCharCode(...req.body));
} catch (e) {
return;
}
console.log(json);
});
} catch (e) {
console.log(e);
fail(e);
}

// Wait for observations to complete.
setTimeout(() => {
// Close connection.
try {
client.close();
} catch (e) {
fail(e);
}
}, 20000)
}

0 comments on commit 7408faa

Please sign in to comment.