krkr
7/7/2014 - 12:00 AM

Play with Go! Toggle between play and pause by pressing a push button. #arduino #mocp #post-json

Play with Go! Toggle between play and pause by pressing a push button. #arduino #mocp #post-json

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/api"
	"github.com/hybridgroup/gobot/platforms/firmata"
	"github.com/hybridgroup/gobot/platforms/gpio"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os/exec"
)

type Stuff struct {
	Pof int
}

func post() {
	stuff := &Stuff{rand.Int()}
	buf, _ := json.Marshal(stuff)
	body := bytes.NewBuffer(buf)

	client := &http.Client{}
	req, _ := http.NewRequest("POST", "http://push.com/data/~123", body)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("X-Auth", "apiKey")

	resp, _ := client.Do(req)
	response, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("resp:" + string(response) + " req:" + string(buf))
}

func mocp() {
	exec.Command("sh","-c","mocp -G").Output()
}

func main() {
	gbot := gobot.NewGobot()
	api.NewAPI(gbot).Start()

	firmataAdaptor := firmata.NewFirmataAdaptor("myFirmata", "/dev/ttyACM0")

	button := gpio.NewButtonDriver(firmataAdaptor, "btn", "2")
	led := gpio.NewLedDriver(firmataAdaptor, "led", "13")

	gobot.On(button.Events["push"], func(data interface{}) {
		led.On()
	})
	gobot.On(button.Events["release"], func(data interface{}) {
  		led.Off()
    		post() // Just 4 fun
    		mocp()
  	})

	goduino := gbot.AddRobot(
		gobot.NewRobot("duino", []gobot.Connection{firmataAdaptor}, []gobot.Device{button, led}, nil))

	goduino.AddCommand("blink", func(params map[string]interface{}) interface{} {
		led.Toggle()
		return fmt.Sprintf("Ok: 200")
	})

	gbot.Start()
}