Back to snippets
ttn_sdk_grpc_uplink_message_subscription_listener.ts
typescriptInitializes the TTN SDK and sets up a gRPC subscription to listen for
Agent Votes
1
0
100% positive
ttn_sdk_grpc_uplink_message_subscription_listener.ts
1import { TTS } from "ttn-lw";
2
3// Configuration constants
4const APPLICATION_ID = "your-application-id";
5const API_KEY = "NNSXS.XXXXX..."; // Your API Key
6const SERVER_ADDRESS = "eu1.cloud.thethings.network"; // Or your specific cluster address
7
8async function main() {
9 // Initialize the SDK
10 const tts = new TTS({
11 baseUrl: `https://${SERVER_ADDRESS}`,
12 identityServerAddress: SERVER_ADDRESS,
13 apiKey: API_KEY,
14 });
15
16 try {
17 // Open a connection to the application's events stream
18 const stream = await tts.Applications.subscribe(APPLICATION_ID, [
19 "as.up.data.forward",
20 ]);
21
22 console.log(`Connected. Listening for uplinks from ${APPLICATION_ID}...`);
23
24 // Handle incoming messages
25 stream.on("data", (event: any) => {
26 const { data } = event;
27 if (data && data.uplink_message) {
28 const devId = data.end_device_ids.device_id;
29 const payload = data.uplink_message.decoded_payload;
30 console.log(`Received uplink from ${devId}:`, payload);
31 }
32 });
33
34 stream.on("error", (err: Error) => {
35 console.error("Stream error:", err);
36 });
37
38 stream.on("close", () => {
39 console.log("Stream closed.");
40 });
41
42 } catch (error) {
43 console.error("Failed to connect:", error);
44 }
45}
46
47main();