Skip to content

Commit

Permalink
WebSocket transport example
Browse files Browse the repository at this point in the history
  • Loading branch information
sarxos committed Feb 15, 2015
1 parent 646f426 commit 6a8a2f6
Show file tree
Hide file tree
Showing 15 changed files with 396 additions and 4 deletions.
1 change: 0 additions & 1 deletion webcam-capture-drivers/driver-ipcam/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- uncomment to debug wire log from httpclient -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.ds.ipcam.IpCamDriver;
import com.github.sarxos.webcam.ds.ipcam.IpCamStorage;
import com.github.sarxos.webcam.log.WebcamLogConfigurator;


/**
Expand Down Expand Up @@ -41,8 +40,6 @@ public class JpegDasdingStudioExample {

public static void main(String[] args) throws MalformedURLException {

WebcamLogConfigurator.configure("src/examples/resources/cameras.xml");

JFrame f = new JFrame("Dasding Studio Live IP Cameras Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 3, 1, 1));
Expand Down
1 change: 1 addition & 0 deletions webcam-capture-examples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<module>webcam-capture-swt-awt</module>
<module>webcam-capture-video-recording</module>
<module>webcam-capture-onejar</module>
<module>webcam-capture-websockets</module>
</modules>

<build>
Expand Down
19 changes: 19 additions & 0 deletions webcam-capture-examples/webcam-capture-websockets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Webcam WebSockets Example

This example demonstrates how images feed can be transported over the WebSocket.

## What Is This


## Screenshoots


## License

Copyright (C) 2015 Bartosz Firyn

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 changes: 40 additions & 0 deletions webcam-capture-examples/webcam-capture-websockets/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.github.sarxos</groupId>
<artifactId>webcam-capture-examples</artifactId>
<version>0.3.11-SNAPSHOT</version>
</parent>

<artifactId>webcam-capture-example-websockets</artifactId>
<packaging>jar</packaging>

<name>Webcam Capture - WebSockets Example</name>
<description>Example demonstrating how to transmit images over WebSockets from webcam server to the web application frontend</description>

<dependencies>
<dependency>
<groupId>com.github.sarxos</groupId>
<artifactId>webcam-capture-driver-ipcam</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all</artifactId>
<version>9.2.7.v20150116</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
</dependencies>

</project>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ws.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class='wrapper'>
<h1>webcam websocket transport example</h1>
<div id="webcams"></div>
</div>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

.wrapper {
margin-left: auto;
margin-right: auto;
width: 1084px;
text-align: center;
}

img {
margin-left: 8px;
margin-bottom: 8px;
width: 348px;
height: 198px;
box-shadow: 0 0 16px #444;
border: 1px solid #fff;
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
$(document).ready(function() {

var ws = new WebSocket("ws://127.0.0.1:8123/");

ws.onopen = function(e) {
if (typeof console !== 'undefined') {
console.info('WS open');
}
};

ws.onmessage = function (e) {

var data = JSON.parse(e.data),
type = data.type,
i = 0,
$webcams = $('#webcams'),
$img = null;

if (typeof console !== 'undefined') {
console.info('WS message', type);
}

if (type === 'list') {
for (i = 0; i < data.webcams.length; i += 1) {
$img = $("<img></img>")
.attr("src", "webcam-capture-logo-small.jpg")
.attr("alt", data.webcams[i])
.attr("name", data.webcams[i]);
$webcams.append($img)
}
} else if (type === 'image') {
$("img[name='" + data.webcam + "']")
.attr("src", "data:image/jpeg;base64," + data.image)
.trigger("change");
}
};

ws.onclose = function() {
if (typeof console !== 'undefined') {
console.info('WS close');
}
};

ws.onerror = function(err) {
if (typeof console !== 'undefined') {
console.info('WS error');
}
};
});

Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamEvent;
import com.github.sarxos.webcam.WebcamListener;
import com.github.sarxos.webcam.WebcamUpdater;


public class WebcamCache implements WebcamUpdater.DelayCalculator, WebcamListener {

/**
* How often images are updated on Dasding server.
*/
private static final long DELAY = 10000;

/**
* Webcams list.
*/
private Map<String, Webcam> webcams = new HashMap<String, Webcam>();

/**
* WebSocket handlers.
*/
private List<WebcamWebSocketHandler> handlers = new ArrayList<WebcamWebSocketHandler>();

/**
* Static instance to make access easier.
*/
private static final WebcamCache CACHE = new WebcamCache();

public WebcamCache() {
for (Webcam webcam : Webcam.getWebcams()) {
webcam.addWebcamListener(this);
webcam.open(true, this);
webcams.put(webcam.getName(), webcam);
}
}

@Override
public long calculateDelay(long snapshotDuration, double deviceFps) {
return Math.max(DELAY - snapshotDuration, 0);
}

public static BufferedImage getImage(String name) {
return CACHE.webcams.get(name).getImage();
}

public static List<String> getWebcamNames() {
return new ArrayList<String>(CACHE.webcams.keySet());
}

@Override
public void webcamOpen(WebcamEvent we) {
// do nothing
}

@Override
public void webcamClosed(WebcamEvent we) {
// do nothing
}

@Override
public void webcamDisposed(WebcamEvent we) {
// do nothing
}

@Override
public void webcamImageObtained(WebcamEvent we) {
for (WebcamWebSocketHandler handler : handlers) {
handler.newImage(we.getSource(), we.getImage());
}
}

public static void subscribe(WebcamWebSocketHandler handler) {
CACHE.handlers.add(handler);
}

public static void unsubscribe(WebcamWebSocketHandler handler) {
CACHE.handlers.remove(handler);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sarxos.webcam.Webcam;


@WebSocket
public class WebcamWebSocketHandler {

private static final Logger LOG = LoggerFactory.getLogger(WebcamWebSocketHandler.class);

private static final ObjectMapper MAPPER = new ObjectMapper();

private Session session;

private void teardown() {
try {
session.close();
session = null;
} finally {
WebcamCache.unsubscribe(this);
}
}

private void setup(Session session) {

this.session = session;

Map<String, Object> message = new HashMap<String, Object>();
message.put("type", "list");
message.put("webcams", WebcamCache.getWebcamNames());

send(message);

WebcamCache.subscribe(this);
}

@OnWebSocketClose
public void onClose(int status, String reason) {
LOG.info("WebSocket closed, status = {}, reason = {}", status, reason);
teardown();
}

@OnWebSocketError
public void onError(Throwable t) {
LOG.error("WebSocket error", t);
teardown();
}

@OnWebSocketConnect
public void onConnect(Session session) {
LOG.info("WebSocket connect, from = {}", session.getRemoteAddress().getAddress());
setup(session);
}

@OnWebSocketMessage
public void onMessage(String message) {
LOG.info("WebSocket message, text = {}", message);
}

public void newImage(Webcam webcam, BufferedImage image) {

LOG.info("New image from {}", webcam);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, "JPG", baos);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}

String base64 = null;
try {
base64 = new String(Base64.getEncoder().encode(baos.toByteArray()), "UTF8");
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage(), e);
}

Map<String, Object> message = new HashMap<String, Object>();
message.put("type", "image");
message.put("webcam", webcam.getName());
message.put("image", base64);

send(message);
}

private void send(String message) {
try {
session.getRemote().sendString(message);
} catch (IOException e) {
LOG.error("Exception when sending string", e);
}
}

private void send(Object object) {
try {
send(MAPPER.writeValueAsString(object));
} catch (JsonProcessingException e) {
LOG.error(e.getMessage(), e);
}
}
}
Loading

0 comments on commit 6a8a2f6

Please sign in to comment.