In front end I have this code. Can you help me how...
# ask-ai
c
In front end I have this code. Can you help me how I can send and retrieve that code in backend Room.localparticipant.publishData(data, {reliable:true, topic: ‘tracking’});
t
Thanks for reaching out, Ashish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To send and retrieve data using
Room.localParticipant.publishData
in the backend with
reliable: true
and
topic: 'tracking'
, here are the steps: Sending Data: • Prepare the data you want to send. For example, you can encode a JSON object into a `Uint8Array`:
Copy code
const trackingData = JSON.stringify({
  userId: "user123",
  position: { x: 100, y: 200 },
  timestamp: Date.now()
});

const encoder = new TextEncoder();
const data = encoder.encode(trackingData);

await room.localParticipant.publishData(data, {
  reliable: true,
  topic: 'tracking'
});
Retrieving Data: • Set up a data message handler to listen for messages with the topic `'tracking'`:
Copy code
room.on('dataReceived', (payload, participant, topic) => {
  if (topic === 'tracking') {
    const decoder = new TextDecoder();
    const trackingData = JSON.parse(decoder.decode(payload));
    console.log('Received tracking data:', trackingData);
  }
});
Key Points: • Reliable Delivery: With
reliable: true
, packets are delivered in order with automatic retransmission in case of packet loss. • Topic Filtering: The
topic: 'tracking'
parameter allows you to differentiate this data from other types of messages. • Size Limits: In reliable delivery mode, each packet can be up to 15KiB in size. Let me know if you need further clarification or assistance!
c
The backend is in Python
t
Here’s a friendly guide on how to send data using
Room.localParticipant.publishData
in a Python backend with
reliable: true
and `topic: 'tracking'`: Sending Data:
Copy code
import json

# Let’s get your tracking data ready
tracking_data = {
    "userId": "user123",
    "position": {"x": 100, "y": 200},
    "timestamp": time.time()
}

# Now, publish that data
await room.local_participant.publish_data(
    payload=json.dumps(tracking_data).encode(),  # Convert it to bytes
    reliable=True,  # This makes sure your data gets there reliably
    topic="tracking"  # Tag it with 'tracking' so it’s easy to identify
)
Key Points to Keep in Mind: • Reliable Delivery: Setting
reliable: true
means your packets arrive in order, and if anything gets lost, they’ll be sent again automatically. • Topic Filtering: Using
topic: 'tracking'
helps you separate this data from other messages, keeping things organized. • Size Limits: When using reliable delivery, each packet can be up to 15KiB in size. Retrieving Data: About receiving data in Python, the docs don’t provide a specific method just yet. Usually, you’d set up a listener or callback to catch incoming messages. If you’d like, I’m more than happy to connect you with a specialist who can help you set this up! Sources: livekit-rtc/livekit/rtc/_proto/room_pb2.pyi | Data packets | LiveKit Docs
c
The thing is I’m publishing on jsx and I want to fetch that data on python backend agents
t
Hey there! If you want to fetch data published using
Room.localParticipant.publishData
in JavaScript and handle it on a Python backend, here’s a simple way to do it: JavaScript Side (Publishing Data):
Copy code
const strData = JSON.stringify({some: "data"});
const encoder = new TextEncoder();

// Convert the string to a Uint8Array
const data = encoder.encode(strData);

// Publish reliable data to the entire room
room.localParticipant.publishData(data, {reliable: true});

// Or publish to specific participants
room.localParticipant.publishData(data, {
  reliable: true, 
  destinationIdentities: ['python-backend-identity'],
  topic: 'custom-topic'
});
Python Backend (Receiving Data):
Copy code
import asyncio
from livekit import rtc

async def main():
    room = rtc.Room()
    
    @room.on("data_received")
    def on_data_received(data: rtc.DataPacket):
        # Here’s where you get the raw bytes and info about who sent it
        message = data.data.decode('utf-8')
        sender_identity = data.participant.identity
        
        print(f"Received data from {sender_identity}: {message}")
        
        # Let’s try to parse that data and do something with it
        try:
            parsed_data = json.loads(message)
            # Handle your data here
        except json.JSONDecodeError:
            print("Received non-JSON data")
    
    # Connect to your room
    token = "your-access-token"
    await room.connect("your-livekit-url", token)
    
    # Keep things running
    await asyncio.sleep(3600)  # or your app’s logic

if __name__ == "__main__":
    asyncio.run(main())
Some things to keep in mind: • Data Format: The
publishData
method expects a
Uint8Array
in JavaScript, so make sure to encode your data properly. • DataPacket Properties: On the Python side, the
DataPacket
object includes: ◦ `data`: The raw bytes sent over from JavaScript ◦ `participant`: Info about who sent the data ◦ `topic`: The topic you specified when publishing (if any) • Selective Delivery: If you want to send data only to certain participants, use
destinationIdentities
in your JavaScript code. Otherwise, leaving it empty will broadcast to everyone in the room. And that’s it! This setup should help your Python backend receive and work with data sent from your JavaScript frontend. If you have any questions or need a hand, just let me know! Sources: Data messages | LiveKit Docs | livekit-rtc/livekit/rtc/_proto/room_pb2.pyi