Skip to content

Commit

Permalink
Lots...
Browse files Browse the repository at this point in the history
  • Loading branch information
hilli committed May 18, 2023
1 parent 2e71dd0 commit bd7e961
Show file tree
Hide file tree
Showing 15 changed files with 910 additions and 58 deletions.
4 changes: 3 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
KEFW2_IP=10.0.0.93
KEFW2_IP=10.0.0.143
DEBUG=true
HOMEKIT_PIN=66600666
16 changes: 16 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch kefw2 config speaker add",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "cmd/kefw2/kefw2.go",
"args": ["config", "speaker", "add", "10.0.0.93"]
}
]
}
122 changes: 103 additions & 19 deletions cmd/kef-virtual-hub/kef-virtual-hub.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
package main

import (
"context"
"fmt"
"hash/fnv"
"log"
"os"
"os/signal"
"syscall"

log "github.com/sirupsen/logrus"

"github.com/brutella/hap"
"github.com/brutella/hap/accessory"
"github.com/brutella/hap/characteristic"
haplog "github.com/brutella/hap/log"
"github.com/brutella/hap/service"
"github.com/hilli/go-kef-w2/kefw2"
"github.com/joho/godotenv"
)
Expand All @@ -22,35 +30,111 @@ func main() {
if err != nil {
log.Fatal("Error loading .env file")
}
if os.Getenv("DEBUG") == "true" {
log.SetLevel(log.DebugLevel)
log.SetReportCaller(true)
// dnslog.Debug.Enable() // Very noisy
haplog.Debug.Enable()
}

bridgeInfo := accessory.Info{
Name: "KEF Virtual Hub",
Manufacturer: "Jens Hilligsøe <[email protected]>",
Model: "1.0.0",
}
myBridge := accessory.NewBridge(bridgeInfo)

// switchInfo := accessory.Info{
// Name: "KEF Virtual Hub",
// Manufacturer: "Jens Hilligsøe <[email protected]>",
// Model: "1.0.0",
// }
// Create a new file store
fs := hap.NewFsStore("kef-virtual-hub")

// Create speaker
mySpeaker, err := kefw2.NewSpeaker(os.Getenv("KEFW2_IP"))

// Create Speaker Service
// s := service.NewSpeaker()
if err != nil {
panic(err)
}
log.Debug(mySpeaker)

// Create Accessory
a := accessory.New(accessory.Info{
Name: "KEF W2",
speakerInfo := accessory.Info{
Name: "Virtual " + mySpeaker.Name,
Manufacturer: "KEF",
Model: mySpeaker.Model,
}, byte(34))
Firmware: mySpeaker.FirmwareVersion,
SerialNumber: mySpeaker.MacAddress,
}
a := accessory.New(speakerInfo, byte(34))

// Create Speaker Service
s := service.NewSpeaker()

// Add service to Accessory
// a.AddS(service.S(s))

// hash the speaker id to a uint64
// so the speaker remains the same
a.AddS(s.S)
vol := characteristic.NewVolume()
vol.Description = "Volume"
s.AddC(vol.C)
mute := characteristic.NewMute()
mute.Description = "Mute"
s.AddC(mute.C)
fmt.Printf("Service: %+v\n", s.Cs[1])

// updateCurrentState := func() {
// state, err := mySpeaker.Source()
// if err != nil {
// log.Error(err)
// }
// // switch st
// log.Debug(state)
// }

s.Mute.OnValueRemoteUpdate(func(state bool) {
if state {
err := mySpeaker.Mute()
if err != nil {
log.Error(err)
}
} else {
err := mySpeaker.Unmute()
if err != nil {
log.Error(err)
}
}
})

// s.Volume.OnValueRemoteUpdate(func(state int) {
// err := mySpeaker.SetVolume(state)
// if err != nil {
// log.Error(err)
// }
// })
// cap := characteristic.NewVolumeSelector()

// hash the speaker id to a uint64 so the speaker remains the same across cold restarts
h := fnv.New64a()
h.Write([]byte(mySpeaker.Id))
a.Id = h.Sum64()

hap.NewServer(fs, a)
}

log.Debug(fmt.Sprintf("%+v", a))

server, err := hap.NewServer(fs, myBridge.A, a)
if err != nil {
panic(err)
}
server.Pin = os.Getenv("HOMEKIT_PIN")

// Setup a listener for interrupts and SIGTERM signals
// to stop the server.
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)

ctx, cancel := context.WithCancel(context.Background())
go func() {
<-c
// Stop delivering signals.
signal.Stop(c)
// Cancel the context to stop the server.
cancel()
}()

server.ListenAndServe(ctx)
}
31 changes: 31 additions & 0 deletions cmd/kefw2/cmd/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cmd

import (
"github.com/spf13/cobra"
)

// configCmd represents the config command
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Configure kefw2",
Long: `kefw2 needs to be configured with the IP address of your W2 speaker.
This will do it.`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help() // Just display help for bare config command
},
}

func init() {
// rootCmd.AddCommand(configCmd)
ConfigCmd.AddCommand(speakerCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// configCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// configCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
69 changes: 69 additions & 0 deletions cmd/kefw2/cmd/config_speaker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cmd

import (
"fmt"

"github.com/hilli/go-kef-w2/kefw2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var speakerCmd = &cobra.Command{
Use: "speaker",
Short: "Manage speakers: add, remove, list",
Long: `Manage speakers`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}

func init() {
speakerCmd.AddCommand(speakerAddCmd)
speakerCmd.AddCommand(speakerRemoveCmd)
speakerCmd.AddCommand(speakerListCmd)
}

var speakerAddCmd = &cobra.Command{
Use: "add",
Short: "Add a speaker",
Long: `Add a speaker`,
Run: func(cmd *cobra.Command, args []string) {
if err := addSpeaker(args[0]); err != nil {
fmt.Printf("Error adding speaker (%s): %s\n", args[0], err)
}
},
}

var speakerRemoveCmd = &cobra.Command{
Use: "remove",
Short: "Remove a speaker",
Long: `Remove a speaker`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("remove speaker")
},
}

var speakerListCmd = &cobra.Command{
Use: "list",
Short: "List speakers",
Long: `List speakers`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Speakers:")
for _, speaker := range speakers {
fmt.Printf("- %s\n", speaker.Name)
}
},
}

func addSpeaker(host string) (err error) {
speaker, err := kefw2.NewSpeaker(host)
if err != nil {
fmt.Println(err)
return
}
speakers = append(speakers, speaker)
viper.Set("speakers", speakers)
fmt.Printf("Added speaker: %s (%s)\n", speaker.Name, speaker.IPAddress)
viper.WriteConfig()
return
}
107 changes: 107 additions & 0 deletions cmd/kefw2/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
Copyright © 2023 Jens Hilligsøe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
"fmt"
"os"
"path/filepath"

"github.com/hilli/go-kef-w2/kefw2"
log "github.com/sirupsen/logrus"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
cfgFile string
speakers []kefw2.KEFSpeaker
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "kefw2",
Short: "kefw2 is a CLI tool for controlling KEF's W2 platform speakers",
Long: ``,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
cfgPath := filepath.Join(home, ".config", "kefw2")
err = os.MkdirAll(cfgPath, 0755)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}

viper.SetConfigType("yaml")
viper.SetConfigName("kefw2")
viper.SetConfigFile(filepath.Join(cfgPath, "kefw2.yaml"))

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", viper.ConfigFileUsed(), "config file (default is "+viper.ConfigFileUsed()+")")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

rootCmd.AddCommand(ConfigCmd)
// rootCmd.AddCommand(config.SpeakerCmd)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
}

viper.SetEnvPrefix("kefw2")
viper.AutomaticEnv() // read in environment variables that match KEFW2_*

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
if err := viper.UnmarshalKey("speakers", &speakers); err != nil {
log.Fatal(err)
}
}
Loading

0 comments on commit bd7e961

Please sign in to comment.