message: Minor improvements to data tracing
  Timestamps are added to saved trace data
  controller is queried to find sample time rather then hard code it
diff: @@ -49,10 +49,6 @@ VAR_INT32 = 1
  VAR_UINT32 = 2
  VAR_FLOAT = 3
  -# Frequency with which the controller's high-priority loop runs, in
  -# milliseconds. Keep this in sync with Conrtroller::GetLoopPeriod().
  -PID_SAMPLE_PERIOD_MS = 10
  -
  # Can trace this many variables at once. Keep this in sync with TRACE_VAR_CT
  # in the controller.
  TRACE_VAR_CT = 4
  @@ -454,6 +450,9 @@ trace_samples
  SetVar(f"trace_var{i + 1}", var)
  SendCmd(OP_TRACE, [SUBCMD_TRACE_FLUSH])
  +
  + # The transition from 0 to 1 resets and starts the trace
  + SetVar("trace_ctrl", 0)
  SetVar("trace_ctrl", 1)
  elif cl[0] == "download":
  @@ -475,11 +474,7 @@ trace_samples
  return
  dat = TraceDownload()
  - with open(args.dest, "w") as fp:
  - fp.write(args.separator.join(v.name for v in tv) + "\n")
  - for i in range(len(dat[0])):
  - line = (tv[j].fmt % dat[j][i] for j in range(len(tv)))
  - fp.write(args.separator.join(line) + "\n")
  + TraceSaveDat(dat, fname=args.dest, separator=args.separator)
  elif cl[0] == "graph":
  TraceGraph()
  @@ -643,7 +638,6 @@ def TraceDownload():
  ct = GetVar("trace_samples", raw=True) * len(traceVars)
  - print("Download trace data...")
  data = []
  while len(data) < 4 * ct:
  dat = SendCmd(OP_TRACE, [SUBCMD_TRACE_GETDATA])
  @@ -668,6 +662,15 @@ def TraceDownload():
  for sample in zip(*iters):
  for i, val in enumerate(sample):
  ret[i].append(traceVars[i].ConvertInt(val))
  +
  + per = GetVar("trace_period", raw=True)
  + if per < 1:
  + per = 1
  + per *= GetVar("loop_period", raw=True) * 1e-6
  +
  + time = [x * per for x in range(len(ret[0]))]
  + ret.insert(0, time)
  +
  return ret
  @@ -676,13 +679,8 @@ def TraceGraph():
  dat = TraceDownload()
  TraceSaveDat(dat, "last_graph.dat")
  - # trace_period <= 0 is canonically interpreted as 1.
  - trace_period = GetVar("trace_period", raw=True)
  - if trace_period <= 0:
  - trace_period = 1
  - trace_period_ms = trace_period * PID_SAMPLE_PERIOD_MS
  -
  - timestamps_sec = [t * trace_period_ms / 1000 for t in range(len(dat[0]))]
  + timestamps_sec = dat[0]
  + dat = dat[1:]
  plt.figure()
  for i, d in enumerate(dat):
  plt.plot(timestamps_sec, d, label=traceVars[i].help)
  @@ -701,15 +699,15 @@ def TraceSaveDat(dat, fname, separator=" "):
  tv = TraceActiveVars()
  fp = open(fname, "w")
  - line = []
  + line = ["time"]
  for v in tv:
  line.append(v.name)
  fp.write(separator.join(line) + "\n")
  for i in range(len(dat[0])):
  - line = []
  + line = ["%.3f" % dat[0][i]]
  for j in range(len(tv)):
  - line.append(tv[j].fmt % dat[j][i])
  + line.append(tv[j].fmt % dat[j + 1][i])
  fp.write(separator.join(line) + "\n")
  fp.close()
  