go-xmpp/cmd/xmpp_component/xmpp_component.go

87 lines
2.0 KiB
Go
Raw Normal View History

2018-01-11 13:15:54 -08:00
package main
2018-01-12 10:08:47 -08:00
import (
2018-01-15 03:28:34 -08:00
"encoding/xml"
2018-01-12 10:08:47 -08:00
"fmt"
"fluux.io/xmpp"
)
2018-01-11 13:15:54 -08:00
func main() {
2018-01-14 07:54:12 -08:00
component := MyComponent{Name: "MQTT Component", Category: "gateway", Type: "mqtt"}
component.xmpp = &xmpp.Component{Host: "mqtt.localhost", Secret: "mypass"}
component.xmpp.Connect("localhost:8888")
2018-01-12 10:08:47 -08:00
for {
2018-01-14 07:54:12 -08:00
packet, err := component.xmpp.ReadPacket()
2018-01-12 10:08:47 -08:00
if err != nil {
2018-01-13 08:46:10 -08:00
fmt.Println("read error", err)
2018-01-12 10:08:47 -08:00
return
}
2018-01-13 09:50:17 -08:00
switch p := packet.(type) {
case xmpp.IQ:
2018-01-13 10:27:46 -08:00
switch inner := p.Payload.(type) {
case *xmpp.Node:
2018-01-15 03:28:34 -08:00
fmt.Printf("%q\n", inner)
data, err := xml.Marshal(inner)
if err != nil {
fmt.Println("cannot marshall payload")
}
fmt.Println("data=", string(data))
2018-01-14 07:54:12 -08:00
component.processIQ(p.Type, p.Id, p.From, inner)
2018-01-13 10:27:46 -08:00
default:
fmt.Println("default")
2018-01-13 10:14:26 -08:00
}
2018-01-13 09:50:17 -08:00
default:
fmt.Println("Packet unhandled packet:", packet)
}
2018-01-12 10:08:47 -08:00
}
2018-01-11 13:15:54 -08:00
}
2018-01-14 07:54:12 -08:00
const (
NSDiscoInfo = "http://jabber.org/protocol/disco#info"
)
type MyComponent struct {
Name string
// Typical categories and types: https://xmpp.org/registrar/disco-categories.html
Category string
Type string
xmpp *xmpp.Component
}
func (c MyComponent) processIQ(iqType, id, from string, inner *xmpp.Node) {
fmt.Println("Node:", inner.XMLName.Space, inner.XMLName.Local)
switch inner.XMLName.Space + " " + iqType {
case NSDiscoInfo + " get":
fmt.Println("Send Disco Info")
result := fmt.Sprintf(`<iq type='result'
from='%s'
to='%s'
id='%s'>
<query xmlns='http://jabber.org/protocol/disco#info'>
<identity
category='%s'
type='%s'
name='%s'/>
<feature var='http://jabber.org/protocol/disco#info'/>
<feature var='http://jabber.org/protocol/disco#items'/>
</query>
</iq>`, c.xmpp.Host, from, id, c.Category, c.Type, c.Name)
c.xmpp.Send(result)
default:
iqErr := fmt.Sprintf(`<iq type='error'
from='%s'
to='%s'
id='%s'>
<error type="cancel" code="501">
<feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
</error>
</iq>`, c.xmpp.Host, from, id)
c.xmpp.Send(iqErr)
}
}