Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
B
baby-monitoring-spring-backend
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
R24-145
baby-monitoring-spring-backend
Commits
8ef7416a
Commit
8ef7416a
authored
Aug 27, 2024
by
Ishankha K.C
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
update realtime websocket connectivity
parent
20e860a0
Changes
6
Hide whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
118 additions
and
43 deletions
+118
-43
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SecurityConfig.java
...rprises/babycarebackendservice/config/SecurityConfig.java
+1
-0
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketClient.java
...prises/babycarebackendservice/config/WebSocketClient.java
+42
-4
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketConfig.java
...prises/babycarebackendservice/config/WebSocketConfig.java
+23
-39
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/TestController.java
...terprises/babycarebackendservice/rest/TestController.java
+52
-0
src/main/resources/music.mp3
src/main/resources/music.mp3
+0
-0
src/main/resources/music.wav
src/main/resources/music.wav
+0
-0
No files found.
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/SecurityConfig.java
View file @
8ef7416a
...
...
@@ -47,6 +47,7 @@ public class SecurityConfig {
"/webjars/**"
,
"/swagger-ui.html"
,
"/emotional/video-process"
,
"/test/**"
};
@Bean
...
...
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketClient.java
View file @
8ef7416a
...
...
@@ -2,25 +2,38 @@ package com.kaluwa.enterprises.babycarebackendservice.config;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.kaluwa.enterprises.babycarebackendservice.socketHandlers.EmotionPrediction
;
import
org.springframework.scheduling.annotation.Scheduled
;
import
org.springframework.web.socket.BinaryMessage
;
import
org.springframework.web.socket.TextMessage
;
import
org.springframework.web.socket.WebSocketSession
;
import
org.springframework.web.socket.client.standard.StandardWebSocketClient
;
import
org.springframework.web.socket.handler.TextWebSocketHandler
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
config
.
WebSocketConfig
.
SendVideoHandler
.
sendTextMessageToClient
;
import
java.util.concurrent.Executors
;
import
java.util.concurrent.ScheduledExecutorService
;
import
java.util.concurrent.TimeUnit
;
import
static
com
.
kaluwa
.
enterprises
.
babycarebackendservice
.
config
.
WebSocketConfig
.
VideoFrameHandler
.
sendTextMessageToClient
;
public
class
WebSocketClient
{
private
WebSocketSession
session
;
private
static
final
String
WEBSOCKET_URL
=
"ws://localhost:8000/ws/emotion"
;
private
static
final
ScheduledExecutorService
scheduler
=
Executors
.
newSingleThreadScheduledExecutor
();
public
WebSocketClient
()
{
connectToWebSocket
();
}
p
ublic
WebSocketClien
t
()
{
p
rivate
void
connectToWebSocke
t
()
{
try
{
this
.
session
=
new
StandardWebSocketClient
()
.
doHandshake
(
new
MyWebSocketHandler
(
),
"ws://localhost:8000/ws/emotion"
)
.
doHandshake
(
new
MyWebSocketHandler
(
this
),
WEBSOCKET_URL
)
.
get
();
System
.
out
.
println
(
"Connected to WebSocket!"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
System
.
out
.
println
(
"Failed to connect to WebSocket, scheduling reconnection..."
);
scheduleReconnection
();
}
}
...
...
@@ -32,10 +45,29 @@ public class WebSocketClient {
}
}
private
void
scheduleReconnection
()
{
scheduler
.
schedule
(
this
::
connectToWebSocket
,
2
,
TimeUnit
.
MINUTES
);
}
@Scheduled
(
fixedDelay
=
120000
)
// Check every 5 minutes
private
void
checkConnection
()
{
if
(
session
==
null
||
!
session
.
isOpen
())
{
System
.
out
.
println
(
"WebSocket connection is closed. Reconnecting..."
);
connectToWebSocket
();
}
}
static
ObjectMapper
objectMapper
=
new
ObjectMapper
();
public
static
EmotionPrediction
[]
predictions
;
static
class
MyWebSocketHandler
extends
TextWebSocketHandler
{
private
final
WebSocketClient
webSocketClient
;
public
MyWebSocketHandler
(
WebSocketClient
webSocketClient
)
{
this
.
webSocketClient
=
webSocketClient
;
}
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
throws
Exception
{
// This method will be called when the server sends a text message
...
...
@@ -48,5 +80,11 @@ public class WebSocketClient {
sendTextMessageToClient
(
lastPrediction
);
}
}
@Override
public
void
afterConnectionClosed
(
WebSocketSession
session
,
org
.
springframework
.
web
.
socket
.
CloseStatus
status
)
{
System
.
out
.
println
(
"WebSocket connection closed. Status: "
+
status
);
webSocketClient
.
scheduleReconnection
();
}
}
}
src/main/java/com/kaluwa/enterprises/babycarebackendservice/config/WebSocketConfig.java
View file @
8ef7416a
...
...
@@ -28,7 +28,6 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Override
public
void
registerWebSocketHandlers
(
WebSocketHandlerRegistry
registry
)
{
registry
.
addHandler
(
new
VideoFrameHandler
(),
"/emotional/video-process"
).
setAllowedOrigins
(
"*"
);
registry
.
addHandler
(
new
SendVideoHandler
(),
"/emotional/video-send"
).
setAllowedOrigins
(
"*"
);
}
@Bean
...
...
@@ -39,34 +38,11 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Component
class
VideoFrameHandler
extends
BinaryWebSocketHandler
{
WebSocketClient
webSocketClient
=
customWebSocketClient
();
@Override
protected
void
handleBinaryMessage
(
WebSocketSession
session
,
BinaryMessage
message
)
throws
Exception
{
byte
[]
binaryData
=
message
.
getPayload
().
array
();
// Process the binary data representing the video frame
// log.info("Received binary data from client: {}", binaryData);
// Here you can process the binary data as needed, such as saving it to a file, performing image processing, etc.
webSocketClient
.
sendBytesToWebSocket
(
binaryData
);
SendVideoHandler
.
sendBinaryMessageToClient
(
binaryData
);
}
@Override
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
{
super
.
handleTextMessage
(
session
,
message
);
}
}
@Component
class
SendVideoHandler
extends
BinaryWebSocketHandler
{
WebSocketClient
webSocketClient
=
customWebSocketClient
();
private
static
StandardWebSocketSession
session
;
private
static
WebSocketSession
currentSession
;
@Override
public
void
afterConnectionEstablished
(
WebSocketSession
session
)
throws
Exception
{
SendVideoHandler
.
session
=
(
StandardWebSocketSession
)
session
;
currentSession
=
session
;
// Store the current session
log
.
info
(
"Connection established with client: {}"
,
session
);
super
.
afterConnectionEstablished
(
session
);
}
...
...
@@ -74,13 +50,21 @@ public class WebSocketConfig implements WebSocketConfigurer {
@Override
protected
void
handleBinaryMessage
(
WebSocketSession
session
,
BinaryMessage
message
)
throws
Exception
{
byte
[]
binaryData
=
message
.
getPayload
().
array
();
// Process the binary data as needed
// Send binary data back to the client
sendBinaryMessageToClient
(
binaryData
);
// Optionally, send a text message
EmotionPrediction
emotionPrediction
=
new
EmotionPrediction
();
// Example object
sendTextMessageToClient
(
emotionPrediction
);
}
@Override
public
void
afterConnectionClosed
(
WebSocketSession
session
,
CloseStatus
status
)
throws
Exception
{
// Handle session closure here
// For example, cleanup resources or attempt to reconnect
SendVideoHandler
.
session
=
null
;
// Reset session variable
if
(
currentSession
==
session
)
{
currentSession
=
null
;
// Reset session variable
}
log
.
info
(
"Connection closed with client: {}"
,
session
);
super
.
afterConnectionClosed
(
session
,
status
);
}
...
...
@@ -89,37 +73,37 @@ public class WebSocketConfig implements WebSocketConfigurer {
protected
void
handleTextMessage
(
WebSocketSession
session
,
TextMessage
message
)
{
super
.
handleTextMessage
(
session
,
message
);
try
{
System
.
out
.
println
(
"Received text message from client: "
+
message
.
getPayload
());
System
.
out
.
println
(
"Received text message from client: "
+
message
.
getPayload
());
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
// Method to send a message back to the client
public
static
void
sendBinaryMessageToClient
(
byte
[]
bytes
)
{
// Method to send a
binary
message back to the client
public
void
sendBinaryMessageToClient
(
byte
[]
bytes
)
{
try
{
if
(
session
!=
null
&&
s
ession
.
isOpen
())
{
s
ession
.
sendMessage
(
new
BinaryMessage
(
bytes
));
System
.
out
.
println
(
"Sent
message to client: "
+
bytes
.
length
);
if
(
currentSession
!=
null
&&
currentS
ession
.
isOpen
())
{
currentS
ession
.
sendMessage
(
new
BinaryMessage
(
bytes
));
System
.
out
.
println
(
"Sent
binary message to client: "
+
bytes
.
length
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
// Method to send a text message back to the client
public
static
void
sendTextMessageToClient
(
EmotionPrediction
emotionPrediction
)
{
try
{
if
(
session
!=
null
&&
s
ession
.
isOpen
())
{
if
(
currentSession
!=
null
&&
currentS
ession
.
isOpen
())
{
ObjectMapper
objectMapper
=
new
ObjectMapper
();
String
json
=
objectMapper
.
writeValueAsString
(
emotionPrediction
);
s
ession
.
sendMessage
(
new
TextMessage
(
json
));
System
.
out
.
println
(
"Sent message to client: "
+
json
);
currentS
ession
.
sendMessage
(
new
TextMessage
(
json
));
System
.
out
.
println
(
"Sent
text
message to client: "
+
json
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
}
}
\ No newline at end of file
src/main/java/com/kaluwa/enterprises/babycarebackendservice/rest/TestController.java
View file @
8ef7416a
package
com.kaluwa.enterprises.babycarebackendservice.rest
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.core.io.ClassPathResource
;
import
org.springframework.core.io.Resource
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RestController
;
...
...
@@ -18,4 +22,52 @@ public class TestController {
return
new
ResponseEntity
<>(
"Test OK!"
,
HttpStatus
.
OK
);
}
String
lightStatus
=
"OFF"
;
@GetMapping
(
"/light/on"
)
public
ResponseEntity
<
String
>
lightOn
()
{
log
.
info
(
"Inside lightOn controller"
);
lightStatus
=
"ON"
;
return
new
ResponseEntity
<>(
"Light is ON"
,
HttpStatus
.
OK
);
}
@GetMapping
(
"/light/off"
)
public
ResponseEntity
<
String
>
lightOff
()
{
log
.
info
(
"Inside lightOff controller"
);
lightStatus
=
"OFF"
;
return
new
ResponseEntity
<>(
"Light is OFF"
,
HttpStatus
.
OK
);
}
@GetMapping
(
"/light/status"
)
public
ResponseEntity
<
String
>
lightStatus
()
{
log
.
info
(
"Inside lightStatus controller"
);
return
new
ResponseEntity
<>(
lightStatus
,
HttpStatus
.
OK
);
}
@GetMapping
(
"/music/play"
)
public
ResponseEntity
<
Resource
>
getMusicFile
()
{
log
.
info
(
"Inside getMusicFile controller"
);
try
{
// Load the music.wav file from the resources folder
ClassPathResource
resource
=
new
ClassPathResource
(
"music.wav"
);
// Check if the resource exists
if
(!
resource
.
exists
())
{
return
ResponseEntity
.
notFound
().
build
();
}
// Set the headers to specify the content type
HttpHeaders
headers
=
new
HttpHeaders
();
headers
.
add
(
HttpHeaders
.
CONTENT_TYPE
,
"audio/wav"
);
// Return the file as the response
return
new
ResponseEntity
<>(
resource
,
headers
,
HttpStatus
.
OK
);
}
catch
(
Exception
e
)
{
log
.
error
(
"Error serving music file"
,
e
);
return
ResponseEntity
.
status
(
HttpStatus
.
INTERNAL_SERVER_ERROR
).
build
();
}
}
}
src/main/resources/music.mp3
0 → 100644
View file @
8ef7416a
File added
src/main/resources/music.wav
0 → 100644
View file @
8ef7416a
File added
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment