Created
August 31, 2014 03:35
-
-
Save iautom8things/638582f4155e71d37a4e to your computer and use it in GitHub Desktop.
websocket adaptation of http://gobot.io for Beaglebone example: http://gobot.io/documentation/platforms/beaglebone/
This file contains 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
package main | |
import ( | |
"code.google.com/p/go.net/websocket" | |
"fmt" | |
"github.com/hybridgroup/gobot" | |
"github.com/hybridgroup/gobot/platforms/beaglebone" | |
"github.com/hybridgroup/gobot/platforms/gpio" | |
"net/http" | |
"strconv" | |
"time" | |
) | |
func main() { | |
gbot := gobot.NewGobot() | |
c := make(chan int, 1) | |
beagleboneAdaptor := beaglebone.NewBeagleboneAdaptor("beaglebone") | |
led := gpio.NewLedDriver(beagleboneAdaptor, "led", "P9_12") | |
n := 1000 | |
work := func() { | |
for { | |
select { | |
case n = <-c: | |
case <-time.After(time.Duration(n) * time.Millisecond): | |
fmt.Println("Toggling!") | |
led.Toggle() | |
} | |
} | |
} | |
robot := gobot.NewRobot("blinkBot", | |
[]gobot.Connection{beagleboneAdaptor}, | |
[]gobot.Device{led}, | |
work, | |
) | |
gbot.AddRobot(robot) | |
go gbot.Start() | |
ChannelServer := func(ws *websocket.Conn) { | |
for { | |
var message string | |
websocket.Message.Receive(ws, &message) | |
if len(message) == 0 { | |
fmt.Println("breaking") | |
break | |
} | |
fmt.Println("Received: ", message) | |
n64, _ := strconv.ParseInt(message, 10, 0) | |
c <- int(n64) | |
} | |
} | |
http.Handle("/websocket", websocket.Handler(ChannelServer)) | |
http.HandleFunc("/commandcenter", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, ` | |
<html> | |
<head></head> | |
<body> | |
<input type='text' id='sleep_time'> | |
<button onclick='send()'>Send!</button> | |
<script type='text/javascript'> | |
var ws = new WebSocket('ws://10.0.1.48:12345/websocket'); | |
function send ( ) { | |
var time = document.getElementById('sleep_time').value; | |
console.log(time); | |
if (time.length == 0) { | |
console.log('not sending'); | |
alert('Time must be > 0!'); | |
} else { | |
console.log('sending'); | |
ws.send(time); | |
} | |
} | |
</script> | |
</body> | |
</html> | |
`) | |
}) | |
err := http.ListenAndServe(":12345", nil) | |
if err != nil { | |
panic("ListenAndServe: " + err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment