forked from schollz/find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rf.go
96 lines (83 loc) · 2.17 KB
/
rf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/boltdb/bolt"
)
func RandomString(strlen int) string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
func rfLearn(group string) float64 {
tempFile := group + ".rf.json"
db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, group+".db"), 0664, nil)
if err != nil {
panic(err)
}
defer db.Close()
Debug.Println("Writing " + tempFile)
f, err := os.OpenFile(path.Join(RuntimeArgs.SourcePath, tempFile), os.O_WRONLY|os.O_CREATE, 0664)
if err != nil {
return -1
}
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("fingerprints"))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
v2 := loadFingerprint(v)
bJSON, _ := json.Marshal(v2)
f.WriteString(string(bJSON) + "\n")
}
return nil
})
f.Close()
// Do learning
conn, _ := net.Dial("tcp", "127.0.0.1:"+RuntimeArgs.RFPort)
// send to socket
fmt.Fprintf(conn, group+"=")
// listen for reply
out, _ := bufio.NewReader(conn).ReadString('\n')
classificationSuccess, err := strconv.ParseFloat(strings.TrimSpace(string(out)), 64)
if err != nil {
Error.Println(string(out))
}
Debug.Printf("RF classification success for '%s' is %2.2f", group, classificationSuccess)
os.Remove(tempFile)
return classificationSuccess
}
func rfClassify(group string, fingerprint Fingerprint) map[string]float64 {
var m map[string]float64
tempFile := RandomString(10)
d1, _ := json.Marshal(fingerprint)
err := ioutil.WriteFile(tempFile+".rftemp", d1, 0644)
if err != nil {
Error.Println("Could not write file: " + err.Error())
return m
}
// connect to this socket
conn, _ := net.Dial("tcp", "127.0.0.1:"+RuntimeArgs.RFPort)
// send to socket
fmt.Fprintf(conn, group+"="+tempFile)
// listen for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
err = json.Unmarshal([]byte(message), &m)
if err != nil {
// do nothing
}
os.Remove(tempFile + ".rftemp")
return m
}