Example #1
0
func main() {
	config.StableFlagFile = nconfig.String("/var/run/zigbee.stable", "zigbee", "stable-file")
	config.Hostname = nconfig.String("localhost", "zigbee", "host")

	_, err := NewDriver(config)
	if log.IsDebugEnabled() {
		log.Debugf("version - %s - running with configuration %+v", Version, config)
	}

	if err != nil {
		log.Fatalf("Failed to start ZigBee driver: %s", err)
	}

	support.WaitUntilSignal()
}
Example #2
0
func UpdateSphereAvahiService(isPaired, isMaster bool) error {

	tmpl, err := template.New("avahi").Parse(src)

	if err != nil {
		return err
	}

	serviceDefinition := new(bytes.Buffer)

	err = tmpl.Execute(serviceDefinition, map[string]interface{}{
		"Serial":      config.Serial(),
		"Master":      isMaster,
		"Paired":      isPaired,
		"User":        config.String("", "userId"),
		"Site":        config.String("", "siteId"),
		"MasterNode":  config.String("", "masterNodeId"),
		"SiteUpdated": config.Int(0, "siteUpdated"),
		"RestPort":    config.MustInt("homecloud.rest.port"),
	})

	if err != nil {
		return err
	}

	log.Debugf("Saving service definition", serviceDefinition.String())

	if runtime.GOOS != "linux" {
		log.Warningf("Avahi service definition is not being saved, as platform != linux")
		return nil
	}

	if _, err := os.Stat("/data/etc/avahi/services"); err != nil {
		log.Warningf("Avahi service definition is not being saved, as /data/etc/avahi/services does not exist")
		return nil
	}

	err = ioutil.WriteFile("/data/etc/avahi/services/ninjasphere.service", []byte(serviceDefinition.String()), 0644)

	// HACK: Remove this if it doesn't fix Chris's problem
	exec.Command("service", "avahi-daemon", "restart").Output()

	return err
}
Example #3
0
func main() {
	config.StableFlagFile = nconfig.String("/var/run/zigbee.stable", "zigbee", "stable-file")
	config.Hostname = nconfig.String("localhost", "zigbee", "host")

	check, err := os.Open("/etc/disable-zigbee")
	if err != nil {

		// this is the expected case

		_, err := NewDriver(config)
		if log.IsDebugEnabled() {
			log.Debugf("version - %s - running with configuration %+v", Version, config)
		}

		if err != nil {
			log.Fatalf("Failed to start ZigBee driver: %s", err)
		}
	} else {
		check.Close()
		log.Debugf("version - %s - zigbee access disabled by /etc/disable-zigbee", Version)
	}

	support.WaitUntilSignal()
}
func NewPairingLayout() *PairingLayout {

	layout := &PairingLayout{
		log:          logger.GetLogger("PaneLayout"),
		progressPane: NewUpdateProgressPane(util.ResolveImagePath("update-progress.gif"), util.ResolveImagePath("update-loop.gif")),
	}
	layout.ShowIcon(config.String("spinner-blue.gif", "led.loadingImage"))

	/*	go func() {
		time.Sleep(time.Second * 5)

		c, _ := colorful.Hex("#517AB8")

		layout.ShowColor(c)

	}()*/

	/*go func() {
		progress := 0.0
		for {
			time.Sleep(time.Millisecond * 30)
			layout.ShowUpdateProgress(progress)
			progress = progress + 0.01
			if progress >= 1 {
				layout.ShowUpdateProgress(1)
				break
			}
		}
	}()*/

	/*go func() {
		time.Sleep(time.Second * 1)
		layout.ShowDrawing()
		for {
			time.Sleep(time.Millisecond * 2)
			update := []uint8{uint8(rand.Intn(16)), uint8(rand.Intn(16)), uint8(rand.Intn(255)), uint8(rand.Intn(255)), uint8(rand.Intn(255))}
			frames := [][]uint8{update}
			layout.Draw(&frames)
		}
	}()*/

	return layout
}
Example #5
0
func MustConnect(host, id string) Bus {
	//return ConnectTinyBus(host, id)

	library := config.String("tiny", "mqtt.implementation")

	log.Infof("Using mqtt bus implementation: %s", library)

	var bus Bus
	var err error

	switch library {
	case "tiny":
		bus, err = ConnectTinyBus(host, id)
	default:
		log.Fatalf("Unknown mqtt bus implementation: %s", library)
	}

	if err != nil {
		log.HandleError(err, "Failed to connect to mqtt")
	}
	return bus
}
Example #6
0
package client

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os/exec"
	"time"

	"github.com/ninjasphere/go-ninja/config"
)

var meshFile = config.String("/data/etc/opt/ninja/mesh.json", "meshFile")

type meshInfo struct {
	SiteID       string `json:"siteId"`
	MasterNodeID string `json:"masterNodeId"`
	SiteUpdated  int    `json:"siteUpdated"`
}

func refreshMeshInfo() (*meshInfo, error) {

	nodes, err := getNodes()
	if err != nil {
		return nil, err
	}

	sites, err := getSites()
	if err != nil {
		return nil, err
Example #7
0
	SetTag(accessToken string, siteId string, tag string, body interface{}, replace bool) error

	/**
	 * Unmarshals the value of the specifed tag for the specified site onto the specified body object.
	 */
	GetTag(accessToken string, siteId string, tag string, body interface{}) error
}

type cloud struct {
	idPrefix  string
	apiPrefix string
	clientId  string
}

var cloudInstance = cloud{
	idPrefix:  config.String("https://id.sphere.ninja", "cloud.id"),
	apiPrefix: config.String("https://api.sphere.ninja", "cloud.api"),
	clientId:  config.String("0u2jota2o1dlou72hot4", "cloud.client_id"),
}

func CloudAPI() Cloud {
	return &cloudInstance
}

func (c *cloud) RegisterUser(name string, email string, password string) error {

	data := map[string]interface{}{
		"name":     name,
		"email":    email,
		"password": password,
	}
Example #8
0
import (
	"github.com/ninjasphere/go-ninja/config"
	"log"
	"net"
	"os/exec"
	"strings"
	"time"

	"github.com/mostlygeek/arp"
)

var maxDatagramSize = 8192
var udpHost = "224.0.0.1:30050"
var udpClient = "224.0.0.1:30000"
var hemsPrefix = config.String("192.168.12", "go-daikin.hems-prefix")

func Discover(discoverInterval time.Duration) (chan AC, error) {

	seen := map[string]*wirelessAC{}

	found := make(chan AC)

	/*clientAddr, err := net.ResolveUDPAddr("udp", udpClient)
	if err != nil {
		log.Fatal(err)
	}
	l, err := net.ListenUDP("udp", clientAddr)
	if err != nil {
		return nil, err
	}
	"bufio"
	"errors"
	"fmt"
	"image"
	"io"
	"math"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"github.com/ninjasphere/go-ninja/config"
	"github.com/tarm/serial"
)

var ledPath = config.String("/dev/tty.ledmatrix", "led.tty")

var cmdWriteBuffer byte = 1
var cmdSwapBuffers byte = 2

// Attempts this first, then falls back to half.
const baudRate = 230400

// From https://diarmuid.ie/blog/post/pwm-exponential-led-fading-on-arduino-or-other-platforms
var R = (255 * math.Log10(2)) / (math.Log10(255))
var ledAdjust = make(map[uint8]uint8)

func init() {
	for i := 0; i < 256; i++ {
		ledAdjust[uint8(i)] = uint8(math.Pow(2, (float64(i)/R)) - 1)
	}
Example #10
0
package main

import (
	"fmt"

	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/support"
	"github.com/ninjasphere/sphere-go-led-controller/remote"
)

var log = logger.GetLogger("ac-pane")

var host = config.String("localhost", "led.host")
var port = config.Int(3115, "led.remote.port")

func main() {

	app := &App{}
	err := app.Init(info)
	if err != nil {
		app.Log.Fatalf("failed to initialize app: %v", err)
	}

	err = app.Export(app)
	if err != nil {
		app.Log.Fatalf("failed to export app: %v", err)
	}

	support.WaitUntilSignal()
Example #11
0
		if err != nil {
			log.Warningf("Activation error : %s", err)
			log.Warningf("Sleeping for 3sec")
			time.Sleep(time.Second * 3)
		} else if creds != nil {
			break
		}
	}

	log.Infof("Got credentials. User: %s", creds.UserID)

	return saveCreds(creds)
}

var credsFile = config.String("/data/etc/opt/ninja/credentials.json", "credentialFile")

func saveCreds(creds *credentials) error {

	log.Infof("Saving credentials to %s", credsFile)

	credsJSON, err := json.Marshal(creds)
	if err != nil {
		return fmt.Errorf("Failed to marshal credentials: %s", err)
	}

	// XXX: HACK: TODO: CHANGE ME BACK TO 600
	err = ioutil.WriteFile(credsFile, credsJSON, 0644)

	if err != nil {
		return fmt.Errorf("Failed to write credentials file: %s", err)
Example #12
0
func main() {

	log.Infof("Welcome home, Ninja.")

	if config.Bool(true, "homecloud.waitForNTP") {
		waitForNTP()
	}

	// The MQTT Connection
	conn, err := ninja.Connect("sphere-go-homecloud")
	if err != nil {
		log.Fatalf("Failed to connect to sphere: %s", err)
	}

	// An MQTT Connection used for outbound syncing connections
	syncConn := &models.SyncConnection{}
	syncConn.Conn, err = ninja.Connect("sphere-go-homecloud.sync")
	if err != nil {
		log.Fatalf("Failed to connect to sphere (sync): %s", err)
	}

	// Our redis pool
	pool := &redis.Pool{
		MaxIdle:     config.MustInt("homecloud.redis.maxIdle"),
		MaxActive:   config.Int(10, "homecloud.redis.maxActive"),
		IdleTimeout: config.MustDuration("homecloud.redis.idleTimeout"),
		Wait:        true,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", config.String("", "homecloud.redis.host"), config.MustInt("homecloud.redis.port")))
			if err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}

	// Not pretty.
	rpc.RedisPool = pool

	// Wait until we connect to redis successfully.
	for {
		c := pool.Get()

		if c.Err() == nil {
			c.Close()
			break
		}
		log.Warningf("Failed to connect to redis: %s", c.Err())
		time.Sleep(time.Second)
	}

	// Build the object graph using dependency injection
	injectables := []interface{}{}

	injectables = append(injectables, pool, conn, syncConn)
	injectables = append(injectables, &homecloud.HomeCloud{}, &homecloud.TimeSeriesManager{}, &homecloud.DeviceManager{}, &homecloud.ModuleManager{})
	injectables = append(injectables, state.NewStateManager())
	injectables = append(injectables, &rest.RestServer{})
	injectables = append(injectables, models.GetInjectables()...)

	err = inject.Populate(injectables...)

	if err != nil {
		log.Fatalf("Failed to construct the object graph: %s", err)
	}

	// Run PostConstruct on any objects that have it
	for _, node := range injectables {
		if n, ok := node.(postConstructable); ok {
			go func(c postConstructable) {
				if err := c.PostConstruct(); err != nil {
					log.Fatalf("Failed PostConstruct on object %s: %s", reflect.TypeOf(c).String(), err)
				}
			}(n)
		}
	}

	support.WaitUntilSignal()
	// So long, and thanks for all the fish.
}
Example #13
0
package main

import (
	"fmt"
	"os"
	"os/signal"

	"github.com/ninjasphere/go-daikin-ac/proxy"
	"github.com/ninjasphere/go-ninja/config"
)

var udpBroadcast = config.String("192.168.12.255", "daikin-proxy.broadcast") + ":30050"
var iface = config.String("eth2", "daikin-proxy.interface")

func main() {

	err := proxy.Start(udpBroadcast, iface)
	if err != nil {
		panic(err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	// Block until a signal is received.
	s := <-c
	fmt.Println("Got signal:", s)
}