示例#1
0
文件: main.go 项目: kienhung/gohome
func (self *Service) Run() error {
	// connect to modem
	devname := expandDevName()
	if devname == "" {
		log.Fatalln("Device not found")
	}
	conf := serial.Config{Name: devname, Baud: 115200}
	var err error
	modem, err = gogsmmodem.Open(&conf, false)
	if err != nil {
		return err
	}
	log.Println("Connected")

	log.Println("Checking message storage for unread")
	msgs, err := modem.ListMessages("ALL")
	if err == nil {
		for _, msg := range *msgs {
			if msg.Status == "REC UNREAD" {
				fmt.Printf("Message from %s: %s\n", msg.Telephone, msg.Body)
				services.SendQuery(msg.Body, "sms", msg.Telephone, "alert")
			}
			// delete - any unread have been read
			modem.DeleteMessage(msg.Index)
		}
	}

	log.Println("Ready")

	events := services.Subscriber.FilteredChannel("alert")
	for {
		select {
		case ev := <-events:
			if ev.Target() == "sms" {
				sendMessage(ev)
			}

		case p := <-modem.OOB:
			log.Printf("Received: %#v\n", p)
			switch p := p.(type) {
			case gogsmmodem.MessageNotification:
				msg, err := modem.GetMessage(p.Index)
				if err == nil {
					fmt.Printf("Message from %s: %s\n", msg.Telephone, msg.Body)
					services.SendQuery(msg.Body, "sms", msg.Telephone, "alert")
					modem.DeleteMessage(p.Index)
				}
			}

		}
	}
	return nil
}
示例#2
0
文件: main.go 项目: kienhung/gohome
// Run the service
func (self *Service) Run() error {
	client, err := NewClient()
	if err != nil {
		log.Fatal(err)
	}

	presence := map[string]string{}

	go func() {
		for {
			chat := client.Recv()
			switch v := chat.(type) {
			case xmpp.Chat:
				if v.Text == "" || IsSelf(v.Remote) {
					continue
				}

				log.Println("Query:", v.Text)
				services.SendQuery(v.Text, "jabber", v.Remote, "alert")
			case xmpp.Presence:
				// ignore self
				if !IsSelf(v.From) {
					if presence[v.From] != v.Show {
						presence[v.From] = v.Show
						log.Println("Presence:", v.From, v.Show)
					}
				}
			}
		}
	}()

	events := services.Subscriber.FilteredChannel("alert")
	for ev := range events {
		if ev.Target() != "jabber" {
			continue
		}

		remote := ev.StringField("remote")
		source := ev.Source()
		message := ev.StringField("message")
		if remote == "" {
			// pick first match
			keys := []string{}
			for remote := range presence {
				keys = append(keys, remote)
			}
			sort.Strings(keys)

			if len(keys) == 0 {
				log.Println("No jabber users online to send to")
				continue
			}
			remote = keys[0]
		}
		text := message
		if source != "" {
			if strings.Contains(message, "\n") {
				text = fmt.Sprintf("%s>\n%s", source, message)
			} else {
				text = fmt.Sprintf("%s> %s", source, message)
			}
		}
		client.Send(xmpp.Chat{Remote: remote, Type: "chat", Text: text})
		log.Printf("Sent '%s' to %s", text, remote)
	}
	return nil
}