// SendNotification sends a JSON-RPC notification func (c *Codec) SendNotification(client bus.Bus, topic string, payload ...interface{}) error { notification := &serverRequest{ Version: Version, Time: makeTimestamp(), } jsonPayload, err := json.Marshal(payload) if err != nil { return fmt.Errorf("Failed to marshall rpc notification: %s", err) } rawPayload := json.RawMessage(jsonPayload) notification.Params = &rawPayload jsonNotification, err := json.Marshal(notification) if !strings.HasSuffix(topic, "/module/status") { log.Debugf("< Outgoing to %s : %s", topic, jsonNotification) } client.Publish(topic, jsonNotification) return nil }
// bridgeMqtt connects one mqtt broker to another. Shouldn't probably be doing this. But whatever. func (c *client) bridgeMqtt(from, to bus.Bus, masterToSlave bool, topics []string) { onMessage := func(topic string, payload []byte) { if masterToSlave { // This is a message from master, clear the timeout c.masterReceiveTimeout.Reset(orphanTimeout) } if payload[0] != '{' { log.Warningf("Invalid payload (should be a json-rpc object): %s", payload) return } var msg meshMessage json.Unmarshal(payload, &msg) interesting := false if masterToSlave { // Interesting if it's from the master or one of the other slaves interesting = msg.Source == nil || (*msg.Source != config.Serial()) } else { // Interesting if it's from me interesting = msg.Source == nil } log.Infof("Mesh master2slave:%t topic:%s interesting:%t", masterToSlave, topic, interesting) if interesting { if msg.Source == nil { if masterToSlave { payload = addMeshSource(config.MustString("masterNodeId"), payload) } else { payload = addMeshSource(config.Serial(), payload) } } to.Publish(topic, payload) } } for _, topic := range topics { _, err := from.Subscribe(topic, onMessage) if err != nil { log.Fatalf("Failed to subscribe to topic %s when bridging to master: %s", topic, err) } } }
func (c *CodecRequest) writeServerResponse(client bus.Bus, res *serverResponse) { // Id is null for notifications and they don't have a response. if c.request.ID != nil { payload, err := json.Marshal(res) log.Debugf("< Outgoing to %s : %s", c.topic+"/reply", payload) if err != nil { log.Errorf("Failed to marshall rpc response: %s", err) return } client.Publish(c.topic+"/reply", payload) if err != nil { log.Errorf("Failed to write rpc response to MQTT: %s", err) return } } }