59 lines
1017 B
Go
59 lines
1017 B
Go
|
package pubsub
|
||
|
|
||
|
import (
|
||
|
"time"
|
||
|
|
||
|
telemetrypb "git.wntrmute.dev/kyle/sensenet/proto"
|
||
|
"google.golang.org/protobuf/proto"
|
||
|
goczmq "gopkg.in/zeromq/goczmq.v4"
|
||
|
)
|
||
|
|
||
|
const singleFrame = 0
|
||
|
|
||
|
type Publisher struct {
|
||
|
addr string
|
||
|
sock *goczmq.Sock
|
||
|
}
|
||
|
|
||
|
func NewPublisher(addr string) (*Publisher, error) {
|
||
|
pub := &Publisher{
|
||
|
addr: addr,
|
||
|
sock: goczmq.NewSock(goczmq.Pub),
|
||
|
}
|
||
|
|
||
|
pub.Conflate(1)
|
||
|
err := pub.connect()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return pub, nil
|
||
|
}
|
||
|
|
||
|
func (pub *Publisher) connect() error {
|
||
|
return pub.sock.Connect(pub.addr)
|
||
|
}
|
||
|
|
||
|
func (pub *Publisher) Conflate(n int) {
|
||
|
pub.sock.SetConflate(n)
|
||
|
}
|
||
|
|
||
|
func (pub *Publisher) Transmit(topic string, data []byte) error {
|
||
|
packet, err := genPacket(topic, data)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return pub.sock.SendFrame(packet, singleFrame)
|
||
|
}
|
||
|
|
||
|
func genPacket(topic string, payload []byte) ([]byte, error) {
|
||
|
packet := &telemetrypb.Packet{
|
||
|
Topic: topic,
|
||
|
Timestamp: uint64(time.Now().Unix()),
|
||
|
Payload: payload,
|
||
|
}
|
||
|
|
||
|
return proto.Marshal(packet)
|
||
|
}
|