mini-beieli-web/scales.go

110 lines
3.1 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"regexp"
)
// scales handler
func save_scale_settingsHandler(response http.ResponseWriter, request *http.Request) {
name := getUserName(request)
if name != "" {
deveui, ok := request.URL.Query()["deveui"]
if !ok || len(deveui[0]) < 1 {
log.Println("Url Param 'deveui' is missing")
fmt.Fprintf(response, "{ \"rc\": 1, \"msg\": \"deveui must be specified in URL\" }")
return
}
// Query()["deveui"] will return an array of items,
// we only want the single item.
mydeveui := deveui[0]
if len(mydeveui) != 16 {
log.Println("specified 'deveui' has invalid length")
fmt.Fprintf(response, "{ \"rc\": 8, \"msg\": \"specified deveui has invalid length\" }")
return
}
if !(Contains(getMyDevs(name), mydeveui)) {
log.Println("specified 'deveui' does not belong to this user")
fmt.Fprintf(response, "{ \"rc\": 2, \"msg\": \"specified deveui does not belong to this user\" }")
return
}
log.Println("Url Param 'deveui' is: " + string(mydeveui))
alias, ok2 := request.URL.Query()["alias"]
if !ok2 || len(alias[0]) < 1 {
log.Println("Url Param 'alias' is missing")
fmt.Fprintf(response, "{ \"rc\": 3, \"msg\": \"alias must be specified in URL\" }")
return
}
myalias := alias[0]
// validate alias
match, _ := regexp.MatchString("^[a-zA-Z0-9 ]{1,16}$", myalias)
if !(match) {
log.Println("Url Param 'alias' is not valid")
fmt.Fprintf(response, "{ \"rc\": 9, \"msg\": \"alias is not valid\" }")
return
}
alarmactive, ok3 := request.URL.Query()["alarmactive"]
if !ok3 || len(alarmactive[0]) < 1 {
log.Println("Url Param 'alarmactive' is missing")
fmt.Fprintf(response, "{ \"rc\": 4, \"msg\": \"alarmactive must be specified in URL\" }")
return
}
myalarmactive := alarmactive[0]
if !((myalarmactive == "0") || (myalarmactive == "1")) {
log.Println("Url Param 'alarmactive' is not valid")
fmt.Fprintf(response, "{ \"rc\": 10, \"msg\": \"alarmactive is not valid\" }")
return
}
smsnumber, ok4 := request.URL.Query()["smsnumber"]
if !ok4 || len(smsnumber[0]) < 1 {
log.Println("Url Param 'smsnumber' is missing")
fmt.Fprintf(response, "{ \"rc\": 5, \"msg\": \"smsnumber must be specified in URL\" }")
return
}
mysmsnumber := smsnumber[0]
match1, _ := regexp.MatchString(`^\+[0-9]{11,11}$`, mysmsnumber)
if !(match1) {
log.Println("Url Param 'smsnumber' is not valid")
fmt.Fprintf(response, "{ \"rc\": 11, \"msg\": \"smsnumber is not valid, must be in in format +41791234567\" }")
return
}
var mydev Dev
mydev.Deveui = mydeveui
mydev.Alias = myalias
mydev.Alarmactive = myalarmactive
mydev.Smsnumber = mysmsnumber
// now we try to save the settings
err := updateScaleSettings(mydev)
if err != nil {
log.Println("Error to Update Device Settings")
fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"error with saving device settings\" }")
return
} else {
fmt.Fprintf(response, "{ \"rc\": 0, \"msg\": \"SUCCESS\" }")
}
} else {
fmt.Fprintf(response, "{ \"rc\": 7, \"msg\": \"Only available for logged in users\" }")
}
}