Skip to content

Commit

Permalink
First pass at improving documentation. Issue #75
Browse files Browse the repository at this point in the history
  • Loading branch information
schollz committed May 1, 2016
1 parent aafdef7 commit 39d95c2
Show file tree
Hide file tree
Showing 13 changed files with 131 additions and 24 deletions.
6 changes: 6 additions & 0 deletions api.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// api.go handles functions that return JSON responses.

package main

import (
Expand Down
6 changes: 6 additions & 0 deletions cache.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// cache.go handles the global variables for caching and the clearing.

package main

import "time"
Expand Down
8 changes: 8 additions & 0 deletions db.go
@@ -1,3 +1,11 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// db.go contains generic functions for parsing data from the database.
// This file is not exhaustive of all database functions, if they pertain to a
// specific property (fingerprinting/priors/parameters), it will instead be in respective file.

package main

import (
Expand Down
6 changes: 6 additions & 0 deletions fingerprint.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// fingerprint.go contains structures and functions for handling fingerprints.

package main

import (
Expand Down
6 changes: 6 additions & 0 deletions mqtt.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// mqtt.go contains functions for performing MQTT transactions.

package main

import (
Expand Down
6 changes: 6 additions & 0 deletions network.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// network.go contains structures and functions for creating networks from slices.

package main

import (
Expand Down
6 changes: 6 additions & 0 deletions parameters.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// parameters.go contains structures and functions for setting and getting Naive-Bayes parameters.

package main

import (
Expand Down
10 changes: 10 additions & 0 deletions posterior.go
@@ -1,7 +1,14 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// posteriors.go contains variables for calcualting Naive-Bayes posteriors.

package main

import "math"

// calculatePosterior takes a Fingerprint and a Parameter set and returns the noramlized Bayes probabilities of possible locations
func calculatePosterior(res Fingerprint, ps FullParameters) (string, map[string]float64) {
if !ps.Loaded {
ps, _ = openParameters(res.Group)
Expand Down Expand Up @@ -78,6 +85,8 @@ func calculatePosterior(res Fingerprint, ps FullParameters) (string, map[string]
return bestLocation, PBayesMix
}

// calculatePosteriorThreadSafe is exactly the same as calculatePosterior except it does not do the mixin calculation
// as it is used for optimizing priors.
func calculatePosteriorThreadSafe(res Fingerprint, ps FullParameters, cutoff float64) (map[string]float64, map[string]float64) {
if !ps.Loaded {
ps, _ = openParameters(res.Group)
Expand Down Expand Up @@ -136,6 +145,7 @@ func calculatePosteriorThreadSafe(res Fingerprint, ps FullParameters, cutoff flo
return PBayes1, PBayes2
}

// normalizeBayes takes the bayes map and normalizes to standard normal.
func normalizeBayes(bayes map[string]float64) map[string]float64 {
vals := make([]float64, len(bayes))
i := 0
Expand Down
8 changes: 8 additions & 0 deletions priors.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// priors.go contains variables for calcualting priors.

package main

import (
Expand Down Expand Up @@ -42,6 +48,7 @@ func init() {
FoldCrossValidation = 4
}

// deprecated
func optimizePriors(group string) {
// generate the fingerprintsInMemory
fingerprintsInMemory := make(map[string]Fingerprint)
Expand Down Expand Up @@ -187,6 +194,7 @@ func crossValidation(group string, n string, ps *FullParameters, fingerprintsInM
return average
}

// calculatePriors generates the prior data for Naive-Bayes classification. Now deprecated, use calculatePriorsThreaded instead.
func calculatePriors(group string, ps *FullParameters, fingerprintsInMemory map[string]Fingerprint, fingerprintsOrdering []string) {
// defer timeTrack(time.Now(), "calculatePriors")
ps.Priors = make(map[string]PriorParameters)
Expand Down
7 changes: 7 additions & 0 deletions priorsThreaded.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// priorsThreaded.go contains the main Prior-calculation function which is multi-threaded

package main

import (
Expand Down Expand Up @@ -55,6 +61,7 @@ func worker(id int, jobs <-chan jobA, results chan<- resultA) {
}
}

// optimizePriorsThreaded generates the optimized prior data for Naive-Bayes classification.
func optimizePriorsThreaded(group string) {
// Debug.Println("Optimizing priors for " + group)
// generate the fingerprintsInMemory
Expand Down
15 changes: 15 additions & 0 deletions routes.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// routes.go contains the functions that handle the web page views

package main

import (
Expand All @@ -15,6 +21,7 @@ import (
"github.com/gin-gonic/gin"
)

// slash returns the dashboard, if logged in, else it redirects to login page.
func slash(c *gin.Context) {
var group string
loginGroup := sessions.Default(c)
Expand All @@ -27,6 +34,7 @@ func slash(c *gin.Context) {
}
}

// slashLogin handles a login with url parameter and returns dashboard if successful, else login.
func slashLogin(c *gin.Context) {
loginGroup := sessions.Default(c)
group := c.DefaultQuery("group", "noneasdf")
Expand All @@ -39,6 +47,7 @@ func slashLogin(c *gin.Context) {
}
}

// slashLogin handles a POST login and returns dashboard if successful, else login.
func slashLoginPOST(c *gin.Context) {
loginGroup := sessions.Default(c)
group := strings.ToLower(c.PostForm("group"))
Expand All @@ -53,6 +62,7 @@ func slashLoginPOST(c *gin.Context) {
}
}

// slashLogout handles a logout
func slashLogout(c *gin.Context) {
var group string
loginGroup := sessions.Default(c)
Expand All @@ -70,6 +80,7 @@ func slashLogout(c *gin.Context) {
}
}

// slashDashboard displays the dashboard
func slashDashboard(c *gin.Context) {
group := c.Param("group")
if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) {
Expand Down Expand Up @@ -118,6 +129,7 @@ func slashDashboard(c *gin.Context) {
})
}

// slash Location returns location (to be deprecated)
func slashLocation(c *gin.Context) {
group := c.Param("group")
if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) {
Expand All @@ -129,6 +141,7 @@ func slashLocation(c *gin.Context) {
c.JSON(http.StatusOK, userJSON)
}

// slashExplore returns a chart of the data
func slashExplore(c *gin.Context) {
group := c.Param("group")
if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) {
Expand Down Expand Up @@ -170,6 +183,7 @@ func slashExplore(c *gin.Context) {
})
}

// slashExplore returns a chart of the data (canvas.js)
func slashExplore2(c *gin.Context) {
group := c.Param("group")
if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) {
Expand Down Expand Up @@ -233,6 +247,7 @@ func slashExplore2(c *gin.Context) {
})
}

// slashPie returns a Pie chart
func slashPie(c *gin.Context) {
group := c.Param("group")
if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) {
Expand Down
54 changes: 30 additions & 24 deletions server.go
@@ -1,3 +1,9 @@
// Copyright 2015-2016 Zack Scholl. All rights reserved.
// Use of this source code is governed by a AGPL
// license that can be found in the LICENSE file.

// server.go handles Flag parsing and starts the Gin-Tonic webserver.

package main

import (
Expand Down Expand Up @@ -32,6 +38,7 @@ var RuntimeArgs struct {
// VersionNum keeps track of the version
var VersionNum string

// init initiates the paths in RuntimeArgs
func init() {
cwd, _ := os.Getwd()
RuntimeArgs.SourcePath = path.Join(cwd, "data")
Expand All @@ -41,6 +48,8 @@ func init() {
func main() {
VersionNum = "2.0"
// _, executableFile, _, _ := runtime.Caller(0) // get full path of this file

// Bing flags for changing parameters of FIND
flag.StringVar(&RuntimeArgs.Port, "p", ":8003", "port to bind")
flag.StringVar(&RuntimeArgs.Socket, "s", "", "unix socket")
flag.StringVar(&RuntimeArgs.ServerCRT, "crt", "", "location of ssl crt")
Expand All @@ -49,7 +58,6 @@ func main() {
flag.StringVar(&RuntimeArgs.MqttAdmin, "mqttadmin", "", "admin to read all messages")
flag.StringVar(&RuntimeArgs.MqttAdminPassword, "mqttadminpass", "", "admin to read all messages")
flag.StringVar(&RuntimeArgs.MosquittoPID, "mosquitto", "", "mosquitto PID")

flag.CommandLine.Usage = func() {
fmt.Println(`find (version ` + VersionNum + `)
run this to start the server and then visit localhost at the port you specify
Expand All @@ -68,72 +76,70 @@ Options:`)
RuntimeArgs.ExternalIP = GetLocalIP() + RuntimeArgs.Port
}

// Check whether all the MQTT variables are passed to initiate the MQTT routines
if len(RuntimeArgs.MqttServer) > 0 && len(RuntimeArgs.MqttAdmin) > 0 && len(RuntimeArgs.MosquittoPID) > 0 {
RuntimeArgs.Mqtt = true
setupMqtt()
} else {
RuntimeArgs.Mqtt = false
}

// var ps FullParameters = *NewFullParameters()
// getParameters("findtest2", &ps)
// calculatePriors("findtest2", &ps)
// saveParameters("findtest2", ps)
// // fmt.Println(string(dumpParameters(ps)))
// saveParameters("findtest2", ps)
// fmt.Println(ps.MacVariability)
// fmt.Println(ps.NetworkLocs)
// optimizePriors("findtest2")
// ps, _ = openParameters("findtest2")
//
// getPositionBreakdown("findtest2", "zack")

// Setup Gin-Gonic
gin.SetMode(gin.ReleaseMode)
r := gin.Default()

// Load templates
r.LoadHTMLGlob(path.Join(RuntimeArgs.Cwd, "templates/*"))

// Load static files (if they are not hosted by external service)
r.Static("static/", path.Join(RuntimeArgs.Cwd, "static/"))

// Create cookie store to keep track of logged in user
store := sessions.NewCookieStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))

// 404 page
// 404-page redirects to login
r.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusOK, "login.tmpl", gin.H{
"ErrorMessage": "Please login first.",
})
})

// webpages (routes.go)
r.GET("/pie/:group/:network/:location", slashPie)
// Routes for logging in and viewing dashboards (routes.go)
r.GET("/", slash)
r.GET("/login", slashLogin)
r.POST("/login", slashLoginPOST)
r.GET("/logout", slashLogout)
r.GET("/dashboard/:group", slashDashboard)
r.GET("/explore/:group/:network/:location", slashExplore2)
r.GET("/pie/:group/:network/:location", slashPie)

// fingerprinting (fingerprint.go)
// r.POST("/fingerprint", handleFingerprint)
// Routes for performing fingerprinting (fingerprint.go)
r.POST("/learn", learnFingerprintPOST)
r.POST("/track", trackFingerprintPOST)

// MQTT routes (mqtt.go)
// Routes for MQTT (mqtt.go)
r.PUT("/mqtt", putMQTT)

// API routes (api.go)
r.PUT("/mixin", putMixinOverride)
// Routes for API access (api.go)
r.GET("/location", getUserLocations)
r.GET("/whereami", whereAmI)
r.GET("/editname", editName)
r.GET("/editusername", editUserName)
r.GET("/editnetworkname", editNetworkName)
r.DELETE("/location", deleteLocation)
r.DELETE("/locations", deleteLocations)
r.DELETE("/user", deleteUser)
r.GET("/calculate", calculate)
r.GET("/userlocs", userLocations)
r.GET("/status", getStatus)
r.GET("/userlocs", userLocations) // to be deprecated
r.GET("/whereami", whereAmI) // to be deprecated
r.PUT("/mixin", putMixinOverride)

// Load and display the logo
dat, _ := ioutil.ReadFile("./static/logo.txt")
fmt.Println(string(dat))

// Check whether user is providing certificates
if RuntimeArgs.Socket != "" {
r.RunUnix(RuntimeArgs.Socket)
} else if RuntimeArgs.ServerCRT != "" && RuntimeArgs.ServerKey != "" {
Expand Down

0 comments on commit 39d95c2

Please sign in to comment.