Skip to content

Commit

Permalink
added UAVTalk raw socket
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaminwater committed Jul 25, 2015
1 parent bf6da80 commit 3944697
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 8 deletions.
27 changes: 19 additions & 8 deletions uavtalkconnection/uavtalk.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ func start(sh *stateHolder) {
var link linker
var err error
for {
link, err = newUSBLink() //newTCPLink()
link, err = newTCPLink() // newUSBLink()
if err != nil {
log.Warning(err)
time.Sleep(1 * time.Second)
Expand All @@ -300,10 +300,15 @@ func start(sh *stateHolder) {
break
}

r, err := newUAVTalkRelayChan(9001)
if err != nil {
log.Warning(err)
}

linkError := make(chan error)
defer close(linkError)
defer link.Close()
// From USB
// From Controller
go func() {
defer recoverChanClosed()
packet := make([]byte, maxHIDFrameSize)
Expand All @@ -318,6 +323,9 @@ func start(sh *stateHolder) {
continue
}

if r.connected {
r.outChan <- packet[0:n]
}
buffer = append(buffer, packet[0:n]...)

for {
Expand Down Expand Up @@ -347,12 +355,15 @@ func start(sh *stateHolder) {
go func() {
defer recoverChanClosed()
for {
packet := <-sh.inChan

binaryPacket, err := packet.toBinary()
if err != nil {
log.Warning(err)
continue
var binaryPacket []byte
select {
case packet := <-sh.inChan:
binaryPacket, err = packet.toBinary()
if err != nil {
log.Warning(err)
continue
}
case binaryPacket = <-r.inChan:
}

_, err = link.Write(binaryPacket)
Expand Down
71 changes: 71 additions & 0 deletions uavtalkconnection/uavtalkrelay.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package uavtalkconnection

import (
"fmt"
"net"
"sync"

log "github.com/Sirupsen/logrus"
)

type relay struct {
inChan chan []byte
outChan chan []byte

connected bool
}

func newUAVTalkRelayChan(port int) (*relay, error) {
r := &relay{}
r.inChan = make(chan []byte, 100)
r.outChan = make(chan []byte, 100)

ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return nil, err
}
log.Infof("Relay listening %d", port)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
log.Warning(err)
continue
}
r.connected = true

wg := sync.WaitGroup{}
wg.Add(1)
go func(wg sync.WaitGroup) {
defer wg.Done()
buffer := make([]byte, 1024)
for {
n, err := conn.Read(buffer)
if err != nil {
log.Warning(err)
return
}
r.inChan <- buffer[0:n]
}
}(wg)

go func(wg sync.WaitGroup) {
defer wg.Done()
for {
buffer := <-r.outChan

_, err := conn.Write(buffer)
if err != nil {
log.Warning(err)
return
}
}
}(wg)

wg.Wait()
r.connected = false
}
}()

return r, nil
}

0 comments on commit 3944697

Please sign in to comment.