generated from rmcguire/go-server-with-otel
add set mode option
This commit is contained in:
@@ -70,3 +70,49 @@ func (s *EconetGRPCServer) GetDevice(ctx context.Context, req *pb.GetDeviceReque
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return &pb.GetDeviceResponse{Device: deviceToProto(d)}, nil
|
||||
}
|
||||
|
||||
// modeSlugs maps the settable proto Mode enum to the normalized slugs the
|
||||
// client (and Device.mode) use. MODE_UNSPECIFIED is intentionally absent;
|
||||
// protovalidate rejects it before we get here.
|
||||
var modeSlugs = map[pb.Mode]string{
|
||||
pb.Mode_MODE_OFF: "off",
|
||||
pb.Mode_MODE_ELECTRIC: "electric",
|
||||
pb.Mode_MODE_ENERGY_SAVING: "energy-saving",
|
||||
pb.Mode_MODE_HEAT_PUMP: "heat-pump",
|
||||
pb.Mode_MODE_HIGH_DEMAND: "high-demand",
|
||||
pb.Mode_MODE_GAS: "gas",
|
||||
pb.Mode_MODE_PERFORMANCE: "performance",
|
||||
pb.Mode_MODE_VACATION: "vacation",
|
||||
}
|
||||
|
||||
func (s *EconetGRPCServer) SetMode(ctx context.Context, req *pb.SetModeRequest) (
|
||||
*pb.SetModeResponse, error,
|
||||
) {
|
||||
ctx, span := s.tracer.Start(ctx, "setMode", trace.WithAttributes(
|
||||
attribute.String("serialNumber", req.GetSerialNumber()),
|
||||
attribute.String("mode", req.GetMode().String()),
|
||||
))
|
||||
defer span.End()
|
||||
|
||||
slug, ok := modeSlugs[req.GetMode()]
|
||||
if !ok {
|
||||
err := status.Errorf(grpccodes.InvalidArgument, "unsupported mode %q", req.GetMode())
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.client.SetMode(ctx, req.GetSerialNumber(), slug); err != nil {
|
||||
err := status.Error(grpccodes.FailedPrecondition, err.Error())
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
span.SetStatus(codes.Ok, "")
|
||||
// State applies asynchronously; return the last-known snapshot. Guard against
|
||||
// a concurrent refresh evicting the device between publish and lookup.
|
||||
resp := &pb.SetModeResponse{}
|
||||
if d := s.client.Device(req.GetSerialNumber()); d != nil {
|
||||
resp.Device = deviceToProto(d)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user