aboutsummaryrefslogtreecommitdiff
path: root/pw_trace_tokenized/example/public/pw_trace_tokenized/example/trace_to_file.h
blob: 97a8bb8017e5d7596365d75c2bc27af4630a30df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2020 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//==============================================================================
//

#pragma once

#include <stdio.h>

#include <fstream>

#include "pw_trace_tokenized/trace_callback.h"

namespace pw {
namespace trace {

class TraceToFile {
 public:
  TraceToFile(Callbacks& callbacks, const char* file_name)
      : callbacks_(callbacks) {
    callbacks_
        .RegisterSink(TraceSinkStartBlock,
                      TraceSinkAddBytes,
                      TraceSinkEndBlock,
                      &out_,
                      &sink_handle_)
        .IgnoreError();  // TODO: b/242598609 - Handle Status properly
    out_.open(file_name, std::ios::out | std::ios::binary);
  }

  ~TraceToFile() {
    callbacks_.UnregisterSink(sink_handle_)
        .IgnoreError();  // TODO: b/242598609 - Handle Status properly
    out_.close();
  }

  static void TraceSinkStartBlock(void* user_data, size_t size) {
    std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data);
    uint8_t b = static_cast<uint8_t>(size);
    out->write(reinterpret_cast<const char*>(&b), sizeof(b));
  }

  static void TraceSinkAddBytes(void* user_data,
                                const void* bytes,
                                size_t size) {
    std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data);
    out->write(reinterpret_cast<const char*>(bytes), size);
  }

  static void TraceSinkEndBlock(void* user_data) {
    std::ofstream* out = reinterpret_cast<std::ofstream*>(user_data);
    out->flush();
  }

 private:
  Callbacks& callbacks_;
  std::ofstream out_;
  Callbacks::SinkHandle sink_handle_;
};

}  // namespace trace
}  // namespace pw