commit 2021-12-15]17:07:50

This commit is contained in:
Godopu 2021-12-15 17:07:52 +09:00
parent fa43e0cb9f
commit 66c1674539
9 changed files with 200 additions and 42 deletions

3
.gitignore vendored
View File

@ -1 +1,2 @@
public/
public/
front/

View File

@ -0,0 +1,32 @@
package constants
import (
"fmt"
"net"
"os"
"strings"
)
func getIP() string {
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
return addrs[0].String()
}
var ServerAddr string
var MyIP string
func init() {
var exist bool
ServerAddr, exist = os.LookupEnv("SERVER_ADDR")
if !exist {
fmt.Println("Please set SERVER_ADDR as environment variable")
}
MyIP = getIP()
idx := strings.LastIndex(MyIP, ".")
ServerAddr = MyIP[:idx+1] + "1"
fmt.Println(ServerAddr)
}

View File

@ -1,3 +1,8 @@
module devicemanagera
module devicemanagerb
go 1.17
require (
github.com/gorilla/mux v1.7.4
github.com/urfave/negroni v1.0.0
)

View File

@ -0,0 +1,4 @@
github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=

View File

@ -2,50 +2,30 @@ package main
import (
"bytes"
"devicemanagera/router"
"devicemanagerb/constants"
"devicemanagerb/router"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
)
var server_addr string
func getIP() string {
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
return addrs[0].String()
}
func registerToServer() {
var exist bool
server_addr, exist = os.LookupEnv("SERVER_ADDR")
if !exist {
fmt.Println("Please set SERVER_ADDR as environment variable")
}
ip := getIP()
idx := strings.LastIndex(ip, ".")
serverAddr := ip[:idx+1] + "1"
fmt.Println(serverAddr)
var obj map[string]string = make(map[string]string)
obj["name"] = "devicemanagera"
obj["addr"] = getIP() + ":3000"
obj["name"] = "devicemanagerb"
obj["addr"] = constants.MyIP + ":3000"
b, err := json.Marshal(obj)
if err != nil {
panic(err)
}
req, err := http.NewRequest("PUT", "http://"+serverAddr+":3000/services", bytes.NewBuffer(b))
req, err := http.NewRequest("PUT", "http://"+constants.ServerAddr+":3000/services", bytes.NewBuffer(b))
if err != nil {
panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
@ -56,7 +36,6 @@ func registerToServer() {
panic(err)
}
fmt.Println(string(b))
// http.Post("")
}
func main() {

View File

@ -1,15 +1,150 @@
package router
import (
"bytes"
"devicemanagerb/constants"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
func NewRouter() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("I am devicemanagerA"))
})
mux := mux.NewRouter()
// mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// w.WriteHeader(http.StatusOK)
// w.Write([]byte("I am devicemanagerB"))
// })
return mux
mux.HandleFunc("/{id}", PutStatusChangedHandle).Methods("PUT")
mux.HandleFunc("/{id}", PostStatusChangedHandle).Methods("POST")
mux.HandleFunc("/{id}", GetStatusHandle).Methods("GET")
n := negroni.Classic()
n.UseHandler(mux)
return n
}
// sensing data per device
var s_data = map[string]interface{}{}
// status from sensor
func PutStatusChangedHandle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
status := map[string]interface{}{}
err = json.Unmarshal(b, &status)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
did, ok := vars["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
s_data[did] = status
log.Println(s_data)
cdata, ok := c_data[did]
if !ok {
w.Write([]byte("I am devicemanagerB"))
} else {
encoder := json.NewEncoder(w)
err := encoder.Encode(cdata)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
}
req, err := http.NewRequest("PUT", "http://"+constants.ServerAddr+":3000/device/"+did, bytes.NewReader(b))
if err != nil {
return
}
_, err = http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
}
var c_data = map[string]interface{}{}
func GetStatusHandle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
did, ok := vars["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
status, ok := c_data[did]
if !ok {
status = map[string]interface{}{
"servo": 0,
"fan": 0,
"light": 0,
}
}
encoder := json.NewEncoder(w)
err := encoder.Encode(status)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
}
func PostStatusChangedHandle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
status := map[string]interface{}{}
err = json.Unmarshal(b, &status)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
did, ok := vars["id"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
c_data[did] = status
log.Println(c_data)
w.WriteHeader(http.StatusOK)
}
// status from user per device

View File

@ -52,16 +52,15 @@ func (s *dbHandler) QueryDevice(dname string) (*Device, error) {
return &device, nil
}
func (s *dbHandler) DeleteDevice(device *Device) error {
func (s *dbHandler) DeleteDevice(device *Device) error {
tx := s.db.Delete(device)
if tx.Error != nil {
return tx.Error
}
tx.First(device, "did=?", device.DID)
// tx.First(device, "did=?", device.DID)
return nil
}
func (s *dbHandler) IsExistDevice(dname string) bool {

View File

@ -86,7 +86,6 @@ func PostDevice(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
fmt.Println("^^")
mutex.Lock()
defer mutex.Unlock()
delete(waitPermission, device.DID)
@ -104,7 +103,11 @@ func PostDevice(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("This operation is not permitted"))
return
case b := <-waitPermission[device.DID]:
case b, ok := <-waitPermission[device.DID]:
if !ok {
return
}
if b {
// 디바이스 등록 절차 수행
db.AddDevice(device)

View File

@ -33,8 +33,8 @@ func removeNotification(noti chan *Notification) {
defer notiMutex.Unlock()
for i, e := range notifications {
if e == noti {
discoveredDevices[i] = discoveredDevices[len(discoveredDevices)-1]
discoveredDevices = discoveredDevices[:len(discoveredDevices)-1]
notifications[i] = notifications[len(notifications)-1]
notifications = notifications[:len(notifications)-1]
}
}
}