示例#1
0
func (c *HomeCloud) PostConstruct() error {

	c.log = logger.GetLogger("HomeCloud")

	c.ExportRPCServices()
	c.ensureSiteExists()

	ledController := c.Conn.GetServiceClient("$home/led-controller")
	err := ledController.Call("enableControl", nil, nil, 0)
	if err != nil {
		c.log.Infof("Failed to enable control on LED controller: %s", err)
	}

	if syncEnabled {
		// We wait for at least one sync to happen, or fail
		<-c.StartSyncing(config.MustDuration("homecloud.sync.interval"))
	}

	// This is required to enable sphere-reset to clear out redis, then push this empty db to
	// cloud.
	if config.Bool(false, "clearcloud") {
		c.log.Infof("Just clearing cloud so exiting now!")
		os.Exit(0)
	}

	c.AutoStartModules()

	return nil
}
func NewStateManager() StateManager {

	return &NinjaStateManager{
		lastStates: make(map[string]*LastState),
		log:        logger.GetLogger("sphere-go-homecloud-state"),
	}
}
示例#3
0
// Connect Builds a new ninja connection to the MQTT broker, using the given client ID
func Connect(clientID string) (*Connection, error) {

	log := logger.GetLogger(fmt.Sprintf("%s.connection", clientID))

	conn := Connection{
		log:      log,
		services: []model.ServiceAnnouncement{},
	}

	mqttURL := fmt.Sprintf("%s:%d", config.MustString("mqtt", "host"), config.MustInt("mqtt", "port"))

	log.Infof("Connecting to %s using cid:%s", mqttURL, clientID)

	conn.mqtt = bus.MustConnect(mqttURL, clientID)

	log.Infof("Connected")

	conn.rpc = rpc.NewClient(conn.mqtt, json2.NewClientCodec())
	conn.rpcServer = rpc.NewServer(conn.mqtt, json2.NewCodec())

	// Add service discovery service. Responds to queries about services exposed in this process.
	discoveryService := &discoverService{&conn}
	_, err := conn.exportService(discoveryService, "$discover", &simpleService{*discoveryService.GetServiceAnnouncement()})
	if err != nil {
		log.Fatalf("Could not expose discovery service: %s", err)
	}

	return &conn, nil
}
func NewCertPane(conn bus.Bus) *CertPane {

	log := logger.GetLogger("CertPane")

	pane := &CertPane{
		log: log,
	}

	if !enableCertificationPane {
		return pane
	}

	_, err := conn.Subscribe("$location/waypoints", func(topic string, payload []byte) {
		var waypoints int
		err := json.Unmarshal(payload, &waypoints)
		if err != nil {
			log.Infof("Failed to parse incoming waypoints json %s, from %s", err, payload)
		} else {
			log.Infof("Number of waypoints: %d", waypoints)
		}
		pane.waypoints = waypoints
	})

	if err != nil {
		log.HandleError(err, "Could not start subscription to waypoint topic")
	}

	pane.StartRssi(conn)

	return pane
}
示例#5
0
func CreateLightDevice(driver ninja.Driver, info *model.Device, conn *ninja.Connection) (*LightDevice, error) {

	d := &LightDevice{
		baseDevice: baseDevice{
			conn:   conn,
			driver: driver,
			log:    logger.GetLogger("LightDevice - " + *info.Name),
			info:   info,
		},
	}

	err := conn.ExportDevice(d)
	if err != nil {
		d.log.Fatalf("Failed to export device %s: %s", *info.Name, err)
	}

	methods := []string{"setBatch"}
	events := []string{}

	err = conn.ExportChannelWithSupported(d, &LightBatchChannel{d}, "batch", &methods, &events)
	if err != nil {
		d.log.Fatalf("Failed to create batch channel: %s", err)
	}

	d.log.Infof("Created")

	return d, nil
}
func main() {

	/*
		go func() {
			log.Printf("Starting pprof server")
			log.Println(http.ListenAndServe(":6060", nil))
		}()
		//*/

	log := logger.GetLogger("LED-controller")

	conn, err := ninja.Connect(drivername)

	if err != nil {
		log.FatalErrorf(err, "Failed to connect to mqtt")
	}

	controller, err := NewLedController(conn)

	if err != nil {
		log.FatalErrorf(err, "Failed to create led controller")
	}

	enableControl := config.Bool(false, "enableControl")

	controller.start(enableControl)

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

	// Block until a signal is received.
	x := <-blah
	log.Infof("Got signal:", x)

}
func NewPane(conn net.Conn) *Pane {

	pane := &Pane{
		conn:           conn,
		log:            logger.GetLogger("Pane"),
		Disconnected:   make(chan bool, 1),
		incoming:       gob.NewDecoder(conn),
		outgoing:       gob.NewEncoder(conn),
		enabled:        true,
		incomingFrames: make(chan *Incoming, 1),
	}

	// Ping the remote pane continuously so we can see if it's disappeared.
	// This is kinda dumb.
	go func() {
		for {
			if !pane.enabled {
				break
			}
			pane.out(Outgoing{})
			time.Sleep(time.Second)
		}
	}()

	go pane.listen()

	return pane
}
示例#8
0
func CreateSwitchDevice(driver ninja.Driver, info *model.Device, conn *ninja.Connection) (*SwitchDevice, error) {

	d := &SwitchDevice{
		baseDevice: baseDevice{
			conn:   conn,
			driver: driver,
			log:    logger.GetLogger("SwitchDevice - " + *info.Name),
			info:   info,
		},
	}

	err := conn.ExportDevice(d)
	if err != nil {
		d.log.Fatalf("Failed to export device %s: %s", *info.Name, err)
	}

	d.onOffChannel = channels.NewOnOffChannel(d)
	d.conn.ExportChannel(d, d.onOffChannel, "on-off")
	if err != nil {
		d.log.Fatalf("Failed to export on-off channel: %s", err)
	}

	d.log.Infof("Created")

	return d, nil
}
示例#9
0
// this function will always return a logger that can be used even if the
// support object has not been initialized in the correct sequence or with
// the correct arguments.
func safeLog(m *ModuleSupport, info *model.Module) *logger.Logger {
	if m == nil || m.Log == nil {
		return logger.GetLogger(fmt.Sprintf("%s.module", safeID(info)))
	} else {
		return m.Log
	}
}
func NewSystemPane(conn *ninja.Connection) Pane {

	pane := &SystemPane{
		log:   logger.GetLogger("SystemPane"),
		code:  "0000",
		color: "green",
	}

	status := conn.GetServiceClient("$device/:deviceId/component/:componentId")
	status.OnEvent("status", func(statusEvent *StatusEvent, values map[string]string) bool {
		if deviceId, ok := values["deviceId"]; !ok {
			return true
		} else if deviceId != config.Serial() {
			return true
		} else {
			params, _ := json.Marshal(statusEvent)
			pane.log.Infof("$device/%s/component/%s - %s", deviceId, values["componentId"], params)
			pane.code = statusEvent.Code
			pane.color = statusEvent.Color
			if pane.color == "" {
				pane.color = "green"
			}
			return true
		}
	})

	return pane
}
示例#11
0
func NewLifxDriver() {
	d := &LifxDriver{
		log:     logger.GetLogger(info.Name),
		client:  lifx.NewClient(),
		devices: make(map[string]*lifxDevice),
	}

	conn, err := ninja.Connect(info.ID)
	if err != nil {
		d.log.Fatalf("Failed to connect to MQTT: %s", err)
	}

	err = conn.ExportDriver(d)

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

	go func() {

		sub := d.client.Subscribe()

		for {

			event := <-sub.Events

			switch evnt := event.(type) {
			case *lifx.Bulb:
				if isUnique(evnt) {
					d.log.Infof("creating new light")
					_, err := d.newLight(evnt)
					if err != nil {
						d.log.HandleErrorf(err, "Error creating light instance")
					}
					seenlights = append(seenlights, evnt) //TODO remove bulbs that haven't been seen in a while?
					err = d.client.GetBulbState(evnt)

					if err != nil {
						d.log.Warningf("unable to intiate bulb state request %s", err)
					}
				}
			case *lifx.LightSensorState:
				// handle these vents for each bulb
				if d.devices[evnt.GetLifxAddress()] != nil {
					d.devices[evnt.GetLifxAddress()].illuminance.SendState(float64(evnt.Lux))
				}

			default:
				d.log.Infof("Event %v", event)
			}

		}

	}()

	go d.publishSensorData()

	d.conn = conn
}
示例#12
0
func main() {

	client.Start()

	s := make(chan os.Signal, 1)
	signal.Notify(s, os.Interrupt, os.Kill)
	logger.GetLogger("Client").Infof("Got signal: %v", <-s)
}
func (m *DeviceManager) PostConstruct() error {
	m.log = logger.GetLogger("DeviceManager")
	err := m.Start()
	if err != nil {
		return err
	}
	return nil
}
示例#14
0
func StartSonosDriver() {
	d := &sonosDriver{
		log:     logger.GetLogger(info.Name),
		players: make(map[string]*sonosZonePlayer),
	}

	conn, err := ninja.Connect(info.ID)
	if err != nil {
		d.log.Fatalf("Failed to connect to MQTT: %s", err)
	}

	err = conn.ExportDriver(d)

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

	if nil != err {
		nlog.HandleError(err, "Could not locate interface to bind to")
	}

	d.reactor = sonos.MakeReactor(EventingPort)

	go func() {
		events := d.reactor.Channel()

		d.log.Infof("waiting for events.")

		for {
			event := <-events

			switch v := event.(type) {
			case upnp.MusicServicesEvent: // this cuts down the events by a factor of 4
				d.log.Infof("processing event %T", v)

				// because event is a big ball of string it is easier to just iterate over all players
				// and update them all when an event occurs
				for id, player := range d.players {
					d.log.Infof("Updating state for %s", id)
					player.updateState()
				}

			}

			// switch v := event.(type) {
			// case upnp.RenderingControlEvent:
			// 	d.log.Infof(spew.Sprintf("Volume %v", v.LastChange.InstanceID.Volume))
			// case upnp.AVTransportEvent:
			// 	d.log.Infof(spew.Sprintf("TransportState %v", v.LastChange.InstanceID.TransportState))
			// }

			//spew.Dump(event)

		}
	}()

	d.conn = conn
}
func NewMatrix(pane pane) *Matrix {

	matrix := &Matrix{
		log:          logger.GetLogger("Matrix"),
		Disconnected: make(chan bool, 1),
		pane:         pane,
	}

	return matrix
}
示例#16
0
func newBaseModel(idType string, obj interface{}) baseModel {
	objType := reflect.TypeOf(obj)

	return baseModel{
		syncing:     &sync.WaitGroup{},
		idType:      idType,
		objType:     objType,
		log:         logger.GetLogger(objType.Name() + "Model"),
		entityLocks: make(map[string]*sync.Mutex),
	}
}
示例#17
0
func NewHueDriver() {
	d := &HueDriver{
		log: logger.GetLogger(info.Name),
	}

	conn, err := ninja.Connect(info.ID)
	d.conn = conn
	if err != nil {
		d.log.Fatalf("Failed to connect to MQTT: %s", err)
	}

	err = conn.ExportDriver(d)
	if err != nil {
		d.log.Fatalf("Failed to export driver: %s", err)
	}
}
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
}
func NewOnOffPane(offImage string, onImage string, onStateChange func(bool), conn *ninja.Connection, thingType string) *OnOffPane {

	log := logger.GetLogger("OnOffPane")

	pane := &OnOffPane{
		onImage:       util.LoadImage(onImage),
		offImage:      util.LoadImage(offImage),
		onStateChange: onStateChange,
		log:           log,
		devices:       make([]*ninja.ServiceClient, 0),
		conn:          conn,
	}

	listening := make(map[string]bool)

	getChannelServicesContinuous(thingType, "on-off", nil, func(clients []*ninja.ServiceClient, err error) {
		if err != nil {
			log.Infof("Failed to update devices: %s", err)
		} else {
			log.Infof("Pane got %d on/off devices", len(clients))
			pane.devices = clients

			for _, device := range clients {
				if _, ok := listening[device.Topic]; !ok {
					listening[device.Topic] = true

					device.OnEvent("state", func(state *bool, topicKeys map[string]string) bool {
						log.Debugf("Got on-off state: %t", *state)

						if time.Since(pane.lastTap) > 1*time.Second {
							pane.state = *state
						}

						return true
					})
				}
			}
		}
	})

	return pane
}
示例#20
0
func NewPlayer(driver *sonosDriver, conn *ninja.Connection, zoneInfo *sonosZoneInfo) (*sonosZonePlayer, error) {

	id := zoneInfo.attributes.CurrentZoneGroupID
	name := zoneInfo.attributes.CurrentZoneGroupName

	nlog.Infof("Making media player with ID: %s Label: %s")

	player, err := devices.CreateMediaPlayerDevice(driver, &model.Device{
		NaturalID:     id,
		NaturalIDType: "sonos",
		Name:          &name,
		Signatures: &map[string]string{
			"ninja:manufacturer": "Sonos",
			"ninja:productName":  "Sonos Player",
			"ninja:productType":  "MediaPlayer",
			"ninja:thingType":    "mediaplayer",
		},
	}, conn)

	if err != nil {
		nlog.FatalError(err, "Failed to create media player device")
	}

	// At the moment I am using the first player in that zone
	// i need to know how this looks in a multi player situation.
	sonosUnit := zoneInfo.players[0]

	sp := &sonosZonePlayer{sonosUnit, logger.GetLogger("sonosZonePlayer"), player, time.Now()}

	err = sp.bindMethods()
	if err != nil {
		sp.log.FatalError(err, "Failed to bind channels to sonos device")
	}

	err = sp.updateState()

	if err != nil {
		sp.log.FatalError(err, "Failed to get initial device state")
	}

	return sp, nil
}
示例#21
0
func CreateMediaPlayerDevice(driver ninja.Driver, info *model.Device, conn *ninja.Connection) (*MediaPlayerDevice, error) {

	d := &MediaPlayerDevice{
		baseDevice: baseDevice{
			conn:   conn,
			driver: driver,
			log:    logger.GetLogger("MediaPlayerDevice - " + *info.Name),
			info:   info,
		},
	}

	err := conn.ExportDevice(d)
	if err != nil {
		d.log.Fatalf("Failed to export device %s: %s", *info.Name, err)
	}

	d.log.Infof("Created")

	return d, nil
}
func newSecurityLight(config SecurityLightConfig) (*securityLight, error) {

	l := &securityLight{
		config:        config,
		log:           logger.GetLogger("[Name: " + config.Name + "]"),
		subscriptions: make(map[string]*bus.Subscription),
		onOffServices: []*ninja.ServiceClient{},
	}

	l.timeout = time.AfterFunc(time.Minute, l.turnOffLights)
	l.timeout.Stop()

	l.log.Infof("start(%+v)", config)

	// start listening to sensors
	for _, sensorID := range config.Sensors {
		sub, err := listenToSensor(sensorID, l.onSensor)
		if err == nil {
			if sub == nil {
				l.log.Fatalf("Got a nil subscription back for sensor id: %s", sensorID)
			} else {
				l.subscriptions[sensorID] = sub
			}
		} else {
			l.log.Warningf("Failed to subscribe to sensor %s: %s", sensorID, err)
		}
	}

	// Grab the on-off channels for the lights
	for _, lightID := range config.Lights {
		service, err := getOnOffChannelClient(lightID)
		if err == nil {
			l.onOffServices = append(l.onOffServices, service)
		} else {
			l.log.Warningf("Failed to get light %s on-off service: %s", lightID, err)
		}
	}

	return l, nil
}
示例#23
0
func NewDriver(config *ZStackConfig) (*Driver, error) {
	driver := &Driver{
		config:  config,
		devices: make(map[uint64]*Device),
	}

	err := driver.Init(info)
	if err != nil {
		log.Fatalf("Failed to initialize fake driver: %s", err)
	}
	log = driver.Log
	zigbee.SetLogger(logger.GetLogger(info.ID + ".backend"))

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

	userAgent := driver.Conn.GetServiceClient("$device/:deviceId/channel/user-agent")
	userAgent.OnEvent("pairing-requested", func(pairingRequest *events.PairingRequest, values map[string]string) bool {

		duration := uint32(pairingRequest.Duration)

		if duration > 254 {
			duration = 254
		}

		log.Infof("Pairing request received from %s for %d seconds", values["deviceId"], duration)

		if err := driver.EnableJoin(duration); err != nil {
			log.Warningf("Failed to enable joining: %s", err)
		}

		return true
	})

	return driver, nil

}
示例#24
0
func ResetDevice() error {

	log := logger.GetLogger("Gestic Reset")

	log.Infof("resetting gestic device")

	err := writetofile("/sys/kernel/debug/omap_mux/mii1_rxdv", "2f")

	if err != nil {
		return fmt.Errorf("Unable to reset gestic device: %v", err)
	}

	err = writetofile("/sys/class/gpio/export", "100")

	if err != nil {
		return fmt.Errorf("Unable to write to export pin: %v", err)
	}

	err = writetofile("/sys/class/gpio/gpio100/direction", "out")

	if err != nil {
		return fmt.Errorf("Unable to reset gestic device: %v", err)
	}

	err = writetofile("/sys/class/gpio/gpio100/value", "0")

	if err != nil {
		return fmt.Errorf("Unable to reset gestic device: %v", err)
	}

	err = writetofile("/sys/class/gpio/gpio100/value", "1")

	if err != nil {
		return fmt.Errorf("Unable to reset gestic device: %v", err)
	}
	return nil
}
示例#25
0
package main

// app-twitter Ninja Sphere app for Twitter (notifications)
// Lindsay Ward, July 2015 - https://github.com/lindsaymarkward/app-twitter

import (
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/support"
)

var log = logger.GetLogger(info.Name)

func main() {
	app := &TwitterApp{}

	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()
}
	"github.com/ninjasphere/go-ninja/bus"
	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"
)

var mocking = config.Bool(false, "mock")

// This isn't an example of good code. Fix it or ignore it, but don't copy it.

var lightsConfig map[string]SecurityLightConfig
var conn *ninja.Connection
var saveConfig func()
var thingModel *ninja.ServiceClient

var log = logger.GetLogger("service")
var lights = make(map[string]*securityLight)

var allThings []model.Thing

var started bool

var latitude, longitude float64

type sensor struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type light struct {
	ID   string `json:"id"`
示例#27
0
import (
	"os"
	"path/filepath"
	"reflect"
	"sync"
	"time"

	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"
	"github.com/ninjasphere/redigo/redis"
	"github.com/ninjasphere/sphere-go-homecloud/models"
)

var log = logger.GetLogger("HomeCloud")

var syncEnabled = config.Bool(true, "homecloud.sync.enabled")
var syncTimeout = config.MustDuration("homecloud.sync.timeout")

type HomeCloud struct {
	Conn         *ninja.Connection    `inject:""`
	Pool         *redis.Pool          `inject:""`
	ThingModel   *models.ThingModel   `inject:""`
	DeviceModel  *models.DeviceModel  `inject:""`
	ChannelModel *models.ChannelModel `inject:""`
	RoomModel    *models.RoomModel    `inject:""`
	ModuleModel  *models.ModuleModel  `inject:""`
	SiteModel    *models.SiteModel    `inject:""`
	log          *logger.Logger
}
示例#28
0
func (r *RestServer) PostConstruct() error {
	r.log = logger.GetLogger("RestServer")
	return r.Listen()
}
	Channels []Channel
}

type Channel struct {
	Protocol string `json:"protocol"`
	Name     string `json:"channel"`
	ID       string `json:"id"`
}*/

var sameRoomOnly = config.Bool(true, "homecloud.sameRoomOnly")

var conn *ninja.Connection
var tasks []*request
var thingModel *ninja.ServiceClient

var log = logger.GetLogger("ui")

type request struct {
	thingType string
	protocol  string
	filter    func(thing *model.Thing) bool
	cb        func([]*ninja.ServiceClient, error)
}

var roomID *string

func runTasks() {

	// Find this sphere's location, if we care..
	if sameRoomOnly {
		for _, thing := range allThings {
示例#30
0
package cloud

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

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

var log = logger.GetLogger("cloud")

var (
	AlreadyRegistered = errors.New("The userid is already registered")
	TagNotFound       = errors.New("The specified tag was not found.")
)

type Cloud interface {
	/**
	 * Registers a user.
	 */
	RegisterUser(name string, email string, password string) error

	/**
	 * Authenticates the user with the e-mail and password supplied, returns
	 * a token that can be used with the activate call.