Exemple #1
0
func GetDeviceCurrentStatus(urlparams martini.Params, r render.Render) {
	identifier := urlparams["identifier"]
	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", identifier)

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	result := DeviceStatusResponse{}

	onlineargs := rpcs.ArgsGetDeviceStatus{
		Id: uint64(device.ID),
	}
	onlinereply := rpcs.ReplyGetDeviceStatus{}
	err = server.RPCCallByName("devicemanger", "DeviceManager.GetDeviceStatus", onlineargs, &onlinereply)
	if err != nil {
		// if device is not online, just return
		server.Log.Errorf("get devie status error: %v", err)
		r.JSON(http.StatusOK, result)
		return
	}

	// device is online, try read status
	// todo
}
Exemple #2
0
func GetDeviceCurrentStatus(urlparams martini.Params, r render.Render) {
	identifier := urlparams["identifier"]
	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", identifier)

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
		Id: uint64(device.ID),
	}
	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
	err = server.RPCCallByName("devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
	if err != nil {
		server.Log.Errorf("get devie online status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrDeviceNotOnline, err))
		return
	}

	statusargs := rpcs.ArgsGetStatus{
		Id: uint64(device.ID),
	}
	statusreply := rpcs.ReplyGetStatus{}
	err = server.RPCCallByName("controller", "Controller.GetStatus", statusargs, &statusreply)
	if err != nil {
		server.Log.Errorf("get devie status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	product := &models.Product{}
	err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrProductNotFound, err))
		return
	}

	c, err := productconfig.New(product.ProductConfig)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongProductConfig, err))
		return
	}

	data, err := c.StatusToMap(statusreply.Status)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongStatusFormat, err))
		return
	}
	result := DeviceStatusResponse{
		Data: data,
	}

	r.JSON(http.StatusOK, result)
	return
}
func (mp *MQTTProvider) OnDeviceMessage(deviceid uint64, msgtype string, message []byte) {
	server.Log.Infof("device {%v} message {%v} : %x", deviceid, msgtype, message)
	switch msgtype {
	case "s":
		// it's a status
		data := &protocol.Data{}
		err := data.UnMarshal(message)
		if err != nil {
			server.Log.Errorf("unmarshal data error : %v", err)
			return
		}
		// if there is a realtime query
		ch, exist := StatusChan[deviceid]
		if exist {
			ch <- data
			return
		}

		// it's a normal report.
		reply := rpcs.ReplyOnStatus{}
		args := rpcs.ArgsOnStatus{
			DeviceId:  deviceid,
			Timestamp: data.Head.Timestamp,
			Subdata:   data.SubData,
		}
		err = server.RPCCallByName("controller", "Controller.OnStatus", args, &reply)
		if err != nil {
			server.Log.Errorf("device report status error. args: %v, error: %v", args, err)
			return
		}
	case "e":
		// it's an event report
		event := &protocol.Event{}
		err := event.UnMarshal(message)
		if err != nil {
			server.Log.Errorf("unmarshal event error : %v", err)
			return
		}
		reply := rpcs.ReplyOnEvent{}
		args := rpcs.ArgsOnEvent{
			DeviceId:  deviceid,
			TimeStamp: event.Head.Timestamp,
			SubDevice: event.Head.SubDeviceid,
			No:        event.Head.No,
			Priority:  event.Head.Priority,
			Params:    event.Params,
		}
		err = server.RPCCallByName("controller", "Controller.OnEvent", args, &reply)
		if err != nil {
			server.Log.Errorf("device on event error. args: %v, error: %v", args, err)
			return
		}
	default:
		server.Log.Infof("unkown message type: %v", msgtype)
	}
}
Exemple #4
0
func (ift *Ifttt) Check(deviceid uint64, eventid uint16) error {
	actions := &[]models.Rule{}
	query := &models.Rule{
		RuleType: "ifttt",
		DeviceID: int64(deviceid),
	}
	err := server.RPCCallByName("registry", "Registry.QueryRules", query, actions)
	if err != nil {
		server.Log.Warnf("load ifttt rules error : %v", err)
		return err
	}

	if len(*actions) > 0 {
		device := &models.Device{}
		err := server.RPCCallByName("registry", "Registry.FindDeviceById", int64(deviceid), device)
		if err != nil {
			server.Log.Errorf("find device error : %v", err)
			return err
		}

		product := &models.Product{}
		err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
		if err != nil {
			server.Log.Errorf("find product error : %v", err)
			return err
		}

		c, err := productconfig.New(product.ProductConfig)
		if err != nil {
			server.Log.Errorf("product config error : %v", err)
			return err
		}

		name := ""
		for _, ev := range c.Events {
			if ev.No == int(eventid) {
				name = ev.Name
			}
		}

		for _, action := range *actions {
			if action.Trigger == name {
				err := performRuleAction(action.Target, action.Action)
				if err != nil {
					server.Log.Warnf("ifttt action failed: %v", err)
				}
			}
		}
	}

	return nil
}
Exemple #5
0
func AddRule(device *models.Device, req *http.Request, r render.Render) {
	var ruleReq CreateRuleRequest
	decoder := json.NewDecoder(req.Body)
	err := decoder.Decode(&ruleReq)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	rule := &models.Rule{
		DeviceID: device.ID,
		RuleType: ruleReq.Type,
		Trigger:  ruleReq.Trigger,
		Target:   ruleReq.Target,
		Action:   ruleReq.Action,
	}
	reply := &rpcs.ReplyEmptyResult{}

	err = server.RPCCallByName("registry", "Registry.CreateRule", rule, reply)
	if err != nil {
		server.Log.Errorf("create device rule error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	r.JSON(http.StatusOK, Common{})
	return

}
Exemple #6
0
func addVendor() error {
	args := models.Vendor{}

	reader := bufio.NewReader(os.Stdin)

	fmt.Printf("vendor name: ")
	name, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.VendorName = strings.Replace(name, "\n", "", -1)

	fmt.Printf("vendor description: ")
	desc, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.VendorDescription = strings.Replace(desc, "\n", "", -1)

	reply := &models.Vendor{}

	err = server.RPCCallByName("registry", "Registry.SaveVendor", &args, reply)
	if err != nil {
		return err
	}

	fmt.Println("=======> vendor created successfully:")
	printStruct(reply)
	fmt.Println("=======")

	return nil
}
Exemple #7
0
func GetDeviceCurrentStatus(device *models.Device, config *productconfig.ProductConfig,
	urlparams martini.Params, r render.Render) {
	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", device.DeviceIdentifier)

	statusargs := rpcs.ArgsGetStatus{
		Id: uint64(device.ID),
	}
	statusreply := rpcs.ReplyGetStatus{}
	err := server.RPCCallByName("controller", "Controller.GetStatus", statusargs, &statusreply)
	if err != nil {
		server.Log.Errorf("get devie status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	status, err := config.StatusToMap(statusreply.Status)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}
	result := DeviceStatusResponse{
		Data: status,
	}

	r.JSON(http.StatusOK, result)
	return
}
Exemple #8
0
func RegisterDevice(args DeviceRegisterArgs, r render.Render) {
	server.Log.Printf("ACTION RegisterDevice, args:: %v ", args)
	rpcargs := &rpcs.ArgsDeviceRegister{
		ProductKey:    args.ProductKey,
		DeviceCode:    args.DeviceCode,
		DeviceVersion: args.Version,
	}
	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.RegisterDevice", rpcargs, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}
	server.Log.Infof("register device success: %v", device)

	result := DeviceRegisterResponse{}
	result.Data = DeviceRegisterData{
		DeviceId:         device.ID,
		DeviceSecret:     device.DeviceSecret,
		DeviceKey:        device.DeviceKey,
		DeviceIdentifier: device.DeviceIdentifier,
	}
	r.JSON(http.StatusOK, result)
	return
}
func (mp *MQTTProvider) OnDeviceOnline(args rpcs.ArgsGetOnline) error {
	reply := rpcs.ReplyGetOnline{}
	err := server.RPCCallByName("devicemanager", "DeviceManager.GetOnline", args, &reply)
	if err != nil {
		server.Log.Errorf("device online error. args: %v, error: %v", args, err)
	}

	return err
}
func (mp *MQTTProvider) OnDeviceHeartBeat(deviceid uint64) error {
	args := rpcs.ArgsDeviceId{
		Id: deviceid,
	}
	reply := rpcs.ReplyHeartBeat{}
	err := server.RPCCallByName("devicemanager", "DeviceManager.HeartBeat", args, &reply)
	if err != nil {
		server.Log.Errorf("device heartbeat error. deviceid: %v, error: %v", deviceid, err)
	}
	return err
}
Exemple #11
0
func (n *Notifier) updateApplications() error {
	for {

		err := server.RPCCallByName("registry", "Registry.GetApplications", 0, &n.apps)
		if err != nil {
			server.Log.Errorf("get applications error : %v", err)
		}

		time.Sleep(time.Minute)
	}
}
Exemple #12
0
func addApplication() error {
	args := models.Application{}

	reader := bufio.NewReader(os.Stdin)

	fmt.Printf("application name: ")
	name, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.AppName = strings.Replace(name, "\n", "", -1)

	fmt.Printf("application description: ")
	desc, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.AppDescription = strings.Replace(desc, "\n", "", -1)

	fmt.Printf("application domain: ")
	domain, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.AppDomain = strings.Replace(domain, "\n", "", -1)

	fmt.Printf("application report url: ")
	url, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.ReportUrl = strings.Replace(url, "\n", "", -1)

	fmt.Printf("application token: ")
	token, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.AppToken = strings.Replace(token, "\n", "", -1)

	reply := &models.Application{}

	err = server.RPCCallByName("registry", "Registry.SaveApplication", &args, reply)
	if err != nil {
		return err
	}

	fmt.Println("=======> application created successfully:")
	printStruct(reply)
	fmt.Println("=======")

	return nil
}
Exemple #13
0
func getAccessRPCHost(deviceid uint64) (string, error) {
	args := rpcs.ArgsGetDeviceOnlineStatus{
		Id: deviceid,
	}
	reply := &rpcs.ReplyGetDeviceOnlineStatus{}
	err := server.RPCCallByName("devicemanager", "DeviceManager.GetDeviceOnlineStatus", args, reply)
	if err != nil {
		return "", err
	}

	return reply.AccessRPCHost, nil
}
func (mp *MQTTProvider) OnDeviceOffline(deviceid uint64) error {
	args := rpcs.ArgsGetOffline{
		Id: deviceid,
	}
	reply := rpcs.ReplyGetOffline{}
	err := server.RPCCallByName("devicemanager", "DeviceManager.GetOffline", args, &reply)
	if err != nil {
		server.Log.Errorf("device offline error. deviceid: %v, error: %v", deviceid, err)
	}

	return err
}
Exemple #15
0
// get device identifier
func CheckDeviceIdentifier(context martini.Context, params martini.Params, req *http.Request, r render.Render) {
	identifier := params["identifier"]

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	context.Map(device)
}
func (mp *MQTTProvider) ValidateDeviceToken(deviceid uint64, token []byte) error {
	args := rpcs.ArgsValidateDeviceAccessToken{
		Id:          deviceid,
		AccessToken: token,
	}
	reply := rpcs.ReplyValidateDeviceAccessToken{}
	err := server.RPCCallByName("devicemanager", "DeviceManager.ValidateDeviceAccessToken", args, &reply)
	if err != nil {
		server.Log.Errorf("validate device token error. deviceid : %v, token : %v, error: %v", deviceid, token, err)
		return err
	}
	return nil
}
Exemple #17
0
// check if device is online.
func CheckDeviceOnline(context martini.Context, params martini.Params, req *http.Request, r render.Render) {
	identifier := params["identifier"]

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
		Id: uint64(device.ID),
	}
	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
	err = server.RPCCallByName("devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
	if err != nil {
		server.Log.Errorf("get devie online status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrDeviceNotOnline, err))
		return
	}

	context.Map(device)
}
Exemple #18
0
func AuthDevice(args DeviceAuthArgs, r render.Render) {
	server.Log.Printf("ACTION AuthDevice, args:: %v", args)
	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceById", int64(args.DeviceId), device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	if device.DeviceSecret != args.DeviceSecret {
		// device secret is wrong.
		r.JSON(http.StatusOK, renderError(ErrWrongSecret, errors.New("wrong device secret.")))
		return
	}

	hepler := token.NewHelper(*confRedisHost)
	token, err := hepler.GenerateToken(uint64(device.ID))
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	var hosts []string
	switch args.Protocol {
	case "http":
		hosts, err = server.GetServerHosts(args.Protocol+"access", "httphost")
	case "mqtt":
		hosts, err = server.GetServerHosts(args.Protocol+"access", "tcphost")
	default:
		err = errors.New("unsuported protocol: " + args.Protocol)
	}
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrProtocolNotSuported, err))
		return
	}

	// just get a random host
	host := hosts[rand.Intn(len(hosts))]

	result := DeviceAuthResponse{}
	result.Data = DeviceAuthData{
		AccessToken: hex.EncodeToString(token),
		AccessAddr:  host,
	}

	server.Log.Infof("auth device success: %v, token: %x, access: %v", device, token, host)

	r.JSON(http.StatusOK, result)
	return
}
Exemple #19
0
func SendCommandToDevice(device *models.Device, config *productconfig.ProductConfig,
	urlparams martini.Params, req *http.Request, r render.Render) {
	timeout := req.URL.Query().Get("timeout")

	server.Log.Printf("ACTION SendCommandToDevice, identifier:: %v, request: %v, timeout: %v",
		device.DeviceIdentifier, req.Body, timeout)

	var args interface{}
	decoder := json.NewDecoder(req.Body)
	err := decoder.Decode(&args)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	m, ok := args.(map[string]interface{})
	if !ok {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	command, err := config.MapToCommand(m)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	cmdargs := rpcs.ArgsSendCommand{
		DeviceId:  uint64(device.ID),
		SubDevice: uint16(command.Head.SubDeviceid),
		No:        uint16(command.Head.No),
		WaitTime:  uint32(defaultTimeOut),
		Params:    command.Params,
	}
	cmdreply := rpcs.ReplySendCommand{}
	err = server.RPCCallByName("controller", "Controller.SendCommand", cmdargs, &cmdreply)
	if err != nil {
		server.Log.Errorf("send devie command error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	r.JSON(http.StatusOK, Common{})
	return

}
Exemple #20
0
// check if proudct is ok and map a product config to context, must by called after CheckDevice
func CheckProductConfig(context martini.Context, device *models.Device,
	params martini.Params, req *http.Request, r render.Render) {
	product := &models.Product{}
	err := server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrProductNotFound, err))
		return
	}

	c, err := productconfig.New(product.ProductConfig)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongProductConfig, err))
		return
	}

	context.Map(c)
}
Exemple #21
0
func GetDeviceInfoByIdentifier(urlparams martini.Params, r render.Render) {
	identifier := urlparams["identifier"]
	server.Log.Printf("ACTION GetDeviceInfoByIdentifier, identifier:: %v", identifier)
	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	result := DeviceInfoResponse{
		Data: DeviceInfoData{
			Identifier:  device.DeviceIdentifier,
			Name:        device.DeviceName,
			Description: device.DeviceDescription,
			Version:     device.DeviceVersion,
		},
	}
	r.JSON(http.StatusOK, result)
	return
}
Exemple #22
0
func GetDeviceInfoByKey(params martini.Params, req *http.Request, r render.Render) {
	key := req.URL.Query().Get("device_key")
	server.Log.Printf("ACTION GetDeviceInfoByKey, key:: %v", key)
	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.ValidateDevice", key, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	result := DeviceInfoResponse{
		Data: DeviceInfoData{
			Identifier:  device.DeviceIdentifier,
			Name:        device.DeviceName,
			Description: device.DeviceDescription,
			Version:     device.DeviceVersion,
		},
	}
	r.JSON(http.StatusOK, result)
	return
}
Exemple #23
0
func SetDeviceStatus(device *models.Device, config *productconfig.ProductConfig,
	urlparams martini.Params, req *http.Request, r render.Render) {
	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v,request: %v", device.DeviceIdentifier, req.Body)

	var args interface{}
	decoder := json.NewDecoder(req.Body)
	err := decoder.Decode(&args)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	m, ok := args.(map[string]interface{})
	if !ok {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	status, err := config.MapToStatus(m)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongRequestFormat, err))
		return
	}

	statusargs := rpcs.ArgsSetStatus{
		DeviceId: uint64(device.ID),
		Status:   status,
	}
	statusreply := rpcs.ReplySetStatus{}
	err = server.RPCCallByName("controller", "Controller.SetStatus", statusargs, &statusreply)
	if err != nil {
		server.Log.Errorf("set devie status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	r.JSON(http.StatusOK, Common{})
	return

}
Exemple #24
0
// check if app has access right on device of given identifier( in url params )
func ApplicationAuthOnDeviceIdentifer(context martini.Context, params martini.Params, req *http.Request, r render.Render) {
	identifier := params["identifier"]
	key := req.Header.Get("App-Key")

	if identifier == "" || key == "" {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, errors.New("missing device identifier or app key.")))
		return
	}

	app := &models.Application{}
	err := server.RPCCallByName("registry", "Registry.ValidateApplication", key, app)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrAccessDenied, err))
		return
	}

	err = checkAppDomain(app.AppDomain, identifier)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrAccessDenied, err))
		return
	}

}
Exemple #25
0
func (t *Timer) refresh() {
	if t.c != nil {
		t.c.Stop()
	}
	t.c = cron.New()
	timers := &[]models.Rule{}
	query := &models.Rule{
		RuleType: "timer",
	}
	err := server.RPCCallByName("registry", "Registry.QueryRules", query, timers)
	if err != nil {
		server.Log.Warnf("refresh timer rules error : %v", err)
		return
	}

	sec := fmt.Sprintf("%d ", (time.Now().Second()+30)%60)

	for _, one := range *timers {
		t.c.AddFunc(sec+one.Trigger, t.createTimerFunc(one.Target, one.Action))
	}

	t.c.Start()
}
Exemple #26
0
func SetDeviceStatus(urlparams martini.Params, req *http.Request, r render.Render) {
	identifier := urlparams["identifier"]
	server.Log.Printf("ACTION GetDeviceCurrentStatus, identifier:: %v", identifier)

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, err))
		return
	}

	onlineargs := rpcs.ArgsGetDeviceOnlineStatus{
		Id: uint64(device.ID),
	}
	onlinereply := rpcs.ReplyGetDeviceOnlineStatus{}
	err = server.RPCCallByName("devicemanager", "DeviceManager.GetDeviceOnlineStatus", onlineargs, &onlinereply)
	if err != nil {
		server.Log.Errorf("get devie online status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrDeviceNotOnline, err))
		return
	}

	var args interface{}
	decoder := json.NewDecoder(req.Body)
	err = decoder.Decode(&args)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongStatusFormat, err))
		return
	}

	product := &models.Product{}
	err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrProductNotFound, err))
		return
	}

	c, err := productconfig.New(product.ProductConfig)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongProductConfig, err))
		return
	}

	m, ok := args.(map[string]interface{})
	if !ok {
		r.JSON(http.StatusOK, renderError(ErrWrongStatusFormat, err))
		return
	}

	status, err := c.MapToStatus(m)
	if err != nil {
		r.JSON(http.StatusOK, renderError(ErrWrongStatusFormat, err))
		return
	}

	statusargs := rpcs.ArgsSetStatus{
		DeviceId: uint64(device.ID),
		Status:   status,
	}
	statusreply := rpcs.ReplySetStatus{}
	err = server.RPCCallByName("controller", "Controller.SetStatus", statusargs, &statusreply)
	if err != nil {
		server.Log.Errorf("set devie status error: %v", err)
		r.JSON(http.StatusOK, renderError(ErrSystemFault, err))
		return
	}

	r.JSON(http.StatusOK, Common{})
	return

}
Exemple #27
0
func addProduct() error {
	args := models.Product{}

	reader := bufio.NewReader(os.Stdin)

	fmt.Printf("vendor ID: ")
	id, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	vendor := strings.Replace(id, "\n", "", -1)
	vendorid, err := strconv.Atoi(vendor)
	if err != nil {
		return err
	}
	args.VendorID = int32(vendorid)

	fmt.Printf("product name: ")
	name, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.ProductName = strings.Replace(name, "\n", "", -1)

	fmt.Printf("product description: ")
	desc, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.ProductDescription = strings.Replace(desc, "\n", "", -1)

	fmt.Printf("product config json file: ")
	file, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	jsonfile := strings.Replace(file, "\n", "", -1)
	fi, err := os.Open(jsonfile)
	if err != nil {
		return err
	}
	content, err := ioutil.ReadAll(fi)
	config := string(content)
	fi.Close()
	_, err = productconfig.New(config)
	if err != nil {
		return err
	}
	args.ProductConfig = config

	reply := &models.Product{}

	err = server.RPCCallByName("registry", "Registry.SaveProduct", &args, reply)
	if err != nil {
		return err
	}

	fmt.Println("=======> product created successfully:")
	printStruct(reply)
	fmt.Println("=======")

	return nil
}
Exemple #28
0
func performRuleAction(target string, action string) error {
	server.Log.Infof("trigger rule action: %v, %v", target, action)

	parts := strings.Split(target, "/")
	if len(parts) != 3 {
		return fmt.Errorf("error target format: %v", target)
	}

	identifier := parts[1]
	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
	if err != nil {
		return err
	}

	product := &models.Product{}
	err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
	if err != nil {
		return err
	}

	config, err := productconfig.New(product.ProductConfig)
	if err != nil {
		return err
	}

	var args interface{}
	err = json.Unmarshal([]byte(action), &args)
	if err != nil {
		server.Log.Errorf("marshal action error: %v", err)
		return err
	}

	m, ok := args.(map[string]interface{})
	if !ok {
		server.Log.Errorf("decode action error:%v", err)
		return fmt.Errorf("decode action error:%v", err)
	}

	sendType := parts[2]
	switch sendType {
	case "command":
		command, err := config.MapToCommand(m)
		if err != nil {
			server.Log.Errorf("action format error: %v", err)
			return err
		}

		cmdargs := rpcs.ArgsSendCommand{
			DeviceId:  uint64(device.ID),
			SubDevice: uint16(command.Head.SubDeviceid),
			No:        uint16(command.Head.No),
			WaitTime:  uint32(3000),
			Params:    command.Params,
		}
		cmdreply := rpcs.ReplySendCommand{}
		err = server.RPCCallByName("controller", "Controller.SendCommand", cmdargs, &cmdreply)
		if err != nil {
			server.Log.Errorf("send device command error: %v", err)
			return err
		}
	case "status":
		status, err := config.MapToStatus(m)
		if err != nil {
			return err
		}

		statusargs := rpcs.ArgsSetStatus{
			DeviceId: uint64(device.ID),
			Status:   status,
		}
		statusreply := rpcs.ReplySetStatus{}
		err = server.RPCCallByName("controller", "Controller.SetStatus", statusargs, &statusreply)
		if err != nil {
			server.Log.Errorf("set devie status error: %v", err)
			return err
		}
	default:
		server.Log.Errorf("wrong action %v", action)
	}

	return nil
}
Exemple #29
0
func (n *Notifier) reportEvent(event rpcs.ArgsOnEvent) error {
	server.Log.Debugf("reporting event %v", event)

	device := &models.Device{}
	err := server.RPCCallByName("registry", "Registry.FindDeviceById", int64(event.DeviceId), device)
	if err != nil {
		server.Log.Errorf("find device error : %v", err)
		return err
	}

	product := &models.Product{}
	err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
	if err != nil {
		server.Log.Errorf("find product error : %v", err)
		return err
	}

	c, err := productconfig.New(product.ProductConfig)
	if err != nil {
		server.Log.Errorf("product config error : %v", err)
		return err
	}

	ev := &protocol.Event{}
	ev.Head.No = event.No
	ev.Head.SubDeviceid = event.SubDevice
	ev.Params = event.Params

	m, err := c.EventToMap(ev)
	if err != nil {
		server.Log.Errorf("gen event json error : %v", err)
		return err
	}

	res := ReportPack{
		Tag:        "event",
		Identifier: device.DeviceIdentifier,
		Data:       m,
	}

	jsonRes, err := json.Marshal(res)
	if err != nil {
		server.Log.Errorf("json marshal error : %v", err)
		return err
	}

	reqHead := map[string]string{}
	reqHead["Content-Type"] = "application/json"

	for _, app := range n.apps {
		if nil == checkAppDomain(app.AppDomain, device.DeviceIdentifier) {
			reqHead["App-Token"] = app.AppToken
			_, err := utils.SendHttpRequest(app.ReportUrl, string(jsonRes), "POST", reqHead)
			if err != nil {
				server.Log.Errorf("http post json error : %v", err)
			}
			server.Log.Debugf("http post json succ : %v", string(jsonRes))
		}
	}

	return nil
}