示例#1
0
func lampActionHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	//check if the lamp exist
	lamp, _ := strconv.Atoi(ps.ByName("lamp"))
	exist, err := db.LampExists(lamp)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode("Database error")
		return
	}

	if !exist {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode("Lamp not found")
		return
	}

	//check if action is okay.
	action := ps.ByName("action")
	_, ok := actions[action]
	if !ok {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode("Action not accepted. Use on or off.")
		return
	}

	//here we should execute the command to the 433 Mhz controller.
	aLamp, _ := db.GetLamp(lamp)
	switch action {
	case "on":
		out, err := exec.Command("/bin/sh", "-c", "/home/david/dev/lamp/./send "+strconv.Itoa(aLamp.Lamp)+" 1").CombinedOutput()
		if err != nil {
			log.Println(err)
			log.Println(string(out))
			w.WriteHeader(500)
			return
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode("Turned on")
	case "off":
		out, err := exec.Command("/bin/sh", "-c", "/home/david/dev/lamp/./send "+strconv.Itoa(aLamp.Lamp)+" 0").CombinedOutput()
		if err != nil {
			log.Println(err)
			log.Println(string(out))
			w.WriteHeader(500)
			return
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode("Turned off")
	default:
		w.WriteHeader(http.StatusInternalServerError)
	}
}
示例#2
0
func lampHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	//fetch array of lamps from db.
	lamp, _ := strconv.Atoi(ps.ByName("lamp"))
	exist, err := db.LampExists(lamp)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode("Database error")
		return
	}

	if !exist {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode("Lamp not found")
		return
	}
	aLamp, _ := db.GetLamp(lamp)
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(aLamp)
}