Example #1
0
// messageHandler is called when a new message arrives
func handleMessage(client *MQTT.Client, msg MQTT.Message) {

	// Unmarshal JSON to RxPacket
	var packet shared.RxPacket
	err := json.Unmarshal(msg.Payload(), &packet)
	if err != nil {
		log.WithField("topic", msg.Topic()).WithError(err).Warn("Failed to unmarshal JSON.")
		return
	}

	// Filter messages by gateway
	if gateway != "" && packet.GatewayEui != gateway {
		return
	}

	// Decode payload
	data, err := base64.StdEncoding.DecodeString(packet.Data)
	if err != nil {
		log.WithField("topic", msg.Topic()).WithError(err).Warn("Failed to decode Payload.")
		return
	}

	ctx := log.WithFields(log.Fields{
		"devAddr": packet.NodeEui,
	})

	if showMeta {
		ctx = ctx.WithFields(log.Fields{
			"gatewayEui": packet.GatewayEui,
			"time":       packet.Time,
			"frequency":  *packet.Frequency,
			"dataRate":   packet.DataRate,
			"rssi":       *packet.Rssi,
			"snr":        *packet.Snr,
		})
	}

	if showRaw {
		ctx = ctx.WithField("data", fmt.Sprintf("%x", data))
	}

	if showTiming {
		rawData, err := base64.StdEncoding.DecodeString(packet.Data)
		if err == nil {
			airtime, err := util.CalculatePacketTime(len(rawData), packet.DataRate)
			if err == nil {
				ctx = ctx.WithField("airtime", fmt.Sprintf("%.1f ms", airtime))
			}
		}
	}

	// Check for unprintable characters
	unprintable, _ := regexp.Compile(`[^[:print:]]`)
	if unprintable.Match(data) {
		ctx.Debug("Received Message")
	} else {
		ctx.WithField("message", fmt.Sprintf("%s", data)).Info("Received Message")
	}

}
Example #2
0
// HandleWS handles the ws server upgrading.
func (s *Server) HandleWS(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	gameID := vars["gameID"]

	ctx := s.Log.WithFields(log.Fields{
		"path":    r.URL.Path,
		"method":  r.Method,
		"handler": "HandleWS",
		"gameID":  gameID,
	})

	ctx.Info("request")

	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		ctx.Error(err.Error())
		return
	}

	ctx.Debug("upgraded")

	user := NewUser(log.WithField("gameID", gameID), ws)

	// pass off the new user to the game hub
	s.Hub.register <- GameRegistrationRequest{
		GameID: gameID,
		User:   &user,
	}

	ctx.Debug("registered")
}
Example #3
0
func ExampleNewClient() {
	ctx := apex.Wrap(log.WithField("Example", "NewClient"))
	exampleClient := NewClient(ctx, "ttnctl", "my-app-id", "my-access-key", "eu.thethings.network:1883")
	err := exampleClient.Connect()
	if err != nil {
		ctx.WithError(err).Fatal("Could not connect")
	}
}
Example #4
0
func subscribeToDevices() {
	log.Info("Subscribing to devices...")
	for _, devAddr := range devices {
		topic := fmt.Sprintf("nodes/%s/packets", devAddr)
		if token := mqttClient.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
			log.WithField("topic", topic).WithError(token.Error()).Fatal("Could not subscribe")
		}
	}
}
Example #5
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".ttntool")
	viper.AddConfigPath("$HOME")
	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		log.WithField("file", viper.ConfigFileUsed()).Debug("Using config file")
	}
}
Example #6
0
func (m *Markup) processTriangles(mwQuery *mwQuery) {

	for _, w := range mwQuery.Triangles {

		degree := Degree(w.Degree)
		lessDegree := degree >> 1

		//Generating points

		ori := PointFromMW(w.Origin)
		pWA := PointFromMW(w.WaveA)
		pWB := PointFromMW(w.WaveB)
		pWC := PointFromMW(w.WaveC)
		pWD := PointFromMW(w.WaveD)
		pWE := PointFromMW(w.WaveE)

		//Generating sub waves

		wave := &Wave{Move: &Move{ori, pWE}, WaveDegree: degree}

		subWA := &Wave{Move: &Move{ori, pWA}, WaveDegree: lessDegree}
		subWB := &Wave{Move: &Move{pWA, pWB}, WaveDegree: lessDegree}
		subWC := &Wave{Move: &Move{pWB, pWC}, WaveDegree: lessDegree}
		subWD := &Wave{Move: &Move{pWC, pWD}, WaveDegree: lessDegree}
		subWE := &Wave{Move: &Move{pWD, pWE}, WaveDegree: lessDegree}

		setParentWave(wave, subWA, subWB, subWC, subWD, subWE)

		// Generating triangle wave
		triangleWave := &Wave{Move: &Move{ori, pWE}, WaveDegree: degree}

		triangleCorrection := m.addCorrection(&Correction{Wave: triangleWave})

		triangle := &Triangle{
			A: m.addCorrection(&Correction{Wave: subWA}),
			B: m.addCorrection(&Correction{Wave: subWB}),
			C: m.addCorrection(&Correction{Wave: subWC}),
			D: m.addCorrection(&Correction{Wave: subWD}),
			E: m.addCorrection(&Correction{Wave: subWE}),
		}

		log.WithField("Triangle", triangle).Debug("+Triangle")

		triangleCorrection.Triangle = triangle

		m.Triangles = append(m.Triangles, triangle)

		//TODO 9 wave triangle
	}
}
Example #7
0
func (m *Markup) processTripleComboWave(w mwComboTriple) {
	degree := Degree(w.Degree)
	lessDegree := degree >> 1

	//Generating points

	ori := PointFromMW(w.Origin)
	pWW := PointFromMW(w.WaveW)
	pWX := PointFromMW(w.WaveX)
	pWY := PointFromMW(w.WaveY)
	pWX2 := PointFromMW(w.WaveX2)
	pWZ := PointFromMW(w.WaveZ)

	//Generating sub waves

	wave := &Wave{Move: &Move{ori, pWZ}, WaveDegree: degree}

	subWW := &Wave{Move: &Move{ori, pWW}, WaveDegree: lessDegree}
	subWX := &Wave{Move: &Move{pWW, pWX}, WaveDegree: lessDegree}
	subWY := &Wave{Move: &Move{pWX, pWY}, WaveDegree: lessDegree}
	subWX2 := &Wave{Move: &Move{pWY, pWX2}, WaveDegree: lessDegree}
	subWZ := &Wave{Move: &Move{pWX2, pWZ}, WaveDegree: lessDegree}

	setParentWave(wave, subWW, subWX, subWY, subWX2, subWZ)

	// Generating triangle wave
	tripleWave := &Wave{Move: &Move{ori, pWZ}, WaveDegree: degree}

	tripleCorrection := m.addCorrection(&Correction{Wave: tripleWave})

	triple := &Triple{
		W:  m.addCorrection(&Correction{Wave: subWW}),
		X:  m.addCorrection(&Correction{Wave: subWX}),
		Y:  m.addCorrection(&Correction{Wave: subWY}),
		X2: m.addCorrection(&Correction{Wave: subWX2}),
		Z:  m.addCorrection(&Correction{Wave: subWZ}),
	}

	tripleCorrection.Triple = triple

	log.WithField("Triple", triple).Debug("+Triple")

	m.Triples = append(m.Triples, triple)
}
Example #8
0
func (m *Markup) processCombo(mwQuery *mwQuery) {
	for _, w := range mwQuery.Combo {
		degree := Degree(w.Degree)
		lessDegree := degree >> 1

		//Generating points

		ori := PointFromMW(w.Origin)
		pWW := PointFromMW(w.WaveW)
		pWX := PointFromMW(w.WaveX)
		pWY := PointFromMW(w.WaveY)

		//Generating sub waves

		wave := &Wave{Move: &Move{ori, pWY}, WaveDegree: degree}

		subWW := &Wave{Move: &Move{ori, pWW}, WaveDegree: lessDegree}
		subWX := &Wave{Move: &Move{pWW, pWX}, WaveDegree: lessDegree}
		subWY := &Wave{Move: &Move{pWX, pWY}, WaveDegree: lessDegree}

		setParentWave(wave, subWW, subWX, subWY)

		// Generating triangle wave
		comboWave := &Wave{Move: &Move{ori, pWY}, WaveDegree: degree}

		comboCorrection := m.addCorrection(&Correction{Wave: comboWave})

		combo := &Combo{
			W: m.addCorrection(&Correction{Wave: subWW}),
			X: m.addCorrection(&Correction{Wave: subWX}),
			Y: m.addCorrection(&Correction{Wave: subWY}),
		}

		comboCorrection.Combo = combo

		log.WithField("Combo", combo).Debug("+Combo")

		m.Combos = append(m.Combos, combo)

	}
}
Example #9
0
func (a *app) Run(logger service.Logger) {
	var logFilePath string
	usr, err := user.Current()
	if err == nil {
		logFilePath = filepath.Join(usr.HomeDir, ".config/go-psexec/server-hidden.log")
	} else {
		logFilePath = "server-hidden.log"
	}

	rollingFile := &lumberjack.Logger{
		Filename:   logFilePath,
		MaxSize:    20, // megabytes
		MaxBackups: 20,
		MaxAge:     28, //days
	}

	apex.SetLevel(apex.DebugLevel) //Global level
	apex.SetHandler(json.New(rollingFile))

	tmpLogger := &defaultLogger{
		logger,
		apex.WithField("exe", filepath.Base(os.Args[0])),
	}
	a.logger = tmpLogger

	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Panic recovery in service RUN function: %T %+v", r, r)
		}
	}()

	a.logger.Infof("Running server version %s", TempVersion)

	a.gracefulTimeout = 30 * time.Second //Because a command could be busy executing

	pvtKey, err := shared.ReadPemKey(*serverPemFlag)
	if err != nil {
		logger.Errorf("Cannot read server pem file, error: %s. Exiting server.", err.Error())
		return
	}
	a.privateKey = pvtKey

	checksumsSvc := checksums.New()
	handlerServices := &HandlerServices{
		FilePathSummaries: filepath_summary.New(checksumsSvc),
	}

	a.h = &handler{logger, a.privateKey, handlerServices}

	allowedKeys, err := shared.LoadAllowedPublicKeysFile(*allowedPublicKeysFileFlag)
	if err != nil {
		logger.Errorf("Cannot read allowed public keys, error: %s. Exiting server.", err.Error())
		return
	}
	if len(allowedKeys) == 0 {
		logger.Errorf("Allowed public key file '%s' was read but contains no keys. Exiting server.", *allowedPublicKeysFileFlag)
		return
	}

	a.setAllowedPublicKeys(allowedKeys)

	watcher, err := shared.StartWatcher(*allowedPublicKeysFileFlag, a)
	if err != nil {

	} else {
		a.watcherPublicKeys = watcher
	}

	e := echo.New()
	if a.debugMode {
		e.SetDebug(true)
	}

	e.Use(middleware.Recover())
	if a.accessLogger {
		loggerCfg := middleware.DefaultLoggerConfig
		loggerCfg.Output = tmpLogger
		e.Use(middleware.LoggerWithConfig(loggerCfg))
	}

	t := &htmlTemplateRenderer{}
	e.SetRenderer(t)

	// Unrestricted group
	e.POST("/token", a.h.handleGenerateTokenFunc)
	e.GET("/webui", a.h.handleWebUIFunc)

	// Restricted group
	r := e.Group("/auth")
	r.Use(GetClientPubkey())
	r.GET("/ping", a.h.handlePingFunc)
	r.GET("/version", a.h.handleVersionFunc)
	r.POST("/stream", a.h.handleStreamFunc)
	r.POST("/start", a.h.handleStartFunc)
	r.POST("/upload-tar", a.h.handleUploadTarFunc)
	r.GET("/download-tar", a.h.handleDownloadTarFunc)
	r.POST("/delete", a.h.handleDeleteFunc)
	r.POST("/move", a.h.handleMoveFunc)
	r.POST("/copy", a.h.handleCopyFunc)
	r.POST("/symlink", a.h.handleSymlinkFunc)
	r.GET("/stats", a.h.handleStatsFunc)
	r.GET("/path-summary", a.h.handlePathSummaryFunc)
	r.GET("/get-temp-dir", a.h.handleGetTempDirFunc)
	r.GET("/get-os-type", a.h.handleGetOsTypeFunc)

	a.logger.Infof("Now serving on '%s'", *addressFlag)

	server := standard.New(*addressFlag)
	server.SetHandler(e)
	server.SetLogger(e.Logger())
	if e.Debug() {
		e.Logger().Debug("running in debug mode")
	}

	a.srv = &graceful.Server{
		Timeout: a.gracefulTimeout,
		Server:  server.Server,
	}

	a.registerInterruptSignal()

	err = a.srv.ListenAndServe()
	if err != nil {
		if !strings.Contains(err.Error(), "closed network connection") {
			logger.Errorf("Unable to ListenAndServe, error: %s", err.Error())
			time.Sleep(time.Second) //Sleep a second to give log time to write out
		}
	}
}
Example #10
0
// Structured logging is supported with fields, and is recommended over the formatted message variants.
func Example_structured() {
	log.WithField("user", "Tobo").Info("logged in")
}
Example #11
0
// WithField returns a new entry with the `key` and `value` set.
func WithField(key string, value interface{}) *apexlog.Entry {
	return apexlog.WithField(key, value)
}