Skip to content

Commit 464a9f0

Browse files
Create DataChannel by default
Demonstrate how to send and receive DataChannel messages
1 parent 87f96f7 commit 464a9f0

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

CMakeLists.txt

+4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ if(NOT DEFINED ENV{OPENAI_API_KEY})
1313
message(FATAL_ERROR "Env variable OPENAI_API_KEY must be set")
1414
endif()
1515

16+
if(DEFINED ENV{LOG_DATACHANNEL_MESSAGES})
17+
add_compile_definitions(LOG_DATACHANNEL_MESSAGES="1")
18+
endif()
19+
1620
add_compile_definitions(OPENAI_API_KEY="$ENV{OPENAI_API_KEY}")
1721
add_compile_definitions(OPENAI_REALTIMEAPI="https://api.openai.com/v1/realtime?model=gpt-4o-mini-realtime-preview-2024-12-17")
1822

deps/libpeer

Submodule libpeer updated 1 file

src/webrtc.cpp

+27-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
#include "main.h"
1111

1212
#define TICK_INTERVAL 15
13+
#define GREETING \
14+
"{\"type\": \"response.create\", \"response\": {\"modalities\": " \
15+
"[\"audio\", \"text\"], \"instructions\": \"Say 'How can I help?.'\"}}"
1316

1417
PeerConnection *peer_connection = NULL;
1518

@@ -25,6 +28,25 @@ void oai_send_audio_task(void *user_data) {
2528
}
2629
#endif
2730

31+
static void oai_ondatachannel_onmessage_task(char *msg, size_t len,
32+
void *userdata, uint16_t sid) {
33+
#ifdef LOG_DATACHANNEL_MESSAGES
34+
ESP_LOGI(LOG_TAG, "DataChannel Message: %s", msg);
35+
#endif
36+
}
37+
38+
static void oai_ondatachannel_onopen_task(void *userdata) {
39+
if (peer_connection_create_datachannel(peer_connection, DATA_CHANNEL_RELIABLE,
40+
0, 0, (char *)"oai-events",
41+
(char *)"") != -1) {
42+
ESP_LOGI(LOG_TAG, "DataChannel created");
43+
peer_connection_datachannel_send(peer_connection, (char *)GREETING,
44+
strlen(GREETING));
45+
} else {
46+
ESP_LOGE(LOG_TAG, "Failed to create DataChannel");
47+
}
48+
}
49+
2850
static void oai_onconnectionstatechange_task(PeerConnectionState state,
2951
void *user_data) {
3052
ESP_LOGI(LOG_TAG, "PeerConnectionState: %s",
@@ -56,7 +78,7 @@ void oai_webrtc() {
5678
.ice_servers = {},
5779
.audio_codec = CODEC_OPUS,
5880
.video_codec = CODEC_NONE,
59-
.datachannel = DATA_CHANNEL_NONE,
81+
.datachannel = DATA_CHANNEL_STRING,
6082
.onaudiotrack = [](uint8_t *data, size_t size, void *userdata) -> void {
6183
#ifndef LINUX_BUILD
6284
oai_audio_decode(data, size);
@@ -78,6 +100,10 @@ void oai_webrtc() {
78100
peer_connection_oniceconnectionstatechange(peer_connection,
79101
oai_onconnectionstatechange_task);
80102
peer_connection_onicecandidate(peer_connection, oai_on_icecandidate_task);
103+
peer_connection_ondatachannel(peer_connection,
104+
oai_ondatachannel_onmessage_task,
105+
oai_ondatachannel_onopen_task, NULL);
106+
81107
peer_connection_create_offer(peer_connection);
82108

83109
while (1) {

0 commit comments

Comments
 (0)