Skip to content

Commit

Permalink
feat: update simple example with observations and failure
Browse files Browse the repository at this point in the history
Updates the simple.js example test to include handling observation
messages. Also updates to exit early and fail tests on failures.

Signed-off-by: Daniel Mangum <georgedanielmangum@gmail.com>
  • Loading branch information
hasheddan committed Jul 20, 2023
1 parent 19c795d commit f17a028
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions examples/simple.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
import { fail } from 'k6';
import { Client } from 'k6/x/coap';


export default function() {
// Create new client and connect.
let client;
try {
client = new Client("coap.golioth.io: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,36 @@ export default function() {
let json = JSON.parse(String.fromCharCode(...res.body));
console.log(json.sequenceNumber);
} catch (e) {
console.log(e);
fail(e);
}

// Observe.
try {
client.observe("/.rpc", 20, (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.
try {
client.close();
} catch (e) {
console.log(e);
fail(e);
}
}

0 comments on commit f17a028

Please sign in to comment.