Skip to content

JavaScript SDK

Overview

The Urban Sky JavaScript SDK provides real-time access to balloon telemetry data. It connects to our WebSocket service and delivers location updates for balloons in your organization.

Prerequisites

Requirements:

  • Node.js 18+ - The SDK is designed for Node.js environments only

Note: The SDK is Node.js only and will not work in browsers. Real-time connectivity and HTTP requests are handled internally — no additional dependencies required.

Installation

Load the SDK using our CDN loader:

javascript
// Load the SDK dynamically
const response = await fetch('https://sdk.atmosys.com/runtime/js/current/loader.js')
const loaderCode = await response.text()
eval(loaderCode) // UrbanSkySDK is now available globally

Basic Usage

Initialization and Connection

javascript
// UrbanSkySDK is available globally after loading
// The init() method handles both initialization and connection
try {
  const sdk = await UrbanSkySDK.init({
    apiToken: 'your-api-token-here',
    // Most configuration options have sensible defaults and don't need to be set
  })
  console.log('Connected to Urban Sky!')
} catch (error) {
  console.error('Initialization failed:', error)
}

Listening for Balloon Updates

The SDK emits balloon:update events when balloon positions change:

javascript
sdk.on('balloon:update', update => {
  console.log(`Balloon ${update.balloonId} update:`)

  update.devices.forEach(device => {
    console.log(`  Device ${device.deviceId}:`)
    console.log(`    Location: ${device.lat}, ${device.lng}`)
    console.log(`    Timestamp: ${device.timestamp}`)
  })
})

API Reference

Constructor Options

typescript
interface SDKOptions {
  apiToken: string // Required: Your API token
  baseUrl?: string // Optional: Custom API URL (rarely needed)
}

Note: Most configuration options have sensible defaults. You typically only need to provide your API token.

Methods

connect(): Promise<void>

Establishes connection to the Urban Sky service.

javascript
await sdk.connect()

Throws:

  • AuthenticationError - Invalid API token
  • ConnectionError - Network or service issues

disconnect(): void

Closes the connection to Urban Sky.

javascript
sdk.disconnect()

on(event: string, callback: Function): void

Registers an event listener.

javascript
sdk.on('balloon:update', update => {
  // Handle balloon update
})

sdk.on('connected', () => {
  console.log('SDK connected')
})

sdk.on('disconnected', () => {
  console.log('SDK disconnected')
})

sdk.on('error', error => {
  console.error('SDK error:', error)
})

off(event: string, callback?: Function): void

Removes event listener(s).

javascript
// Remove specific listener
sdk.off('balloon:update', myHandler)

// Remove all listeners for event
sdk.off('balloon:update')

Events

balloon:update

Emitted when balloon position data is updated.

Payload:

typescript
interface BalloonUpdate {
  balloonId: string
  missionId: string
  devices: Array<{
    deviceId: string
    deviceType: string // e.g., "PLD" (Payload), "APX" (Apex), "BLS" (Ballaster)
    lat: number // Latitude
    lng: number // Longitude
    altitude?: number // Altitude in meters (when available)
    timestamp: string // ISO 8601 timestamp
  }>
}

connected

Emitted when successfully connected to Urban Sky.

disconnected

Emitted when disconnected from Urban Sky.

error

Emitted when an error occurs.

Payload:

typescript
interface SDKError {
  code: string
  message: string
  details?: any
}

Complete Example

javascript
// example.js - Node.js script
const fetch = require('node-fetch') // Ensure node-fetch is installed

async function main() {
  try {
    // Load the SDK
    const response = await fetch('https://sdk.atmosys.com/runtime/js/current/loader.js')
    const loaderCode = await response.text()
    eval(loaderCode)

    // Initialize and connect SDK
    const sdk = await UrbanSkySDK.init({
      apiToken: process.env.URBAN_SKY_API_TOKEN,
    })

    // Connection events
    sdk.on('connected', () => {
      console.log('✅ Connected to Urban Sky')
    })

    sdk.on('disconnected', () => {
      console.log('❌ Disconnected')
    })

    sdk.on('error', error => {
      console.error(`❌ Error: ${error.message}`)
    })

    // Balloon updates
    sdk.on('balloon:update', update => {
      console.log(`🎈 Balloon ${update.balloonId} update:`)
      console.log(`   Mission: ${update.missionId}`)

      update.devices.forEach(device => {
        console.log(`   📍 Device ${device.deviceId}: ${device.lat}, ${device.lng}`)
        console.log(`   🕒 Time: ${new Date(device.timestamp).toLocaleString()}`)
      })
    })

    // SDK is already connected via init()
    console.log('SDK initialized and connected!')

    // Keep the script running
    process.on('SIGINT', () => {
      console.log('Disconnecting...')
      sdk.disconnect()
      process.exit(0)
    })
  } catch (error) {
    console.error('Failed to initialize SDK:', error)
    process.exit(1)
  }
}

main()

Testing Your Implementation

You can test your SDK integration using our test endpoint:

javascript
// Send a test balloon update to verify your implementation
const testResponse = await fetch('https://api.ops.atmosys.com/sdk/test/balloon', {
  method: 'POST',
  headers: {
    'x-api-token': 'your-api-token',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({}),
})

if (testResponse.ok) {
  console.log('Test message sent - you should receive it via your SDK listener')
}

Dependency Installation Issues

Common Issues

"SDK is not supported in browser environments"

  • The JavaScript SDK is Node.js only. For browser applications, consider using our REST API directly or contact support for browser SDK options.

Error Handling

Common Error Codes

  • AUTH_INVALID_TOKEN - API token is invalid or expired
  • AUTH_INSUFFICIENT_PERMISSIONS - Token lacks SDK permissions
  • CONNECTION_FAILED - Network connection issues
  • SERVICE_UNAVAILABLE - Urban Sky service temporarily unavailable

Best Practices

javascript
const sdk = await UrbanSkySDK.init({
  apiToken: process.env.URBAN_SKY_API_TOKEN,
})

// Handle connection errors
sdk.on('error', error => {
  switch (error.code) {
    case 'AUTH_INVALID_TOKEN':
      console.error('Invalid API token - check your credentials')
      break
    case 'CONNECTION_FAILED':
      console.error('Connection failed - retrying...')
      // Implement retry logic
      break
    default:
      console.error('SDK error:', error)
  }
})

// Handle reconnection
sdk.on('disconnected', () => {
  console.log('Disconnected - will attempt to reconnect')
})

sdk.on('connected', () => {
  console.log('Connected/reconnected successfully')
})

// SDK is already connected via init()
// Error handling is done in the init() call above

Next Steps