-
Notifications
You must be signed in to change notification settings - Fork 786
Add tuya webrtc support #1379
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
Open
romasku
wants to merge
16
commits into
AlexxIT:master
Choose a base branch
from
romasku:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add tuya webrtc support #1379
Changes from 9 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
81b70a8
Add tuya webrtc support
romasku a34b389
Cleanup code
romasku ebcc2df
Add Readme entry
romasku a33d95b
Use different hack to avoid ICE controlled issue
romasku a0b9883
Fix get token when token is already acquired
romasku b257c76
Avoid using global variables
romasku facff09
Enable debug logs only for tuya
romasku 0265942
Enable send recv
romasku b429d98
Set correct stream type
romasku 0de5bd2
Merge remote-tracking branch 'upstream/master'
romasku 43cc27d
Apply suggestions from code review
romasku 0404bbf
Translate chinese comments
romasku e93fcef
Remove debug logs
romasku d3dd976
Cleanup code
romasku 2f896f3
Add doc about Tuya's resolution_id
romasku f49f044
Merge remote-tracking branch 'upstream/master'
romasku File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| package tuya | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "crypto/md5" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "net/http" | ||
| "strconv" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/google/uuid" | ||
| "github.com/tidwall/gjson" | ||
| ) | ||
|
|
||
| func (t *tuyaSession) makeHttpSign(ts int64) string { | ||
| // If httpAccessToken is "" then this is un-authed request, so no need to do 'if' here | ||
| data := fmt.Sprintf("%s%s%s%d", t.config.ClientID, t.httpAccessToken, t.config.Secret, ts) | ||
| val := md5.Sum([]byte(data)) | ||
| res := fmt.Sprintf("%X", val) | ||
| return res | ||
| } | ||
|
|
||
| func (t *tuyaSession) httpRequest(method string, path string, body io.Reader) (res []byte, err error) { | ||
| client := &http.Client{ | ||
| Timeout: time.Second * 5, | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s%s", t.config.OpenAPIURL, path) | ||
|
|
||
| request, err := http.NewRequest(method, url, body) | ||
| if err != nil { | ||
| log.Printf("create http request fail: %s", err.Error()) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| ts := time.Now().UnixNano() / 1000000 | ||
| sign := t.makeHttpSign(ts) | ||
|
|
||
| // TODO: do we need all this headers? | ||
|
|
||
| request.Header.Set("Accept", "*") | ||
| request.Header.Set("Content-Type", "application/json") | ||
| request.Header.Set("Access-Control-Allow-Origin", "*") | ||
| request.Header.Set("Access-Control-Allow-Methods", "*") | ||
| request.Header.Set("Access-Control-Allow-Headers", "*") | ||
| request.Header.Set("mode", "no-cors") | ||
| request.Header.Set("client_id", t.config.ClientID) | ||
| request.Header.Set("access_token", t.httpAccessToken) | ||
| request.Header.Set("sign", sign) | ||
| request.Header.Set("t", strconv.FormatInt(ts, 10)) | ||
|
|
||
| response, err := client.Do(request) | ||
| if err != nil { | ||
| log.Printf("http request fail: %s", err.Error()) | ||
|
|
||
| return | ||
| } | ||
| defer response.Body.Close() | ||
|
|
||
| res, err = io.ReadAll(response.Body) | ||
| if err != nil { | ||
| log.Printf("read http response fail: %s", err.Error()) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| return | ||
| } | ||
|
|
||
| func (t *tuyaSession) Authorize() (err error) { | ||
| t.httpAccessToken = "" // Clear all access token if present | ||
|
|
||
| body, err := t.httpRequest("GET", "/v1.0/token?grant_type=1", nil) | ||
| if err != nil { | ||
| log.Printf("sync OpenAPI ressponse to config fail: %s", err.Error()) | ||
| return | ||
| } | ||
|
|
||
| accessTokenValue := gjson.GetBytes(body, "result.access_token") | ||
| if !accessTokenValue.Exists() { | ||
| log.Printf("access_token not exits in body: %s", string(body)) | ||
| return errors.New("access_token not exist") | ||
| } | ||
|
|
||
| t.httpAccessToken = accessTokenValue.String() | ||
|
|
||
| return | ||
| } | ||
|
|
||
| func (t *tuyaSession) GetMotoIDAndAuth() (motoID, auth, iceServers string, err error) { | ||
| path := fmt.Sprintf("/v1.0/users/%s/devices/%s/webrtc-configs", t.config.UID, t.config.DeviceID) | ||
|
|
||
| body, err := t.httpRequest("GET", path, nil) | ||
| if err != nil { | ||
| log.Printf("GET webrtc-configs fail: %s, body: %s", err.Error(), string((body))) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| motoIDValue := gjson.GetBytes(body, "result.moto_id") | ||
| if !motoIDValue.Exists() { | ||
| log.Printf("moto_id not exist in webrtc-configs, body: %s", string(body)) | ||
|
|
||
| return "", "", "", errors.New("moto_id not exist") | ||
| } | ||
|
|
||
| authValue := gjson.GetBytes(body, "result.auth") | ||
| if !authValue.Exists() { | ||
| log.Printf("auth not exist in webrtc-configs, body: %s", string(body)) | ||
|
|
||
| return "", "", "", errors.New("auth not exist") | ||
| } | ||
|
|
||
| iceServersValue := gjson.GetBytes(body, "result.p2p_config.ices") | ||
| if !iceServersValue.Exists() { | ||
| log.Printf("iceServers not exist in webrtc-configs, body: %s", string(body)) | ||
|
|
||
| return "", "", "", errors.New("p2p_config.ices not exist") | ||
| } | ||
|
|
||
| var tokens []Token | ||
| err = json.Unmarshal([]byte(iceServersValue.String()), &tokens) | ||
| if err != nil { | ||
| log.Printf("unmarshal to tokens fail: %s", err.Error()) | ||
| return "", "", "", err | ||
| } | ||
|
|
||
| ices := make([]WebToken, 0) | ||
| for _, token := range tokens { | ||
| if strings.HasPrefix(token.Urls, "stun") { | ||
| ices = append(ices, WebToken{ | ||
| Urls: token.Urls, | ||
| }) | ||
| } else if strings.HasPrefix(token.Urls, "turn") { | ||
| ices = append(ices, WebToken{ | ||
| Urls: token.Urls, | ||
| Username: token.Username, | ||
| Credential: token.Credential, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| iceServersBytes, err := json.Marshal(&ices) | ||
| if err != nil { | ||
| log.Printf("marshal token to web tokens fail: %s", err.Error()) | ||
| return "", "", "", err | ||
| } | ||
|
|
||
| motoID = motoIDValue.String() | ||
| auth = authValue.String() | ||
| iceServers = string(iceServersBytes) | ||
|
|
||
| return | ||
| } | ||
|
|
||
| func (t *tuyaSession) GetHubConfig() (config *OpenIoTHubConfig, err error) { | ||
| request := &OpenIoTHubConfigRequest{ | ||
| UID: t.config.UID, | ||
| UniqueID: uuid.New().String(), | ||
| LinkType: "mqtt", | ||
| Topics: "ipc", | ||
| } | ||
|
|
||
| payload, err := json.Marshal(request) | ||
| if err != nil { | ||
| log.Printf("marshal OpenIoTHubConfig Request fail: %s", err.Error()) | ||
| return nil, err | ||
| } | ||
|
|
||
| body, err := t.httpRequest("POST", "/v2.0/open-iot-hub/access/config", bytes.NewReader(payload)) | ||
|
|
||
| if err != nil { | ||
| log.Printf("get OpenIoTHub config from http fail: %s", err.Error()) | ||
| return | ||
| } | ||
|
|
||
| if !gjson.GetBytes(body, "success").Bool() { | ||
| log.Printf("request OpenIoTHub Config fail, body: %s", string(body)) | ||
| return nil, errors.New("request hub config fail") | ||
| } | ||
|
|
||
| config = &OpenIoTHubConfig{} | ||
|
|
||
| err = json.Unmarshal([]byte(gjson.GetBytes(body, "result").String()), config) | ||
| if err != nil { | ||
| log.Printf("unmarshal OpenIoTHub config to object fail: %s, body: %s", err.Error(), string(body)) | ||
| return | ||
| } | ||
|
|
||
| return | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.