From c1a8b8dd177250d28be02b2a15bc04764ea54f80 Mon Sep 17 00:00:00 2001 From: William Reid Date: Wed, 13 Feb 2019 22:47:31 -0500 Subject: [PATCH] Commit of skeleton code for the real generator server --- .gitignore | 3 ++ README.md | Bin 42 -> 162 bytes dataTypes.go | 6 +++ hello.go | 9 ---- server.go | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 9 deletions(-) create mode 100644 .gitignore create mode 100644 dataTypes.go delete mode 100644 hello.go create mode 100644 server.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f394ffe --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.exe +.idea/* + diff --git a/README.md b/README.md index 863462b85441d6dc9406d334cc0e10e5eda013c4..08fb68f7f6508b1fe0bb4dff48bdb8be94e262a8 100644 GIT binary patch literal 162 zcmZXOOA3HM3`4UPyhFjYxA6jlf7B6FJihumx|1PkLz;H(tB|Qzs|Yp)9a^cS_N33m vxiUE_4H|Lm<3Lw4zwkzqM&H4^CUP_IZSk9G(1!2(4QELDf7|o^m-qGq<_{iI delta 5 McmZ3)s5L 0 { // Only send if we have data + if err := sendData(dataBuffer); err != nil { // Something went wrong + fmt.Printf("Error sending data: %v\n", err) + } else { // Data sent, clear the map + dataBuffer = make(map[string][]StampedReading) + } + } else { // There was no data to send + fmt.Println("Got data send signal but buffer is empty") + // TODO: manage the map so that it doesn't run out of memory and kill everything if we don't send data + } + + } + } +} + +func dataReadLoop(x chan map[string]StampedReading) { + for { + // Send our read packets down the channel + // TODO: error handling + x <- readData() + time.Sleep(time.Second) + } +} + +func readData() map[string]StampedReading { + // TODO: modbus + return map[string]StampedReading{ + "oil.temp": { + Timestamp: int(time.Now().Unix()), + Value: rand.Intn(150), + }, + "fuel.temp": { + Timestamp: int(time.Now().Unix()), + Value: rand.Intn(150), + }, + } +} + +func sendData(data map[string][]StampedReading) error { + + url := "http://localhost:8081/data" + jsonStr, err := json.Marshal(data) + if err != nil { + fmt.Printf("Error marshalling data: %v\n", err) + return err + } + + fmt.Printf("Sending json: %v\n", string(jsonStr)) + + req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) + fillHeader(req) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return err + } + + defer func() { + if err := resp.Body.Close(); err != nil { + fmt.Printf("Error: %v", err) + } + }() + + fmt.Println("response Status:", resp.Status) + if resp.StatusCode != 200 { + fmt.Printf("Received a non-200 response: %v\n", resp.StatusCode) + } + + return nil +} + +func fillHeader(req *http.Request) { // Sets the uuid and timestamp for a request + req.Header.Set("Content-Type", "application/json") + req.Header.Set("uuid", "0000001bcd3f") // TODO: get this from somewhere + req.Header.Set("time", strconv.FormatInt(time.Now().Unix(), 10)) +}