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 }
func ConnectLIFX() { client = lifx.NewClient() err := client.StartDiscovery() if err != nil { log.Fatalf("Could not find bulb %s", err) } sub := client.Subscribe() for { event := <-sub.Events switch event := event.(type) { case *lifx.Gateway: case *lifx.Bulb: updateBulb(event) event.SetStateHandler(func(newState *lifx.BulbState) { log.Println("Updated", newState) updateBulb(event) }) default: log.Printf("Event %v", event) } } }
func realMain() int { c := lifx.NewClient() err := c.StartDiscovery() if err != nil { log.Fatalf("Woops %s", err) } go func() { log.Printf("Subscribing to changes") sub := c.Subscribe() for { event := <-sub.Events switch event := event.(type) { case *lifx.Gateway: log.Printf("Gateway Update %s", event.GetLifxAddress()) case *lifx.Bulb: log.Printf("Bulb Update %s", event.GetLifxAddress()) log.Printf(spew.Sprintf("%+v", event)) event.SetStateHandler(buildHandler(event.GetLifxAddress())) case *lifx.LightSensorState: log.Printf("Light Sensor Update %s %f", event.GetLifxAddress(), event.Lux) default: log.Printf("Event %+v", event) } } }() log.Printf("Looping") for { time.Sleep(5 * time.Second) log.Printf("LightsOn") c.LightsOn() time.Sleep(5 * time.Second) for _, bulb := range c.GetBulbs() { time.Sleep(5 * time.Second) log.Printf("purple %s", bulb.GetLifxAddress()) c.LightColour(bulb, 0xcc15, 0xffff, 0x1f4, 0, 0x0513) time.Sleep(200 * time.Millisecond) c.GetBulbState(bulb) c.GetAmbientLight(bulb) time.Sleep(5 * time.Second) // bright white temps := []int{0, 1000, 2000, 3000, 4000, 5000, 6000} for _, val := range temps { time.Sleep(5 * time.Second) log.Printf("white %s %d", bulb.GetLifxAddress(), val) c.LightColour(bulb, 0, 0, 0x8000, uint16(val), 0x0513) time.Sleep(200 * time.Millisecond) c.GetBulbState(bulb) c.GetAmbientLight(bulb) } } time.Sleep(5 * time.Second) log.Printf("LightsOff") c.LightsOff() } return 0 }