Example #1
0
func (expr *PropertyExpression) Value(device datalayer.Device) (cloudvar.CloudVarValue, error) {
	switch expr.property {
	case "system.activity_status":
		// -1 = never connected
		// 0 = inactive
		// 1 = active
		last := device.LastActivityTime()
		if last == nil {
			return float64(-1), nil
		} else if time.Now().UTC().Sub(*last) > time.Minute {
			return float64(0), nil
		}
		return float64(1), nil
	case "system.ws_connected":
		return device.WSConnected(), nil
	}
	sample, err := device.LatestDataByName(expr.property)
	if err != nil {
		return nil, err
	}
	return sample.Value, nil
}
Example #2
0
func deviceToJsonObj(device datalayer.Device, timestamp_type string) (map[string]interface{}, error) {
	statusJsonObj := map[string]interface{}{
		"ws_connected": device.WSConnected(),
	}
	lastSeen := device.LastActivityTime()
	if lastSeen == nil {
		statusJsonObj["last_activity_time"] = nil
	} else {
		if timestamp_type == "epoch_us" {
			statusJsonObj["last_activity_time"] = canotime.EpochMicroseconds(*lastSeen)
		} else {
			statusJsonObj["last_activity_time"] = canotime.RFC3339(*lastSeen)
		}
	}

	out := map[string]interface{}{
		"device_id":     device.ID().String(),
		"friendly_name": device.Name(),
		"location_note": device.LocationNote(),
		"status":        statusJsonObj,
		"var_decls":     nil,
		"secret_key":    device.SecretKey(),
		"vars":          map[string]interface{}{},
		"notifs":        []interface{}{},
	}

	sddlDoc := device.SDDLDocument()
	if sddlDoc != nil {
		out["var_decls"] = sddlDoc.Json()
	}

	outDoc := device.SDDLDocument()
	if outDoc != nil {
		// get most recent value of each sensor/control
		for _, varDef := range outDoc.VarDefs() {
			sample, err := device.LatestDataByName(varDef.Name())
			if err != nil {
				continue
			}
			if timestamp_type == "epoch_us" {
				out["vars"].(map[string]interface{})[varDef.Name()] = map[string]interface{}{
					"t": canotime.EpochMicroseconds(sample.Timestamp),
					"v": sample.Value,
				}
			} else {
				out["vars"].(map[string]interface{})[varDef.Name()] = map[string]interface{}{
					"t": canotime.RFC3339(sample.Timestamp),
					"v": sample.Value,
				}
			}
		}

		// Generate JSON for notifications
		//
		/*notifications, err := device.HistoricNotifications()
		  canolog.Info("Reading notifications")
		  if err != nil {
		      canolog.Info("Error reading notifications %s", err)
		      return nil, err
		  }

		  outNotifications := []jsonNotification{};
		  for _, notification := range notifications {
		      outNotifications = append(
		              outNotifications,
		              jsonNotification{
		                  notification.Datetime().Format(time.RFC3339),
		                  notification.IsDismissed(),
		                  notification.Msg(),
		              })
		  }*/
	}

	return out, nil

}