예제 #1
0
func (o *Observe) Register(device client.Client) bool {
	registered := false

	conn := []string{device.Host, device.Port}
	keyID := client.GenerateId(conn)

	if _, ok := GetRegClientByKey(keyID); ok != nil {
		return false
	}

	resources, err := Discover(device)
	if err != nil {
		log.Printf("Do not find device: %s\n", err)
		return false
	}
	coreLinks := resources.(string)
	if coreLinks == "" {
		return false
	}
	if endPoints, ok := core.Parse(coreLinks); ok {
		req := coap.Message{
			Type: coap.NonConfirmable,
			Code: coap.GET,
		}
		req.AddOption(coap.Observe, 0)

		RegDev := &Registered{}
		remoteAddr, _ := net.ResolveUDPAddr(Net, strings.Join(conn, ":"))

		for _, res := range endPoints {
			link := res.GetLink()
			if len(link) > 1 {
				req.Token = []byte(utils.GenToken(8))
				req.MessageID = utils.GenMessageID()
				req.SetPathString(link)

				err := coap.Transmit(o.Conn, remoteAddr, req)
				if err != nil {
					log.Printf("Error sending request: %v", err)
				}

				RegDev.Req = append(RegDev.Req, req)
				log.Printf("REGISTER Resource: %s, Host: %s, Port: %d\n", link, remoteAddr.IP, remoteAddr.Port)
				ValidTokens[string(req.Token)] = true
			}
		}
		if len(RegDev.Req) > 0 {
			RegDev.Id = keyID
			RegDev.RemoteAddr = remoteAddr
			RegRes = append(RegRes, *RegDev)
			registered = true
		}
	}

	return registered
}
예제 #2
0
func RemoveUnObservable(m *coap.Message, from *net.UDPAddr) {
	RemoveToken(m.Token)

	conn := []string{fmt.Sprint(from.IP), fmt.Sprint(from.Port)}
	keyID := client.GenerateId(conn)
	id, client := GetRegClientByKey(keyID)
	if id >= 0 {
		for i, reg := range client.Req {
			if string(reg.Token) == string(m.Token) {
				client.Req = append(client.Req[:i], client.Req[i+1:]...)
			}
		}
	}
}