auths
objectreturn
or this.key = 'value'
, pass input data to your code viaparams
, and maintain state across executions with$checkpoint.async
(event, steps, params) => {
}
const axios = require('axios');
const { headers, body } = event;
const { authorization } = params;
if (authorization && authorization !== headers.authorization) {
await $respond({
immediate: true,
status: 401,
body: 'Missing or incorrect Authorization header in request'
});
$end('Missing or incorrect Authorization header in request');
}
console.log('Got body', body);
// See https://www.thethingsnetwork.org/docs/applications/http/
// When using a Decoder in the application's Payload Formats in
// TTN Console, then body.payload_fields will be available too.
const bytes = Buffer.from(body.payload_raw, 'base64');
// Assuming a Kickstarter The Things Node, with the default sketch;
// see https://www.thethingsnetwork.org/docs/devices/node/
const events = {
1: 'setup',
2: 'interval',
3: 'motion',
4: 'button'
};
const decoded = {
event: events[body.port] || 'unknown',
battery: (bytes[0] << 8 | bytes[1]) / 1000,
light: bytes[2] << 8 | bytes[3],
// Sign-extend to 32 bits to support negative values, by shifting
// 24 bits to the left (16 too far), followed by a sign-propagating
// right shift of 16 bits, to effectively shift 8 bits:
temperature: (bytes[4] << 24 >> 16 | bytes[5]) / 100
};
console.log('Decoded', decoded);
const rgb = {
setup: 0b101, // magenta
interval: 0b100, // red
motion: null,
button: 0b010 // green
}[decoded.event];
if (!rgb) {
$end('No downlink needed');
}
const downlink = {
dev_id: body.dev_id,
port: 1,
confirmed: false,
schedule: 'replace',
payload_raw: Buffer.from([rgb]).toString('base64')
};
const options = {
url: body.downlink_url,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: downlink
};
console.log('Will POST', options);
// As we want to schedule the downlink as soon as possible, we cannot use
// $send.http (which would send fully asynchronously, after the workflow
// runs, but would not count against workflow quota)
const response = await axios(options);
const result = `Sent downlink to ${options.url}, ${response.status} ${response.statusText}`;
console.log(result);
// The HTTP Integration doesn't really care about the response
await $respond({
immediate: true,
status: 202,
body: result
});