Initial commit

This commit is contained in:
Milan Nikolic
2017-10-03 20:50:11 +02:00
commit 2ad5743f5f
13 changed files with 1389 additions and 0 deletions

109
handlers/html.go Normal file
View File

@@ -0,0 +1,109 @@
// Package handlers.
package handlers
import (
"fmt"
"net/http"
"strings"
)
// HTML handler.
type HTML struct {
Template []byte
}
// NewHTML returns new HTML handler.
func NewHTML(bind string, width, height float64) *HTML {
h := &HTML{}
b := strings.Split(bind, ":")
if b[0] == "" {
bind = "127.0.0.1" + bind
}
html = strings.Replace(html, "{BIND}", bind, -1)
html = strings.Replace(html, "{WIDTH}", fmt.Sprintf("%.0f", width), -1)
html = strings.Replace(html, "{HEIGHT}", fmt.Sprintf("%.0f", height), -1)
h.Template = []byte(html)
return h
}
// ServeHTTP handles requests on incoming connections.
func (h *HTML) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
msg := fmt.Sprintf("405 Method Not Allowed (%s)", r.Method)
http.Error(w, msg, http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(h.Template)
}
var html = `<html>
<head>
<title>cam2ip</title>
<style>
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background-color: #000000;
}
div {
width: 100%;
height: 100%;
position: relative;
}
canvas {
height: auto;
width: auto;
max-height: 100%;
max-width: 100%;
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
box-sizing: border-box;
margin: auto;
}
</style>
<script>
var url = "ws://{BIND}/socket";
ws = new WebSocket(url);
ws.onopen = function() {
console.log("onopen");
}
ws.onmessage = function(e) {
var context = document.getElementById("canvas").getContext("2d");
var image = new Image();
image.onload = function() {
context.drawImage(image, 0, 0);
}
image.setAttribute("src", "data:image/jpeg;base64," + e.data);
}
ws.onclose = function(e) {
console.log("onclose");
}
ws.onerror = function(e) {
console.log("onerror");
}
</script>
</head>
<body>
<div><canvas id="canvas" width="{WIDTH}" height="{HEIGHT}"></canvas></div>
</body>
</html>`

44
handlers/jpeg.go Normal file
View File

@@ -0,0 +1,44 @@
package handlers
import (
"log"
"net/http"
"github.com/gen2brain/cam2ip/camera"
)
// JPEG handler.
type JPEG struct {
camera *camera.Camera
}
// NewJPEG returns new JPEG handler.
func NewJPEG(camera *camera.Camera) *JPEG {
return &JPEG{camera}
}
// ServeHTTP handles requests on incoming connections.
func (j *JPEG) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Add("Connection", "close")
w.Header().Add("Cache-Control", "no-store, no-cache")
w.Header().Add("Content-Type", "image/jpeg")
img, err := j.camera.Read()
if err != nil {
log.Printf("jpeg: read: %v", err)
return
}
enc := camera.NewEncoder(w)
err = enc.Encode(img)
if err != nil {
log.Printf("jpeg: encode: %v", err)
return
}
}

77
handlers/mjpeg.go Normal file
View File

@@ -0,0 +1,77 @@
// Package handlers.
package handlers
import (
"fmt"
"log"
"mime/multipart"
"net/http"
"net/textproto"
"time"
"github.com/gen2brain/cam2ip/camera"
)
// MJPEG handler.
type MJPEG struct {
camera *camera.Camera
delay int
}
// NewMJPEG returns new MJPEG handler.
func NewMJPEG(camera *camera.Camera, delay int) *MJPEG {
return &MJPEG{camera, delay}
}
// ServeHTTP handles requests on incoming connections.
func (m *MJPEG) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
return
}
mimeWriter := multipart.NewWriter(w)
mimeWriter.SetBoundary("--boundary")
w.Header().Add("Connection", "close")
w.Header().Add("Cache-Control", "no-store, no-cache")
w.Header().Add("Content-Type", fmt.Sprintf("multipart/x-mixed-replace;boundary=%s", mimeWriter.Boundary()))
cn := w.(http.CloseNotifier).CloseNotify()
loop:
for {
select {
case <-cn:
break loop
default:
partHeader := make(textproto.MIMEHeader)
partHeader.Add("Content-Type", "image/jpeg")
partWriter, err := mimeWriter.CreatePart(partHeader)
if err != nil {
log.Printf("mjpeg: createPart: %v", err)
continue
}
img, err := m.camera.Read()
if err != nil {
log.Printf("mjpeg: read: %v", err)
continue
}
enc := camera.NewEncoder(partWriter)
err = enc.Encode(img)
if err != nil {
log.Printf("mjpeg: encode: %v", err)
continue
}
time.Sleep(time.Duration(m.delay) * time.Millisecond)
}
}
mimeWriter.Close()
}

53
handlers/socket.go Normal file
View File

@@ -0,0 +1,53 @@
package handlers
import (
"bytes"
"encoding/base64"
"log"
"time"
"golang.org/x/net/websocket"
"github.com/gen2brain/cam2ip/camera"
)
// Socket handler.
type Socket struct {
camera *camera.Camera
delay int
}
// NewSocket returns new socket handler.
func NewSocket(camera *camera.Camera, delay int) websocket.Handler {
s := &Socket{camera, delay}
return websocket.Handler(s.write)
}
// write writes images to socket
func (s *Socket) write(ws *websocket.Conn) {
for {
img, err := s.camera.Read()
if err != nil {
log.Printf("socket: read: %v", err)
continue
}
w := new(bytes.Buffer)
enc := camera.NewEncoder(w)
err = enc.Encode(img)
if err != nil {
log.Printf("socket: encode: %v", err)
continue
}
b64 := base64.StdEncoding.EncodeToString(w.Bytes())
_, err = ws.Write([]byte(b64))
if err != nil {
break
}
time.Sleep(time.Duration(s.delay) * time.Millisecond)
}
}