Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nest: add support for RTSP cameras #1253

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions internal/nest/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package nest

import (
"net/http"
"strings"

"github.com/AlexxIT/go2rtc/internal/api"
"github.com/AlexxIT/go2rtc/internal/streams"
Expand Down Expand Up @@ -38,11 +39,12 @@ func apiNest(w http.ResponseWriter, r *http.Request) {

var items []*api.Source

for name, deviceID := range devices {
query.Set("device_id", deviceID)
for _, device := range devices {
query.Set("device_id", device.DeviceID)
query.Set("protocols", strings.Join(device.Protocols, ","))

items = append(items, &api.Source{
Name: name, URL: "nest:?" + query.Encode(),
Name: device.Name, URL: "nest:?" + query.Encode(),
})
}

Expand Down
169 changes: 154 additions & 15 deletions pkg/nest/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,28 @@ type API struct {

StreamProjectID string
StreamDeviceID string
StreamSessionID string
StreamExpiresAt time.Time

// WebRTC
StreamSessionID string

// RTSP
StreamToken string
StreamExtensionToken string

extendTimer *time.Timer
}

type Auth struct {
AccessToken string
}

type DeviceInfo struct {
Name string
DeviceID string
Protocols []string
}

var cache = map[string]*API{}
var cacheMu sync.Mutex

Expand Down Expand Up @@ -78,7 +90,7 @@ func NewAPI(clientID, clientSecret, refreshToken string) (*API, error) {
return api, nil
}

func (a *API) GetDevices(projectID string) (map[string]string, error) {
func (a *API) GetDevices(projectID string) ([]DeviceInfo, error) {
uri := "https://smartdevicemanagement.googleapis.com/v1/enterprises/" + projectID + "/devices"
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
Expand All @@ -105,14 +117,21 @@ func (a *API) GetDevices(projectID string) (map[string]string, error) {
return nil, err
}

devices := map[string]string{}
devices := make([]DeviceInfo, 0, len(resv.Devices))

for _, device := range resv.Devices {
if len(device.Traits.SdmDevicesTraitsCameraLiveStream.SupportedProtocols) == 0 {
continue
}

if device.Traits.SdmDevicesTraitsCameraLiveStream.SupportedProtocols[0] != "WEB_RTC" {
supported := false
for _, protocol := range device.Traits.SdmDevicesTraitsCameraLiveStream.SupportedProtocols {
if protocol == "WEB_RTC" || protocol == "RTSP" {
supported = true
break
}
}
if !supported {
continue
}

Expand All @@ -122,7 +141,12 @@ func (a *API) GetDevices(projectID string) (map[string]string, error) {
}

name := device.Traits.SdmDevicesTraitsInfo.CustomName
devices[name] = device.Name[i+1:]
// Devices configured through the Nest app use the container/room name as opposed to the customName trait
if name == "" && len(device.ParentRelations) > 0 {
name = device.ParentRelations[0].DisplayName
}

devices = append(devices, DeviceInfo{Name: name, DeviceID: device.Name[i+1:], Protocols: device.Traits.SdmDevicesTraitsCameraLiveStream.SupportedProtocols})
}

return devices, nil
Expand Down Expand Up @@ -186,11 +210,20 @@ func (a *API) ExtendStream() error {
var reqv struct {
Command string `json:"command"`
Params struct {
MediaSessionID string `json:"mediaSessionId"`
MediaSessionID string `json:"mediaSessionId,omitempty"`
StreamExtensionToken string `json:"streamExtensionToken,omitempty"`
} `json:"params"`
}
reqv.Command = "sdm.devices.commands.CameraLiveStream.ExtendWebRtcStream"
reqv.Params.MediaSessionID = a.StreamSessionID

if a.StreamToken != "" {
// RTSP
reqv.Command = "sdm.devices.commands.CameraLiveStream.ExtendRtspStream"
reqv.Params.StreamExtensionToken = a.StreamExtensionToken
} else {
// WebRTC
reqv.Command = "sdm.devices.commands.CameraLiveStream.ExtendWebRtcStream"
reqv.Params.MediaSessionID = a.StreamSessionID
}

b, err := json.Marshal(reqv)
if err != nil {
Expand Down Expand Up @@ -218,8 +251,10 @@ func (a *API) ExtendStream() error {

var resv struct {
Results struct {
ExpiresAt time.Time `json:"expiresAt"`
MediaSessionID string `json:"mediaSessionId"`
ExpiresAt time.Time `json:"expiresAt"`
MediaSessionID string `json:"mediaSessionId"`
StreamExtensionToken string `json:"streamExtensionToken"`
StreamToken string `json:"streamToken"`
} `json:"results"`
}

Expand All @@ -229,6 +264,111 @@ func (a *API) ExtendStream() error {

a.StreamSessionID = resv.Results.MediaSessionID
a.StreamExpiresAt = resv.Results.ExpiresAt
a.StreamExtensionToken = resv.Results.StreamExtensionToken
a.StreamToken = resv.Results.StreamToken

return nil
}

func (a *API) GenerateRtspStream(projectID, deviceID string) (string, error) {
var reqv struct {
Command string `json:"command"`
Params struct{} `json:"params"`
}
reqv.Command = "sdm.devices.commands.CameraLiveStream.GenerateRtspStream"

b, err := json.Marshal(reqv)
if err != nil {
return "", err
}

uri := "https://smartdevicemanagement.googleapis.com/v1/enterprises/" +
projectID + "/devices/" + deviceID + ":executeCommand"
req, err := http.NewRequest("POST", uri, bytes.NewReader(b))
if err != nil {
return "", err
}

req.Header.Set("Authorization", "Bearer "+a.Token)

client := &http.Client{Timeout: time.Second * 5000}
res, err := client.Do(req)
if err != nil {
return "", err
}

if res.StatusCode != 200 {
return "", errors.New("nest: wrong status: " + res.Status)
}

var resv struct {
Results struct {
StreamURLs map[string]string `json:"streamUrls"`
StreamExtensionToken string `json:"streamExtensionToken"`
StreamToken string `json:"streamToken"`
ExpiresAt time.Time `json:"expiresAt"`
} `json:"results"`
}

if err = json.NewDecoder(res.Body).Decode(&resv); err != nil {
return "", err
}

if _, ok := resv.Results.StreamURLs["rtspUrl"]; !ok {
return "", errors.New("nest: failed to generate rtsp url")
}

a.StreamProjectID = projectID
a.StreamDeviceID = deviceID
a.StreamToken = resv.Results.StreamToken
a.StreamExtensionToken = resv.Results.StreamExtensionToken
a.StreamExpiresAt = resv.Results.ExpiresAt

return resv.Results.StreamURLs["rtspUrl"], nil
}

func (a *API) StopRTSPStream() error {
if a.StreamProjectID == "" || a.StreamDeviceID == "" {
return errors.New("nest: tried to stop rtsp stream without a project or device ID")
}

var reqv struct {
Command string `json:"command"`
Params struct {
StreamExtensionToken string `json:"streamExtensionToken"`
} `json:"params"`
}
reqv.Command = "sdm.devices.commands.CameraLiveStream.StopRtspStream"
reqv.Params.StreamExtensionToken = a.StreamExtensionToken

b, err := json.Marshal(reqv)
if err != nil {
return err
}

uri := "https://smartdevicemanagement.googleapis.com/v1/enterprises/" +
a.StreamProjectID + "/devices/" + a.StreamDeviceID + ":executeCommand"
req, err := http.NewRequest("POST", uri, bytes.NewReader(b))
if err != nil {
return err
}

req.Header.Set("Authorization", "Bearer "+a.Token)

client := &http.Client{Timeout: time.Second * 5000}
res, err := client.Do(req)
if err != nil {
return err
}

if res.StatusCode != 200 {
return errors.New("nest: wrong status: " + res.Status)
}

a.StreamProjectID = ""
a.StreamDeviceID = ""
a.StreamExtensionToken = ""
a.StreamToken = ""

return nil
}
Expand Down Expand Up @@ -261,10 +401,10 @@ type Device struct {
//SdmDevicesTraitsCameraClipPreview struct {
//} `json:"sdm.devices.traits.CameraClipPreview"`
} `json:"traits"`
//ParentRelations []struct {
// Parent string `json:"parent"`
// DisplayName string `json:"displayName"`
//} `json:"parentRelations"`
ParentRelations []struct {
Parent string `json:"parent"`
DisplayName string `json:"displayName"`
} `json:"parentRelations"`
}

func (a *API) StartExtendStreamTimer() {
Expand All @@ -277,7 +417,6 @@ func (a *API) StartExtendStreamTimer() {
duration = time.Until(a.StreamExpiresAt.Add(-30 * time.Second))
a.extendTimer.Reset(duration)
})

}

func (a *API) StopExtendStreamTimer() {
Expand Down
Loading