code.pfad.fr/gohmekit@v0.2.1/doc_test.go (about)

     1  package gohmekit_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  	"strconv"
     9  	"time"
    10  
    11  	"code.pfad.fr/gohmekit/contrib/shelly"
    12  	"code.pfad.fr/gohmekit/discovery"
    13  	"code.pfad.fr/gohmekit/hapip"
    14  	"code.pfad.fr/gohmekit/hapip/characteristic/service/accessory"
    15  	"code.pfad.fr/gohmekit/pairing"
    16  	"code.pfad.fr/gohmekit/storage"
    17  )
    18  
    19  func Example() {
    20  	// store the state in a json file (secret key, pin, paired devices...)
    21  	jsonFile, err := storage.NewJSONFile("db.json")
    22  	if err != nil {
    23  		fmt.Printf("could not get json file storage: %v\n", err)
    24  		return
    25  	}
    26  
    27  	shellyPlug, _ := shelly.NewPlug("http://localhost/")
    28  
    29  	// create an accessory handler.
    30  	port := 51821 // same port used by homebridge (can be changed)
    31  	accessoryServer := hapip.PrepareServer(
    32  		&http.Server{Addr: ":" + strconv.Itoa(port)},
    33  		map[uint16]hapip.Accessory{
    34  			// If multiple accessories are provided, the number 1 must be a bridge
    35  			// (which is required per the spec to have the service.AccessoryInformation).
    36  			1: accessory.Basic{
    37  				Name: "Gohmebridge",
    38  				Identify: func(bool) error {
    39  					fmt.Println("TODO: blink a led or make a tone (not paired yet)")
    40  					return errors.New("identify is not implemented")
    41  				},
    42  
    43  				HAPProtocolVersion: "1.1.0",
    44  			},
    45  			// bridged devices
    46  			2: shellyPlug,
    47  		},
    48  	)
    49  
    50  	// pairing server will manage connection encryption
    51  	// and handle the decrypted requests to the given accessory server.
    52  	pairingServer := pairing.NewServer(accessoryServer, jsonFile, jsonFile,
    53  		pairing.WithIdentify(func() {
    54  			fmt.Println("TODO: blink a led or make a tone (accessory is paired)")
    55  		}),
    56  	)
    57  
    58  	// announce the accessory as a bridge via bonjour (zeroconf)
    59  	stopDiscovery, err := jsonFile.DiscoveryService(
    60  		"gohmebridge",
    61  		port,
    62  		discovery.Bridge,
    63  	).Announce(context.Background())
    64  	if err != nil {
    65  		fmt.Printf("could not start announcing: %v\n", err)
    66  		return
    67  	}
    68  	defer stopDiscovery()
    69  
    70  	// start serving
    71  	go pairingServer.ListenAndServe() //nolint:errcheck
    72  
    73  	time.Sleep(10 * time.Millisecond)
    74  
    75  	// Output:
    76  }