Skip to content

Commit

Permalink
Added go modules and migrated to logrus
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonas Falck committed Dec 6, 2020
1 parent 0a779e5 commit b3419c6
Show file tree
Hide file tree
Showing 14 changed files with 133 additions and 95 deletions.
12 changes: 9 additions & 3 deletions device.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package gocast

import (
"log"
"net"
"strconv"
"sync"

"github.com/sirupsen/logrus"
"github.com/stampzilla/gocast/api"
"github.com/stampzilla/gocast/events"
"github.com/stampzilla/gocast/handlers"
Expand Down Expand Up @@ -50,25 +50,31 @@ func NewDevice() *Device {
func (d *Device) SetName(name string) {
d.name = name
}

func (d *Device) SetUuid(uuid string) {
d.uuid = uuid
}

func (d *Device) SetIp(ip net.IP) {
d.ip = ip
}

func (d *Device) SetPort(port int) {
d.port = port
}

func (d *Device) Name() string {
return d.name
}

func (d *Device) Uuid() string {
return d.uuid
}

func (d *Device) Ip() net.IP {
return d.ip
}

func (d *Device) Port() int {
return d.port
}
Expand Down Expand Up @@ -98,8 +104,7 @@ func (d *Device) Subscribe(urn, destinationId string, handler Handler) {
handler.RegisterDispatch(d.Dispatch)
handler.Connect()

log.Println("Subscribing to ", urn, " --- ", destinationId)

logrus.Debug("Subscribing to ", urn, " --- ", destinationId)
}

func (d *Device) UnsubscribeByUrn(urn string) {
Expand All @@ -117,6 +122,7 @@ func (d *Device) UnsubscribeByUrn(urn string) {
delete(d.subscriptions, sub)
}
}

func (d *Device) UnsubscribeByUrnAndDestinationId(urn, destinationId string) {
subs := []string{}
d.RLock()
Expand Down
43 changes: 21 additions & 22 deletions device_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"time"

"github.com/davecgh/go-spew/spew"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"github.com/stampzilla/gocast/api"
"github.com/stampzilla/gocast/events"
"github.com/stampzilla/gocast/responses"
Expand All @@ -17,29 +17,25 @@ import (
func (d *Device) reader() {
for {
packet, err := d.wrapper.Read()

if err != nil {
log.Println("Error reading from chromecast error:", err, "Packet:", packet)
logrus.Errorf("Error reading from chromecast error: %s Packet: %#v", err, packet)
d.Disconnect()
//d.reconnect <- struct{}{}
return
}

message := &api.CastMessage{}
err = proto.Unmarshal(*packet, message)
if err != nil {
log.Fatalf("Failed to unmarshal CastMessage: %s", err)
logrus.Errorf("Failed to unmarshal CastMessage: %s", err)
continue
}

//spew.Dump("Message!", message)

headers := &responses.Headers{}

err = json.Unmarshal([]byte(*message.PayloadUtf8), headers)

if err != nil {
log.Fatalf("Failed to unmarshal message: %s", err)
logrus.Errorf("Failed to unmarshal message: %s", err)
continue
}

Expand All @@ -53,8 +49,8 @@ func (d *Device) reader() {
d.RUnlock()

if !catched {
log.Println("LOST MESSAGE:")
spew.Dump(message)
logrus.Debug("LOST MESSAGE:")
logrus.Debug(spew.Sdump(message))
}
}
}
Expand All @@ -64,31 +60,38 @@ func (d *Device) Connected() bool {
defer d.RUnlock()
return d.connected
}

func (d *Device) Connect() error {
go d.reconnector()
return d.connect()
}

func (d *Device) Reconnect() {
select {
case d.reconnect <- struct{}{}:
default:
}
}

func (d *Device) reconnector() {
for {
select {
case <-d.reconnect:
log.Println("Reconnect signal received")
logrus.Info("Reconnect signal received")
time.Sleep(time.Second * 2)
d.connect()
err := d.connect()
if err != nil {
logrus.Error(err)
}
}
}
}

func (d *Device) connect() error {
log.Printf("connecting to %s:%d ...", d.ip, d.port)
logrus.Infof("connecting to %s:%d ...", d.ip, d.port)

if d.conn != nil {
return fmt.Errorf("Already connected to: %s (%s:%d)", d.Name(), d.Ip().String(), d.Port())
return fmt.Errorf("already connected to: %s (%s:%d)", d.Name(), d.Ip().String(), d.Port())
}

var err error
Expand All @@ -97,16 +100,14 @@ func (d *Device) connect() error {
})

if err != nil {
//d.reconnect <- struct{}{}
return fmt.Errorf("Failed to connect to Chromecast. Error:%s", err)
return fmt.Errorf("failed to connect to Chromecast. Error:%s", err)
}

d.Lock()
d.connected = true
d.Unlock()

event := events.Connected{}
d.Dispatch(event)
d.Dispatch(events.Connected{})

d.wrapper = NewPacketStream(d.conn)
go d.reader()
Expand Down Expand Up @@ -139,7 +140,6 @@ func (d *Device) Disconnect() {
func (d *Device) Send(urn, sourceId, destinationId string, payload responses.Payload) error {
payloadJson, err := json.Marshal(payload)
if err != nil {
fmt.Println("Failed to json.Marshal: ", err)
return err
}
payloadString := string(payloadJson)
Expand All @@ -157,16 +157,15 @@ func (d *Device) Send(urn, sourceId, destinationId string, payload responses.Pay

data, err := proto.Marshal(message)
if err != nil {
fmt.Println("Failed to proto.Marshal: ", err)
return err
}

if *message.Namespace != "urn:x-cast:com.google.cast.tp.heartbeat" {
log.Println("Writing:", spew.Sdump(message))
logrus.Debug("Writing:", spew.Sdump(message))
}

if d.conn == nil {
return fmt.Errorf("We are disconnected, cannot send!")
return fmt.Errorf("we are disconnected, cannot send!")
}

_, err = d.wrapper.Write(data)
Expand Down
5 changes: 2 additions & 3 deletions discovery/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ func NewService() *Service {
}

func (d *Service) Periodic(interval time.Duration) error {

if d.stopPeriodic != nil {
return fmt.Errorf("Periodic discovery is allready running")
return fmt.Errorf("Periodic discovery is already running")
}

mdns.Query(&mdns.QueryParam{
Expand Down Expand Up @@ -82,7 +81,7 @@ func (d *Service) Found() chan *gocast.Device {

func (d *Service) listner() {
for entry := range d.entriesCh {
//fmt.Printf("Got new entry: %#v\n", entry)
// fmt.Printf("Got new entry: %#v\n", entry)

name := strings.Split(entry.Name, "._googlecast")

Expand Down
5 changes: 1 addition & 4 deletions discovery/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,17 @@ import (
)

func TestDecodeDnsEntry(t *testing.T) {

source := `Stamp\.\.\ \195\132r\ En\ Liten\ Fisk`

result := decodeDnsEntry(source)

assert.Equal(t, result, "Stamp.. Är En Liten Fisk")

}
}
func TestDecodeTxtRecord(t *testing.T) {

source := `id=87cf98a003f1f1dbd2efe6d19055a617|ve=04|md=Chromecast|ic=/setup/icon.png|fn=Chromecast PO|ca=5|st=0|bs=FA8FCA7EE8A9|rs=`

result := decodeTxtRecord(source)

assert.Equal(t, result["id"], "87cf98a003f1f1dbd2efe6d19055a617")

}
12 changes: 6 additions & 6 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ func main() {

func discoveryListner(discovery *discovery.Service) {
for device := range discovery.Found() {
fmt.Printf("New device discoverd: %#v \n", device)
fmt.Printf("New device discovered: %#v \n", device)

//plexHandler := NewPlexHandler()
//device.Subscribe("urn:x-cast:plex", plexHandler)
//device.Subscribe("urn:x-cast:com.google.cast.media", mediaHandler)
// plexHandler := NewPlexHandler()
// device.Subscribe("urn:x-cast:plex", plexHandler)
// device.Subscribe("urn:x-cast:com.google.cast.media", mediaHandler)

device.OnEvent(func(event events.Event) {
switch data := event.(type) {
Expand All @@ -46,8 +46,8 @@ func discoveryListner(discovery *discovery.Service) {
fmt.Println(device.Name(), "- App started:", data.DisplayName, "(", data.AppID, ")")
case events.AppStopped:
fmt.Println(device.Name(), "- App stopped:", data.DisplayName, "(", data.AppID, ")")
//gocast.MediaEvent:
//plexEvent:
// gocast.MediaEvent:
// plexEvent:
default:
fmt.Printf("unexpected event %T: %#v\n", data, data)
}
Expand Down
12 changes: 12 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module github.com/stampzilla/gocast

go 1.15

require (
github.com/davecgh/go-spew v1.1.1
github.com/gogo/protobuf v1.3.1
github.com/micro/mdns v0.3.0
github.com/sirupsen/logrus v1.7.0
github.com/stretchr/testify v1.6.1
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 // indirect
)
33 changes: 33 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls=
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/micro/mdns v0.3.0 h1:bYycYe+98AXR3s8Nq5qvt6C573uFTDPIYzJemWON0QE=
github.com/micro/mdns v0.3.0/go.mod h1:KJ0dW7KmicXU2BV++qkLlmHYcVv7/hHnbtguSWt9Aoc=
github.com/miekg/dns v1.1.3 h1:1g0r1IvskvgL8rR+AcHzUA+oFmGcQlaIm4IqakufeMM=
github.com/miekg/dns v1.1.3/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190130090550-b01c7a725664 h1:YbZJ76lQ1BqNhVe7dKTSB67wDrc2VPRR75IyGyyPDX8=
golang.org/x/crypto v0.0.0-20190130090550-b01c7a725664/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3 h1:ulvT7fqt0yHWzpJwI57MezWnYDVpCAYBVuYst/L+fAY=
golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 changes: 2 additions & 0 deletions handlers/basehandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ func (r *baseHandler) Dispatch(e events.Event) {
func (r *baseHandler) RegisterSend(send func(responses.Payload) error) {
r.send = send
}

func (r *baseHandler) Send(p responses.Payload) error {
return r.send(p)
}

func (r *baseHandler) RegisterRequest(send func(responses.Payload) (*api.CastMessage, error)) {
r.request = send
}

func (r *baseHandler) Request(p responses.Payload) (*api.CastMessage, error) {
return r.request(p)
}
5 changes: 2 additions & 3 deletions handlers/connection.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package handlers

import (
"fmt"

"github.com/sirupsen/logrus"
"github.com/stampzilla/gocast/responses"
)

Expand All @@ -19,5 +18,5 @@ func (c *Connection) Disconnect() {
}

func (c *Connection) Unmarshal(message string) {
fmt.Println("Connection received: ", message)
logrus.Info("Connection received: ", message)
}
Loading

0 comments on commit b3419c6

Please sign in to comment.