| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326 |
- package main
- import (
- "bufio"
- "context"
- "crypto/rand"
- "encoding/binary"
- "encoding/hex"
- "encoding/json"
- "flag"
- "fmt"
- "os"
- "os/signal"
- "path/filepath"
- "syscall"
- "time"
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "google.golang.org/protobuf/encoding/protojson"
- "hth/internal/app"
- "hth/internal/capture"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- )
- func newCaptureID() string {
- var b [16]byte
- if _, err := rand.Read(b[:]); err != nil {
- return fmt.Sprintf("cap-%d", time.Now().UnixNano())
- }
- return hex.EncodeToString(b[:])
- }
- func main() {
- fs := flag.NewFlagSet("hth-capture", flag.ExitOnError)
- observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
- deviceID := fs.String("device", "prod2u-0", "device id")
- out := fs.String("out", "", "output directory")
- dur := fs.Duration("duration", 3*time.Second, "capture duration")
- thermal := fs.Bool("thermal", false, "capture 6400 snapshots instead of Legacy event stream")
- period := fs.Duration("period", 200*time.Millisecond, "6400 snapshot period")
- _ = fs.Parse(os.Args[1:])
- if *out == "" {
- fmt.Fprintln(os.Stderr, "hth-capture: --out required")
- os.Exit(2)
- }
- if err := os.MkdirAll(*out, 0o755); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- conn, err := grpcserver.DialUnix(*observe, 5*time.Second)
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- defer conn.Close()
- cli := hthv1.NewObserveServiceClient(conn)
- ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
- defer stop()
- if *thermal {
- if err := runThermalCapture(ctx, conn, *deviceID, *out, *dur, *period); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- return
- }
- capCtx, capCancel := context.WithTimeout(ctx, 5*time.Second)
- caps, err := cli.GetCapabilities(capCtx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
- capCancel()
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- man := capture.Manifest{
- APIVersion: app.APIVersion,
- APISchemaVersion: app.APIVersion,
- ProfileHash: caps.Capabilities.GetProtocolContractHash(),
- ProfileContractHash: caps.Capabilities.GetProtocolContractHash(),
- ProfileID: caps.Capabilities.GetProfileId(),
- ProfileRevision: caps.Capabilities.GetProfileRevision(),
- CapabilityHash: caps.Capabilities.GetCapabilityHash(),
- DeviceID: *deviceID,
- StartedAt: time.Now().UTC(),
- StartTime: time.Now().UTC(),
- Status: capture.StatusIncomplete,
- CompletionStatus: capture.StatusIncomplete,
- CaptureID: newCaptureID(),
- }
- if err := capture.WriteManifest(*out, man); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- ctx, cancel := context.WithTimeout(ctx, *dur)
- defer cancel()
- f, err := os.Create(capture.RecordsPath(*out))
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- defer func() { _ = f.Close() }()
- ev, err := cli.SubscribeEvents(ctx, &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- n := 0
- firstID, lastID := uint64(0), uint64(0)
- writeErr := error(nil)
- recvErr := error(nil)
- userCancel := false
- durationElapsed := false
- started := time.Now()
- for {
- e, err := ev.Recv()
- if err != nil {
- recvErr = err
- code := status.Code(err)
- switch {
- case ctx.Err() == context.DeadlineExceeded || code == codes.DeadlineExceeded:
- durationElapsed = true
- case ctx.Err() == context.Canceled && time.Since(started) >= *dur:
- durationElapsed = true
- case ctx.Err() == context.Canceled:
- userCancel = true
- }
- break
- }
- rec, err := capture.EventRecord(e)
- if err != nil {
- writeErr = err
- break
- }
- if err := capture.AppendRecord(f, rec); err != nil {
- writeErr = err
- break
- }
- sid := rec.SourceID()
- if n == 0 {
- firstID = sid
- }
- lastID = sid
- n++
- }
- closeErr := f.Close()
- syncErr := error(nil)
- if closeErr == nil {
- // Hash only after a successful close.
- if sum, err := capture.HashFile(capture.RecordsPath(*out)); err == nil {
- man.RecordsSHA256 = sum
- } else {
- syncErr = err
- }
- } else {
- syncErr = closeErr
- }
- man.EndedAt = time.Now().UTC()
- man.EndTime = man.EndedAt
- man.StartTime = man.StartedAt
- man.APISchemaVersion = man.APIVersion
- man.RecordCount = n
- man.FirstSourceEventID = firstID
- man.LastSourceEventID = lastID
- switch {
- case writeErr != nil || syncErr != nil:
- man.Status = capture.StatusIncomplete
- man.CompletionStatus = capture.StatusIncomplete
- if writeErr != nil {
- man.IncompleteReason = writeErr.Error()
- } else {
- man.IncompleteReason = syncErr.Error()
- }
- man.CompletionReason = man.IncompleteReason
- case durationElapsed && n > 0:
- man.Status = capture.StatusComplete
- man.CompletionStatus = capture.StatusComplete
- man.CompletionReason = "duration elapsed"
- case n > 0 && time.Since(started) >= *dur:
- man.Status = capture.StatusComplete
- man.CompletionStatus = capture.StatusComplete
- man.CompletionReason = "duration elapsed"
- case userCancel:
- man.Status = capture.StatusIncomplete
- man.CompletionStatus = capture.StatusIncomplete
- man.IncompleteReason = "user cancel"
- man.CompletionReason = man.IncompleteReason
- case n == 0:
- man.Status = capture.StatusIncomplete
- man.CompletionStatus = capture.StatusIncomplete
- man.IncompleteReason = "zero records"
- man.CompletionReason = man.IncompleteReason
- default:
- man.Status = capture.StatusIncomplete
- man.CompletionStatus = capture.StatusIncomplete
- if recvErr != nil {
- man.IncompleteReason = "stream ended: " + recvErr.Error()
- } else {
- man.IncompleteReason = "unexpected stream end"
- }
- man.CompletionReason = man.IncompleteReason
- }
- if err := capture.WriteManifest(*out, man); err != nil {
- fmt.Fprintf(os.Stderr, "hth-capture manifest failed after %d records: %v\n", n, err)
- os.Exit(1)
- }
- if writeErr != nil || syncErr != nil || man.Status != capture.StatusComplete {
- fmt.Fprintf(os.Stderr, "hth-capture incomplete after %d records status=%s recv=%v write=%v close=%v\n", n, man.Status, recvErr, writeErr, syncErr)
- os.Exit(1)
- }
- fmt.Printf("wrote %d records to %s status=%s\n", n, *out, man.Status)
- }
- func runThermalCapture(parent context.Context, conn *grpc.ClientConn, deviceID, out string, duration, period time.Duration) error {
- if duration <= 0 || period <= 0 {
- return fmt.Errorf("thermal capture duration and period must be positive")
- }
- client := hthv1.NewThermalObserveServiceClient(conn)
- ctx, cancel := context.WithTimeout(parent, duration)
- defer cancel()
- rawPath := filepath.Join(out, "raw-frames.bin")
- jsonlPath := filepath.Join(out, "thermal-snapshots.jsonl")
- rawFile, err := os.Create(rawPath)
- if err != nil {
- return err
- }
- jsonFile, err := os.Create(jsonlPath)
- if err != nil {
- rawFile.Close()
- return err
- }
- rawWriter := bufio.NewWriter(rawFile)
- jsonWriter := bufio.NewWriter(jsonFile)
- started := time.Now().UTC()
- count := 0
- contractHash := ""
- profile := ""
- ticker := time.NewTicker(period)
- defer ticker.Stop()
- for {
- resp, err := client.CaptureSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: deviceID})
- if err != nil {
- if ctx.Err() != nil && count > 0 {
- break
- }
- return err
- }
- snapshot := resp.GetSnapshot()
- if snapshot == nil || len(snapshot.GetRawPayload()) == 0 {
- return fmt.Errorf("thermal snapshot has no raw payload")
- }
- contractHash = snapshot.GetContractSha256()
- profile = snapshot.GetFirmwareProfile()
- if err := binary.Write(rawWriter, binary.LittleEndian, uint32(len(snapshot.GetRawPayload()))); err != nil {
- return err
- }
- if _, err := rawWriter.Write(snapshot.GetRawPayload()); err != nil {
- return err
- }
- message, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(snapshot)
- if err != nil {
- return err
- }
- record, _ := json.Marshal(struct {
- SampleIndex int `json:"sample_index"`
- Snapshot json.RawMessage `json:"snapshot"`
- }{SampleIndex: count, Snapshot: message})
- if _, err := jsonWriter.Write(append(record, '\n')); err != nil {
- return err
- }
- count++
- select {
- case <-ctx.Done():
- if count > 0 {
- break
- }
- return ctx.Err()
- case <-ticker.C:
- continue
- }
- break
- }
- if err := rawWriter.Flush(); err != nil {
- return err
- }
- if err := jsonWriter.Flush(); err != nil {
- return err
- }
- if err := rawFile.Close(); err != nil {
- return err
- }
- if err := jsonFile.Close(); err != nil {
- return err
- }
- rawSHA, err := capture.HashFile(rawPath)
- if err != nil {
- return err
- }
- jsonSHA, err := capture.HashFile(jsonlPath)
- if err != nil {
- return err
- }
- meta := map[string]any{
- "schema": "hth-6400-capture-v1", "device_id": deviceID,
- "firmware_profile": profile, "contract_sha256": contractHash,
- "started_at": started, "ended_at": time.Now().UTC(), "record_count": count,
- "hardware_validation": "NOT RUN", "com_validation": "NOT RUN",
- "real_thermal_performance": "NOT RUN",
- }
- metaBytes, _ := json.MarshalIndent(meta, "", " ")
- runPath := filepath.Join(out, "run.json")
- if err := os.WriteFile(runPath, append(metaBytes, '\n'), 0o644); err != nil {
- return err
- }
- runSHA, err := capture.HashFile(runPath)
- if err != nil {
- return err
- }
- checksums := fmt.Sprintf("%s raw-frames.bin\n%s thermal-snapshots.jsonl\n%s run.json\n", rawSHA, jsonSHA, runSHA)
- if err := os.WriteFile(filepath.Join(out, "checksums.sha256"), []byte(checksums), 0o644); err != nil {
- return err
- }
- fmt.Printf("wrote %d thermal snapshots to %s\n", count, out)
- return nil
- }
|