github.com/gkstretton/dark/services/goo@v0.0.0-20231114224855-2d1a2074d446/keyvalue/handlers.go (about)

     1  package keyvalue
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/gkstretton/dark/services/goo/mqtt"
     8  )
     9  
    10  var respDelay = time.Millisecond * time.Duration(200)
    11  
    12  func setCallback(topic string, payload []byte) {
    13  	key := getLastTopicValue(topic)
    14  
    15  	err := setKeyValue(key, payload)
    16  	if err != nil {
    17  		fmt.Printf("failed to set key %s to %v: %v\n", key, payload, err)
    18  		return
    19  	}
    20  }
    21  
    22  func reqCallback(topic string, payload []byte) {
    23  	key := getLastTopicValue(topic)
    24  	go func() {
    25  		time.Sleep(respDelay)
    26  		sendToSubs(key)
    27  	}()
    28  }
    29  
    30  func sendToSubs(key string) {
    31  	value, err := getKeyValue(key)
    32  	if err != nil {
    33  		// fmt.Printf("error getting value for key %s: %v\n", key, err)
    34  		value = []byte{}
    35  	}
    36  	err = mqtt.Publish(TOPIC_GET_RESP+key, value)
    37  	if err != nil {
    38  		fmt.Printf("error publishing value for key %s: %v\n", key, err)
    39  	}
    40  }