-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadedHSM.hpp
More file actions
1441 lines (1260 loc) · 51 KB
/
ThreadedHSM.hpp
File metadata and controls
1441 lines (1260 loc) · 51 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file ThreadedHSM.hpp
* @brief Threaded Hierarchical State Machine with Commands support
*
* Extends the basic HSM with:
* - Commands (non-state-changing actions restricted to specific states)
* - JSON message protocol for inter-thread communication
* - Synchronous and asynchronous command execution
* - Command buffering with futures/promises
* - Thread-safe message queue
*
* JSON Message Protocol:
* {
* "id": <unique_identifier>,
* "type": "event" | "command",
* "name": <event_or_command_name>,
* "params": { ... },
* "sync": true | false
* }
*
* Response Format:
* {
* "id": <same_identifier>,
* "success": true | false,
* "result": { ... } | null,
* "error": <error_message> | null
* }
*/
#pragma once
#include "LaserTrackerHSM.hpp"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <variant>
namespace LaserTracker
{
// ============================================================================
// JSON Message Types (Simple implementation without external dependencies)
// ============================================================================
/**
* @brief Simple JSON-like value representation
*/
struct JsonValue
{
using Object = std::unordered_map<std::string, JsonValue>;
using Array = std::vector<JsonValue>;
using Value = std::variant<std::nullptr_t, bool, int, double, std::string, Array, Object>;
Value value;
JsonValue() : value(nullptr) {}
JsonValue(std::nullptr_t) : value(nullptr) {}
JsonValue(bool b) : value(b) {}
JsonValue(int i) : value(i) {}
JsonValue(double d) : value(d) {}
JsonValue(const char* s) : value(std::string(s)) {}
JsonValue(const std::string& s) : value(s) {}
JsonValue(std::string&& s) : value(std::move(s)) {}
JsonValue(Array arr) : value(std::move(arr)) {}
JsonValue(Object obj) : value(std::move(obj)) {}
bool isNull() const { return std::holds_alternative<std::nullptr_t>(value); }
bool isBool() const { return std::holds_alternative<bool>(value); }
bool isInt() const { return std::holds_alternative<int>(value); }
bool isDouble() const { return std::holds_alternative<double>(value); }
bool isString() const { return std::holds_alternative<std::string>(value); }
bool isArray() const { return std::holds_alternative<Array>(value); }
bool isObject() const { return std::holds_alternative<Object>(value); }
bool asBool() const { return std::get<bool>(value); }
int asInt() const { return std::get<int>(value); }
double asDouble() const { return std::get<double>(value); }
const std::string& asString() const { return std::get<std::string>(value); }
const Array& asArray() const { return std::get<Array>(value); }
const Object& asObject() const { return std::get<Object>(value); }
Object& asObject() { return std::get<Object>(value); }
JsonValue& operator[](const std::string& key)
{
if (!isObject())
{
value = Object{};
}
return std::get<Object>(value)[key];
}
const JsonValue& at(const std::string& key) const { return std::get<Object>(value).at(key); }
bool contains(const std::string& key) const
{
if (!isObject())
return false;
return std::get<Object>(value).count(key) > 0;
}
/**
* @brief Serialize to JSON string
*/
std::string toJson() const
{
return std::visit(
[](const auto& v) -> std::string
{
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, std::nullptr_t>)
{
return "null";
}
else if constexpr (std::is_same_v<T, bool>)
{
return v ? "true" : "false";
}
else if constexpr (std::is_same_v<T, int>)
{
return std::to_string(v);
}
else if constexpr (std::is_same_v<T, double>)
{
std::ostringstream oss;
oss << std::fixed << std::setprecision(6) << v;
return oss.str();
}
else if constexpr (std::is_same_v<T, std::string>)
{
return "\"" + escapeString(v) + "\"";
}
else if constexpr (std::is_same_v<T, Array>)
{
std::string result = "[";
for (size_t i = 0; i < v.size(); ++i)
{
if (i > 0)
result += ",";
result += v[i].toJson();
}
return result + "]";
}
else if constexpr (std::is_same_v<T, Object>)
{
std::string result = "{";
bool first = true;
for (const auto& [key, val] : v)
{
if (!first)
result += ",";
first = false;
result += "\"" + escapeString(key) + "\":" + val.toJson();
}
return result + "}";
}
return "null";
},
value);
}
private:
static std::string escapeString(const std::string& s)
{
std::string result;
for (char c : s)
{
switch (c)
{
case '"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result += c;
}
}
return result;
}
};
// ============================================================================
// Unified Message Type
// ============================================================================
/**
* @brief Unified message for both requests and responses
*
* Request fields:
* - id: Unique identifier for correlation
* - name: Name of the message (event/command name)
* - params: Parameters for the message
* - sync: If true, sender waits for result before processing next
* - timeoutMs: Timeout in milliseconds for reply (0 = no timeout)
* - timestamp: Creation time of the message
*
* Response fields (when isResponse=true):
* - success: True if executed successfully
* - result: Result data (stored in params)
* - error: Error message if failed
*
* The HSM determines whether a message triggers a state change or not.
* Commands can also cause state changes (e.g., error conditions).
*/
struct Message
{
using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;
uint64_t id = 0; // Unique identifier for correlation
std::string name; // Name of event/command
JsonValue params; // Parameters (request) or result data (response)
bool sync = false; // If true, sender waits for completion
bool needsReply = false; // If true, a response is expected
uint32_t timeoutMs = 5000; // Timeout in ms for reply (0 = no timeout)
TimePoint timestamp; // When the message was created
// Response-specific fields
bool isResponse = false; // True if this is a response message
bool success = false; // True if executed successfully
std::string error; // Error message (if failed)
Message() : timestamp(Clock::now()) {}
/**
* @brief Check if the message has timed out
*/
bool isTimedOut() const
{
if (timeoutMs == 0)
return false;
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timestamp);
return elapsed.count() > timeoutMs;
}
/**
* @brief Get remaining time until timeout
*/
std::chrono::milliseconds remainingTime() const
{
if (timeoutMs == 0)
return std::chrono::milliseconds::max();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timestamp);
auto remaining = static_cast<int64_t>(timeoutMs) - elapsed.count();
return std::chrono::milliseconds(std::max<int64_t>(0, remaining));
}
/**
* @brief Get age of message in milliseconds
*/
uint64_t ageMs() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timestamp).count();
}
/**
* @brief Create a response from a request
*/
static Message createResponse(uint64_t requestId, bool success, JsonValue result = {}, const std::string& error = "")
{
Message resp;
resp.id = requestId;
resp.isResponse = true;
resp.success = success;
resp.params = std::move(result);
resp.error = error;
return resp;
}
/**
* @brief Create a timeout error response
*/
static Message createTimeoutResponse(uint64_t requestId)
{
return createResponse(requestId, false, {}, "Request timed out");
}
std::string toJson() const
{
JsonValue obj = JsonValue::Object{};
obj["id"] = static_cast<int>(id);
obj["name"] = name;
obj["timestamp_ms"] = static_cast<int>(ageMs()); // Age since creation
if (isResponse)
{
obj["isResponse"] = true;
obj["success"] = success;
obj["result"] = params;
if (!error.empty())
{
obj["error"] = error;
}
}
else
{
obj["params"] = params;
obj["sync"] = sync;
obj["timeoutMs"] = static_cast<int>(timeoutMs);
}
return obj.toJson();
}
};
// ============================================================================
// Commands - Non-state-changing actions
// ============================================================================
namespace Commands
{
/**
* @brief Home command - moves laser tracker to home position
* Valid in: Idle state
* Sync: Yes (waits for homing to complete)
*/
struct Home
{
static constexpr const char* name = "Home";
static constexpr bool sync = true;
// Parameters
double speed = 100.0; // Homing speed percentage (0-100)
std::string getName() const { return name; }
};
/**
* @brief GetPosition command - retrieves current position
* Valid in: Idle, Locked, Measuring states
* Sync: No (returns immediately with current position)
*/
struct GetPosition
{
static constexpr const char* name = "GetPosition";
static constexpr bool sync = false;
std::string getName() const { return name; }
};
/**
* @brief SetLaserPower command - adjusts laser power
* Valid in: Any Operational state
* Sync: No
*/
struct SetLaserPower
{
static constexpr const char* name = "SetLaserPower";
static constexpr bool sync = false;
double powerLevel = 1.0; // 0.0 to 1.0
std::string getName() const { return name; }
};
/**
* @brief Compensate command - applies environmental compensation
* Valid in: Idle, Locked states
* Sync: Yes (waits for compensation calculation)
*/
struct Compensate
{
static constexpr const char* name = "Compensate";
static constexpr bool sync = true;
double temperature = 20.0; // Celsius
double pressure = 1013.25; // hPa
double humidity = 50.0; // Percentage
std::string getName() const { return name; }
};
/**
* @brief GetStatus command - retrieves system status
* Valid in: Any state
* Sync: No
*/
struct GetStatus
{
static constexpr const char* name = "GetStatus";
static constexpr bool sync = false;
std::string getName() const { return name; }
};
/**
* @brief MoveRelative command - moves tracker by relative amount
* Valid in: Idle, Locked states
* Sync: Yes (waits for move to complete)
*/
struct MoveRelative
{
static constexpr const char* name = "MoveRelative";
static constexpr bool sync = true;
double azimuth = 0.0; // Degrees
double elevation = 0.0; // Degrees
std::string getName() const { return name; }
};
} // namespace Commands
// Command variant - all possible commands
using Command = std::variant<Commands::Home, Commands::GetPosition, Commands::SetLaserPower, Commands::Compensate, Commands::GetStatus,
Commands::MoveRelative>;
// ============================================================================
// Thread-Safe Message Queue
// ============================================================================
/**
* @brief Thread-safe FIFO queue for messages
*/
template <typename T> class ThreadSafeQueue
{
public:
void push(T item)
{
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push_back(std::move(item));
}
cv_.notify_one();
}
void pushFront(T item)
{
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push_front(std::move(item));
}
cv_.notify_one();
}
std::optional<T> tryPop()
{
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty())
{
return std::nullopt;
}
T item = std::move(queue_.front());
queue_.pop_front();
return item;
}
T waitPop()
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return !queue_.empty() || stopped_; });
if (stopped_ && queue_.empty())
{
throw std::runtime_error("Queue stopped");
}
T item = std::move(queue_.front());
queue_.pop_front();
return item;
}
std::optional<T> waitPopFor(std::chrono::milliseconds timeout)
{
std::unique_lock<std::mutex> lock(mutex_);
if (!cv_.wait_for(lock, timeout, [this] { return !queue_.empty() || stopped_; }))
{
return std::nullopt;
}
if (stopped_ && queue_.empty())
{
return std::nullopt;
}
T item = std::move(queue_.front());
queue_.pop_front();
return item;
}
void stop()
{
{
std::lock_guard<std::mutex> lock(mutex_);
stopped_ = true;
}
cv_.notify_all();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
size_t size() const
{
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
void clear()
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.clear();
}
private:
mutable std::mutex mutex_;
std::condition_variable cv_;
std::deque<T> queue_;
bool stopped_ = false;
};
// ============================================================================
// Pending Message Entry
// ============================================================================
struct PendingMessage
{
Message message;
std::promise<Message> promise; // For sync messages waiting for response
PendingMessage() = default;
PendingMessage(Message msg) : message(std::move(msg)) {}
};
// ============================================================================
// Threaded HSM - State Machine running in its own thread
// ============================================================================
/**
* @brief Threaded HSM with command support and JSON messaging
*
* The HSM runs in a dedicated thread, receiving messages (events/commands)
* via a thread-safe message queue. Responses are sent back through
* a separate queue or via futures for synchronous messages.
*
* There is no distinction between events and commands - the HSM determines
* whether a message triggers a state change based on its name and current state.
*/
class ThreadedHSM
{
public:
ThreadedHSM() : running_(false), nextMessageId_(1), syncMessageInProgress_(false) { std::cout << "=== Threaded Laser Tracker HSM Created ===\n"; }
~ThreadedHSM() { stop(); }
/**
* @brief Start the HSM thread
*/
void start()
{
if (running_.exchange(true))
{
return; // Already running
}
workerThread_ = std::thread(&ThreadedHSM::workerLoop, this);
std::cout << "[ThreadedHSM] Worker thread started\n";
}
/**
* @brief Stop the HSM thread
*/
void stop()
{
if (!running_.exchange(false))
{
return; // Already stopped
}
messageQueue_.stop();
if (workerThread_.joinable())
{
workerThread_.join();
}
std::cout << "[ThreadedHSM] Worker thread stopped\n";
}
/**
* @brief Check if HSM thread is running
*/
bool isRunning() const { return running_.load(); }
// --------------------------------------------------------------------
// Unified Message Sending Interface
// --------------------------------------------------------------------
/**
* @brief Send a message asynchronously (fire and forget)
* @return Message ID for tracking
*/
uint64_t sendAsync(const std::string& name, JsonValue params = {}, bool sync = false)
{
Message msg;
msg.id = nextMessageId_++;
msg.name = name;
msg.params = std::move(params);
msg.sync = sync;
msg.needsReply = false;
msg.timeoutMs = 0; // No timeout for async
queueMessage(std::move(msg));
return msg.id;
}
/**
* @brief Send a message and wait for response
* @param name Message name
* @param params Message parameters
* @param sync If true, HSM blocks other messages until this completes
* @param timeoutMs Timeout in milliseconds (0 = no timeout)
* @return Response message
*/
Message send(const std::string& name, JsonValue params = {}, bool sync = false, uint32_t timeoutMs = 30000)
{
Message msg;
msg.id = nextMessageId_++;
msg.name = name;
msg.params = std::move(params);
msg.sync = sync;
msg.needsReply = true;
msg.timeoutMs = timeoutMs;
// timestamp is set automatically in constructor
return sendAndWait(std::move(msg));
}
// --------------------------------------------------------------------
// Convenience methods for Events (state-changing messages)
// --------------------------------------------------------------------
uint64_t sendEventAsync(const Event& event)
{
return sendAsync(getEventName(event), eventToParams(event), false);
}
Message sendEventSync(const Event& event, uint32_t timeoutMs = 5000)
{
return send(getEventName(event), eventToParams(event), false, timeoutMs);
}
// --------------------------------------------------------------------
// Convenience methods for Commands (may or may not change state)
// --------------------------------------------------------------------
uint64_t sendCommandAsync(const Command& cmd)
{
return sendAsync(getCommandName(cmd), commandToParams(cmd), isCommandSync(cmd));
}
Message sendCommand(const Command& cmd, uint32_t timeoutMs = 30000)
{
return send(getCommandName(cmd), commandToParams(cmd), isCommandSync(cmd), timeoutMs);
}
// --------------------------------------------------------------------
// JSON Message Interface
// --------------------------------------------------------------------
/**
* @brief Send a raw JSON message
* @return Message ID
*/
uint64_t sendJsonMessage(const std::string& json)
{
Message msg = parseJsonMessage(json);
if (msg.id == 0)
{
msg.id = nextMessageId_++;
}
queueMessage(std::move(msg));
return msg.id;
}
/**
* @brief Get response from async response queue
*/
std::optional<Message> tryGetResponse() { return responseQueue_.tryPop(); }
/**
* @brief Wait for a specific response
*/
std::optional<Message> waitForResponse(uint64_t messageId, std::chrono::milliseconds timeout = std::chrono::milliseconds(5000))
{
auto deadline = std::chrono::steady_clock::now() + timeout;
while (std::chrono::steady_clock::now() < deadline)
{
auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
auto response = responseQueue_.waitPopFor(remaining);
if (response && response->id == messageId)
{
return response;
}
// Put back if not our response
if (response)
{
responseQueue_.pushFront(std::move(*response));
}
}
return std::nullopt;
}
// --------------------------------------------------------------------
// State Query Interface (thread-safe)
// --------------------------------------------------------------------
/**
* @brief Get current state name (thread-safe)
*/
std::string getCurrentStateName() const
{
std::lock_guard<std::mutex> lock(stateMutex_);
return hsm_.getCurrentStateName();
}
/**
* @brief Check if in a specific state type
*/
template <typename S> bool isInState() const
{
std::lock_guard<std::mutex> lock(stateMutex_);
return hsm_.isInState<S>();
}
private:
HSM hsm_;
std::thread workerThread_;
std::atomic<bool> running_;
std::atomic<uint64_t> nextMessageId_;
mutable std::mutex stateMutex_;
// Message queues
ThreadSafeQueue<PendingMessage> messageQueue_;
ThreadSafeQueue<Message> responseQueue_;
// Buffered messages (waiting for sync message to complete)
std::deque<PendingMessage> messageBuffer_;
std::atomic<bool> syncMessageInProgress_;
std::mutex bufferMutex_;
// Pending sync requests (id -> promise)
std::unordered_map<uint64_t, std::promise<Message>> pendingPromises_;
std::mutex promiseMutex_;
// --------------------------------------------------------------------
// Worker Thread Loop
// --------------------------------------------------------------------
void workerLoop()
{
std::cout << "[HSM Thread] Started\n";
while (running_.load())
{
try
{
auto pending = messageQueue_.waitPopFor(std::chrono::milliseconds(100));
if (!pending)
{
continue;
}
processMessage(std::move(*pending));
}
catch (const std::exception& e)
{
std::cerr << "[HSM Thread] Exception: " << e.what() << "\n";
}
}
std::cout << "[HSM Thread] Stopped\n";
}
void processMessage(PendingMessage pending)
{
const Message& msg = pending.message;
std::cout << "\n[HSM Thread] Processing: '" << msg.name << "' (id=" << msg.id << ", sync=" << (msg.sync ? "true" : "false") << ", age=" << msg.ageMs()
<< "ms)\n";
// Check if message has already timed out
if (msg.needsReply && msg.isTimedOut())
{
std::cout << "[HSM Thread] Message timed out before processing (age=" << msg.ageMs() << "ms, timeout=" << msg.timeoutMs << "ms)\n";
// The sender has already timed out, no point processing
// But still need to clean up any pending promise
{
std::lock_guard<std::mutex> lock(promiseMutex_);
pendingPromises_.erase(msg.id);
}
return;
}
// If a sync message is in progress, buffer this message
if (syncMessageInProgress_.load() && msg.sync)
{
std::cout << "[HSM Thread] Sync message in progress, buffering\n";
std::lock_guard<std::mutex> lock(bufferMutex_);
messageBuffer_.push_back(std::move(pending));
return;
}
// Mark sync in progress if this is a sync message
if (msg.sync)
{
syncMessageInProgress_.store(true);
}
// Process the message - try as event first, then as command
Message response = processMessageContent(msg);
// Send response if needed
if (msg.needsReply)
{
// Check if there's a promise waiting
{
std::lock_guard<std::mutex> lock(promiseMutex_);
auto it = pendingPromises_.find(msg.id);
if (it != pendingPromises_.end())
{
it->second.set_value(response);
pendingPromises_.erase(it);
}
else
{
// Otherwise put in response queue
responseQueue_.push(std::move(response));
}
}
}
// If this was a sync message and it completed, process buffered messages
if (msg.sync)
{
syncMessageInProgress_.store(false);
processBufferedMessages();
}
}
void processBufferedMessages()
{
std::deque<PendingMessage> toProcess;
{
std::lock_guard<std::mutex> lock(bufferMutex_);
toProcess.swap(messageBuffer_);
}
if (!toProcess.empty())
{
std::cout << "[HSM Thread] Processing " << toProcess.size() << " buffered messages\n";
}
for (auto& pending : toProcess)
{
// Skip timed-out messages in buffer
if (pending.message.needsReply && pending.message.isTimedOut())
{
std::cout << "[HSM Thread] Skipping timed-out buffered message: " << pending.message.name << " (id=" << pending.message.id << ")\n";
std::lock_guard<std::mutex> lock(promiseMutex_);
pendingPromises_.erase(pending.message.id);
continue;
}
processMessage(std::move(pending));
}
}
/**
* @brief Process a message - determines if it's an event or command
*/
Message processMessageContent(const Message& msg)
{
// First, try to process as an event (state-changing)
auto event = paramsToEvent(msg.name, msg.params);
if (event)
{
return processEvent(msg, *event);
}
// Otherwise, process as a command
return processCommand(msg);
}
// --------------------------------------------------------------------
// Event Processing
// --------------------------------------------------------------------
Message processEvent(const Message& msg, const Event& event)
{
// Process the event
bool handled;
{
std::lock_guard<std::mutex> lock(stateMutex_);
handled = hsm_.processEvent(event);
}
JsonValue result = JsonValue::Object{};
result["handled"] = handled;
result["state"] = getCurrentStateName();
result["stateChanged"] = handled;
if (!handled)
{
return Message::createResponse(msg.id, false, result, "Event not handled in current state");
}
return Message::createResponse(msg.id, true, result);
}
// --------------------------------------------------------------------
// Command Processing
// --------------------------------------------------------------------
Message processCommand(const Message& msg)
{
// Check if command is valid in current state
std::string currentState = getCurrentStateName();
// Execute command based on name
if (msg.name == Commands::Home::name)
{
return executeHome(msg, currentState);
}
else if (msg.name == Commands::GetPosition::name)
{
return executeGetPosition(msg, currentState);
}
else if (msg.name == Commands::SetLaserPower::name)
{
return executeSetLaserPower(msg, currentState);
}
else if (msg.name == Commands::Compensate::name)
{
return executeCompensate(msg, currentState);
}
else if (msg.name == Commands::GetStatus::name)
{
return executeGetStatus(msg, currentState);
}
else if (msg.name == Commands::MoveRelative::name)
{
return executeMoveRelative(msg, currentState);
}
else
{
return Message::createResponse(msg.id, false, {}, "Unknown message: " + msg.name);
}
}
// --------------------------------------------------------------------
// Command Executors
// --------------------------------------------------------------------
Message executeHome(const Message& msg, const std::string& currentState)
{
// Home is only valid in Idle state
if (currentState.find("Idle") == std::string::npos)
{
return Message::createResponse(msg.id, false, {}, "Home command only valid in Idle state (current: " + currentState + ")");
}
double speed = 100.0;
if (msg.params.contains("speed"))
{
speed = msg.params.at("speed").asDouble();
}
std::cout << " [COMMAND] Home: Moving to home position at " << speed << "% speed\n";
// Simulate homing operation (sync)
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(1000 / (speed / 100.0))));
std::cout << " [COMMAND] Home: Homing complete\n";
JsonValue result = JsonValue::Object{};
result["position"] = JsonValue::Object{};
result["position"]["azimuth"] = 0.0;
result["position"]["elevation"] = 0.0;
result["state"] = getCurrentStateName();
return Message::createResponse(msg.id, true, result);
}
Message executeGetPosition(const Message& msg, const std::string& currentState)
{