Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_trace / example / sample_app.cc
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 //==============================================================================
15 // ninja -C out/host trace_sample
16 // ./out/host/obj/pw_trace_tokenized/trace_sample
17 // python pw_trace_tokenized/py/trace.py -i out1.bin -o trace.json
18 //       ./out/host/obj/pw_trace_tokenized/trace_sample
19 #include <stdio.h>
20
21 #include <array>
22 #include <chrono>
23
24 #include "pw_ring_buffer/prefixed_entry_ring_buffer.h"
25 #include "pw_trace/trace.h"
26
27 #ifndef SAMPLE_APP_SLEEP_MILLIS
28 #include <thread>
29 #define SAMPLE_APP_SLEEP_MILLIS(millis) \
30   std::this_thread::sleep_for(std::chrono::milliseconds(millis));
31 #endif  // SAMPLE_APP_SLEEP_MILLIS
32
33 using namespace std::chrono;
34
35 namespace {
36
37 // Time helper function
38 auto start = system_clock::now();
39 uint32_t GetTimeSinceBootMillis() {
40   auto delta = system_clock::now() - start;
41   return floor<milliseconds>(delta).count();
42 }
43
44 // Creating a very simple runnable with predictable behaviour to help with the
45 // example. Each Runnable, has a method ShouldRun which indicates if it has work
46 // to do, calling Run will then do the work.
47 class SimpleRunnable {
48  public:
49   virtual const char* Name() const = 0;
50   virtual bool ShouldRun() = 0;
51   virtual void Run() = 0;
52   virtual ~SimpleRunnable() {}
53 };
54
55 // Processing module
56 // Uses trace_id and groups to track the multiple stages of "processing".
57 // These are intentionally long running so they will be processing concurrently.
58 // The trace ID is used to seperates these concurrent jobs.
59 #undef PW_TRACE_MODULE_NAME
60 #define PW_TRACE_MODULE_NAME "Processing"
61 class ProcessingTask : public SimpleRunnable {
62  public:
63   // Run task maintains a buffer of "jobs" which just sleeps for an amount of
64   // time and reposts the job until the value is zero. This gives an async
65   // behaviour where multiple of the same job are happening concurrently, and
66   // also has a nesting effect of a job having many stages.
67   struct Job {
68     uint32_t job_id;
69     uint8_t value;
70   };
71   struct JobBytes {
72     union {
73       Job job;
74       std::byte bytes[sizeof(Job)];
75     };
76   };
77   ProcessingTask() {
78     // Buffer is used for the job queue.
79     std::span<std::byte> buf_span = std::span<std::byte>(
80         reinterpret_cast<std::byte*>(jobs_buffer_), sizeof(jobs_buffer_));
81     jobs_.SetBuffer(buf_span);
82   }
83   const char* Name() const override { return "Processing Task"; }
84   bool ShouldRun() override { return jobs_.EntryCount() > 0; }
85   void Run() override {
86     JobBytes job_bytes;
87     size_t bytes_read;
88
89     // Trace the job count backlog
90     size_t entry_count = jobs_.EntryCount();
91
92     // Get the next job from the queue.
93     jobs_.PeekFront(job_bytes.bytes, &bytes_read);
94     jobs_.PopFront();
95     Job& job = job_bytes.job;
96
97     // Process the job
98     ProcessingJob(job);
99     if (job.value > 0) {  // repost for more work if value > 0
100       AddJobInternal(job.job_id, job.value - 1);
101     } else {
102       PW_TRACE_END("Job", "Process", job.job_id);
103     }
104     PW_TRACE_INSTANT_DATA("job_backlog_count",
105                           "@pw_arg_counter",
106                           &entry_count,
107                           sizeof(entry_count));
108   }
109   void AddJob(uint32_t job_id, uint8_t value) {
110     PW_TRACE_START_DATA(
111         "Job", "Process", job_id, "@pw_py_struct_fmt:B", &value, sizeof(value));
112     AddJobInternal(job_id, value);
113   }
114
115  private:
116   static constexpr size_t kMaxJobs = 10;
117   static constexpr size_t kProcessingTimePerValueMillis = 250;
118   Job jobs_buffer_[kMaxJobs];
119   pw::ring_buffer::PrefixedEntryRingBuffer jobs_{false};
120
121   void ProcessingJob(const Job& job) {
122     PW_TRACE_FUNCTION("Process", job.job_id);
123     for (uint8_t i = 0; i < job.value; i++) {
124       PW_TRACE_SCOPE("loop", "Process", job.job_id);
125       SAMPLE_APP_SLEEP_MILLIS(50);  // Fake processing time
126       SomeProcessing(&job);
127     }
128   }
129
130   void SomeProcessing(const Job* job) {
131     uint32_t id = job->job_id;
132     PW_TRACE_FUNCTION("Process", id);
133     SAMPLE_APP_SLEEP_MILLIS(
134         kProcessingTimePerValueMillis);  // Fake processing time
135   }
136   void AddJobInternal(uint32_t job_id, uint8_t value) {
137     JobBytes job{.job = {.job_id = job_id, .value = value}};
138     jobs_.PushBack(job.bytes);
139   }
140 } processing_task;
141
142 // Input Module
143 // Uses traces in groups to indicate the different steps of reading the new
144 // event.
145 // Uses an instant data event to dump the read sample into the trace.
146 #undef PW_TRACE_MODULE_NAME
147 #define PW_TRACE_MODULE_NAME "Input"
148 class InputTask : public SimpleRunnable {
149   // Every second generate new output
150  public:
151   const char* Name() const override { return "Input Task"; }
152   bool ShouldRun() override {
153     return (GetTimeSinceBootMillis() - last_run_time_ > kRunInterval);
154   }
155   void Run() override {
156     last_run_time_ = GetTimeSinceBootMillis();
157     PW_TRACE_FUNCTION("Input");
158     SAMPLE_APP_SLEEP_MILLIS(50);
159     uint8_t value = GetValue();
160     PW_TRACE_INSTANT_DATA("value", "@pw_arg_counter", &value, sizeof(value));
161     processing_task.AddJob(sample_count_, value);
162     sample_count_++;
163   }
164
165  private:
166   uint8_t GetValue() {
167     PW_TRACE_FUNCTION("Input");
168     SAMPLE_APP_SLEEP_MILLIS(100);  // Fake processing time
169     return sample_count_ % 4 + 1;
170   }
171   size_t sample_count_ = 0;
172   uint32_t last_run_time_ = 0;
173   static constexpr uint32_t kRunInterval = 1000;
174 } input_task;
175
176 // Simple main loop acting as the "Kernel"
177 // Uses simple named trace durations to indicate which task/job is running
178 #undef PW_TRACE_MODULE_NAME
179 #define PW_TRACE_MODULE_NAME "Kernel"
180 void StartFakeKernel() {
181   std::array<SimpleRunnable*, 2> tasks = {&input_task, &processing_task};
182
183   bool idle = false;
184   while (true) {
185     bool have_any_run = false;
186     for (auto& task : tasks) {
187       if (task->ShouldRun()) {
188         if (idle) {
189           PW_TRACE_END("Idle", "Idle");
190           idle = false;
191         }
192         have_any_run = true;
193         // The task name is not a string literal and is therefore put in the
194         // data section, so it can also work with tokenized trace.
195         PW_TRACE_START_DATA(
196             "Running", "@pw_arg_group", task->Name(), strlen(task->Name()));
197         task->Run();
198         PW_TRACE_END_DATA(
199             "Running", "@pw_arg_group", task->Name(), strlen(task->Name()));
200       }
201     }
202     if (!idle && !have_any_run) {
203       PW_TRACE_START("Idle", "Idle");
204       idle = true;
205     }
206   }
207 }
208
209 }  // namespace
210
211 void RunTraceSampleApp() { StartFakeKernel(); }