-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathconcore.hpp
More file actions
935 lines (843 loc) · 30.4 KB
/
concore.hpp
File metadata and controls
935 lines (843 loc) · 30.4 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
// concore.hpp -- this C++ include file will be the equivalent of concore.py
#ifndef CONCORE_HPP
#define CONCORE_HPP
#include <iostream>
#include <vector>
#include <iomanip> //for setprecision
#include <map>
//libraries for files
#include <fstream>
#include <sstream>
#include <string>
//libraries for platform independent delay. Supports C++11 upwards
#include <chrono>
#include <thread>
#ifdef __linux__
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#endif
#include <cstring>
#include <cctype>
#include <regex>
#include "concore_base.hpp"
using namespace std;
/**
* @class Concore
* @brief Class representing the Concore implementation in C++
*/
class Concore{
private:
//private variables
string s="",olds="";
string inpath = "./in";
string outpath = "./out";
static constexpr size_t SHM_SIZE = 4096;
int shmId_create = -1;
int shmId_get = -1;
char* sharedData_create = nullptr;
char* sharedData_get = nullptr;
// File sharing:- 0, Shared Memory:- 1
int communication_iport = 0; // iport refers to input port
int communication_oport = 0; // oport refers to input port
#ifdef CONCORE_USE_ZMQ
map<string, concore_base::ZeroMQPort*> zmq_ports;
#endif
public:
enum class ReadStatus {
SUCCESS,
TIMEOUT,
PARSE_ERROR,
FILE_NOT_FOUND,
RETRIES_EXCEEDED
};
struct ReadResult {
ReadStatus status;
vector<double> data;
};
double delay = 1;
int retrycount = 0;
double simtime;
int maxtime = 100;
map <string, int> iport;
map <string, int> oport;
map <string, string> params;
ReadStatus last_read_status = ReadStatus::SUCCESS;
/**
* @brief Constructor for Concore class.
* Initializes the iport and oport maps by parsing the respective files.
* It also creates or attaches to the shared memory segment if required.
*/
Concore(){
iport = mapParser("concore.iport");
oport = mapParser("concore.oport");
default_maxtime(100);
load_params();
int iport_number = -1;
int oport_number = -1;
if (!iport.empty()) {
std::map<std::string, int>::iterator it_iport = iport.begin();
iport_number = ExtractNumeric(it_iport->first);
}
if (!oport.empty()) {
std::map<std::string, int>::iterator it_oport = oport.begin();
oport_number = ExtractNumeric(it_oport->first);
}
// if iport_number and oport_number is equal to -1 then it refers to File Method,
// otherwise it refers to Shared Memory and the number represent the unique key.
#ifdef __linux__
if(oport_number != -1)
{
// oport_number is not equal to -1 so refers to SM and value is key.
communication_oport = 1;
this->createSharedMemory(oport_number);
}
if(iport_number != -1)
{
// iport_number is not equal to -1 so refers to SM and value is key.
communication_iport = 1;
this->getSharedMemory(iport_number);
}
#endif
}
/**
* @brief Destructor for Concore class.
* Detaches and removes the shared memory segment if shared memory created.
*/
~Concore()
{
#ifdef CONCORE_USE_ZMQ
for (auto& kv : zmq_ports)
delete kv.second;
zmq_ports.clear();
#endif
#ifdef __linux__
// Detach the shared memory segment from the process
if (communication_oport == 1 && sharedData_create != nullptr) {
shmdt(sharedData_create);
}
if (communication_iport == 1 && sharedData_get != nullptr) {
shmdt(sharedData_get);
}
// Remove the shared memory segment
if (shmId_create != -1) {
shmctl(shmId_create, IPC_RMID, nullptr);
}
#endif
}
/**
* @brief Concore is not copyable as it owns shared memory handles.
*/
Concore(const Concore&) = delete;
Concore& operator=(const Concore&) = delete;
/**
* @brief Move constructor. Transfers SHM handle ownership to the new instance.
*/
Concore(Concore&& other) noexcept
: s(std::move(other.s)), olds(std::move(other.olds)),
inpath(std::move(other.inpath)), outpath(std::move(other.outpath)),
shmId_create(other.shmId_create), shmId_get(other.shmId_get),
sharedData_create(other.sharedData_create), sharedData_get(other.sharedData_get),
communication_iport(other.communication_iport), communication_oport(other.communication_oport),
delay(other.delay), retrycount(other.retrycount), simtime(other.simtime),
maxtime(other.maxtime), iport(std::move(other.iport)), oport(std::move(other.oport)),
params(std::move(other.params))
{
other.shmId_create = -1;
other.shmId_get = -1;
other.sharedData_create = nullptr;
other.sharedData_get = nullptr;
other.communication_iport = 0;
other.communication_oport = 0;
}
/**
* @brief Move assignment. Cleans up current SHM resources, then takes ownership from other.
*/
Concore& operator=(Concore&& other) noexcept
{
if (this == &other)
return *this;
#ifdef __linux__
if (communication_oport == 1 && sharedData_create != nullptr)
shmdt(sharedData_create);
if (communication_iport == 1 && sharedData_get != nullptr)
shmdt(sharedData_get);
if (shmId_create != -1)
shmctl(shmId_create, IPC_RMID, nullptr);
#endif
s = std::move(other.s);
olds = std::move(other.olds);
inpath = std::move(other.inpath);
outpath = std::move(other.outpath);
shmId_create = other.shmId_create;
shmId_get = other.shmId_get;
sharedData_create = other.sharedData_create;
sharedData_get = other.sharedData_get;
communication_iport = other.communication_iport;
communication_oport = other.communication_oport;
delay = other.delay;
retrycount = other.retrycount;
simtime = other.simtime;
maxtime = other.maxtime;
iport = std::move(other.iport);
oport = std::move(other.oport);
params = std::move(other.params);
other.shmId_create = -1;
other.shmId_get = -1;
other.sharedData_create = nullptr;
other.sharedData_get = nullptr;
other.communication_iport = 0;
other.communication_oport = 0;
return *this;
}
/**
* @brief Extracts the numeric part from a string.
* @param str The input string.
* @return The numeric part of the string.
* Returns -1 if the string does not contain a numeric part.
*/
key_t ExtractNumeric(const std::string& str) {
std::string numberString;
// Find the number of leading digits in the input string
size_t numDigits = 0;
std::string start_digit = "";
while (numDigits < str.length() && std::isdigit(str[numDigits])) {
numberString += str[numDigits];
++numDigits;
}
if (numDigits == 0)
{
return -1;
}
if (numDigits == 1)
{
// this case is to avoid shared memory when there is just 0 or any negative value in front of edge.
if (std::stoi(numberString) <= 0)
{
return -1;
}
}
return std::stoi(numberString);
}
#ifdef __linux__
/**
* @brief Creates a shared memory segment with the given key.
* @param key The key for the shared memory segment.
*/
void createSharedMemory(key_t key)
{
shmId_create = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmId_create == -1) {
std::cerr << "Failed to create shared memory segment." << std::endl;
return;
}
// Verify the segment is large enough (shmget won't resize an existing segment)
struct shmid_ds shm_info;
if (shmctl(shmId_create, IPC_STAT, &shm_info) == 0 && shm_info.shm_segsz < SHM_SIZE) {
std::cerr << "Shared memory segment too small (" << shm_info.shm_segsz
<< " bytes, need " << SHM_SIZE << "). Removing and recreating." << std::endl;
shmctl(shmId_create, IPC_RMID, nullptr);
shmId_create = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmId_create == -1) {
std::cerr << "Failed to recreate shared memory segment." << std::endl;
return;
}
}
// Attach the shared memory segment to the process's address space
sharedData_create = static_cast<char*>(shmat(shmId_create, NULL, 0));
if (sharedData_create == reinterpret_cast<char*>(-1)) {
std::cerr << "Failed to attach shared memory segment." << std::endl;
sharedData_create = nullptr;
}
}
/**
* @brief Retrieves an existing shared memory segment with the given key.
* Waits until the shared memory segment is created by the writer process.
* @param key The key for the shared memory segment.
*/
void getSharedMemory(key_t key)
{
int retry = 0;
const int MAX_RETRY = 100;
while (retry < MAX_RETRY) {
// Get the shared memory segment created by Writer
shmId_get = shmget(key, SHM_SIZE, 0666);
// Check if shared memory exists
if (shmId_get != -1) {
break; // Break the loop if shared memory exists
}
std::cout << "Shared memory does not exist. Make sure the writer process is running." << std::endl;
sleep(1); // Sleep for 1 second before checking again
retry++;
}
if (shmId_get == -1) {
std::cerr << "Failed to get shared memory segment after max retries." << std::endl;
return;
}
// Attach the shared memory segment to the process's address space
sharedData_get = static_cast<char*>(shmat(shmId_get, NULL, 0));
if (sharedData_get == reinterpret_cast<char*>(-1)) {
std::cerr << "Failed to attach shared memory segment." << std::endl;
sharedData_get = nullptr;
}
}
#endif
/**
* @brief Parses a file containing port and number mappings and returns a map of the values.
* @param filename The name of the file to parse.
* @return A map of port names and their corresponding numbers.
*/
map<string,int> mapParser(string filename){
map<string,int> ans;
auto str_map = concore_base::safe_literal_eval_dict(filename, {});
for (const auto& kv : str_map) {
try {
ans[kv.first] = std::stoi(kv.second);
} catch (...) {
ans[kv.first] = 0;
}
}
return ans;
}
/**
* @brief function to compare and determine whether file content has been changed.
* @return true if the content has not changed, false otherwise.
*/
bool unchanged(){
if(olds.compare(s)==0){
s = "";
return true;
}
else{
olds = s;
return false;
}
}
/**
* @brief Parses a string and extracts a vector of double values.
* @param f The input string to parse.
* @return A vector of double values extracted from the input string.
*/
vector<double> parser(string f){
return concore_base::parselist_double(f);
}
/**
* @brief Parses a literal string into a ConcoreValue representation.
* @param f The input string to parse.
* @return A ConcoreValue obtained by parsing the input string.
*/
concore_base::ConcoreValue parse_literal(string f){
return concore_base::parse_literal(f);
}
/**
* @brief Flattens a ConcoreValue into a vector of numeric (double) values.
* @param v The ConcoreValue to flatten.
* @return A vector of double values obtained by flattening the input.
*/
vector<double> flatten_numeric(const concore_base::ConcoreValue& v){
return concore_base::flatten_numeric(v);
}
/**
* @brief deviate the read to either the SM (Shared Memory) or FM (File Method) communication protocol based on iport and oport.
* @param port The port number.
* @param name The name of the file.
* @param initstr The initial string
* @return
*/
vector<double> read(int port, string name, string initstr)
{
if(communication_iport == 1)
{
return read_SM(port, name, initstr);
}
return read_FM(port, name, initstr);
}
ReadResult read_result(int port, string name, string initstr)
{
ReadResult result;
result.data = read(port, name, initstr);
result.status = last_read_status;
return result;
}
/**
* @brief Reads data from a specified port and name using the FM (File Method) communication protocol.
* @param port The port number.
* @param name The name of the file.
* @param initstr The initial string.
* @return a string of file content
*/
vector<double> read_FM(int port, string name, string initstr){
chrono::milliseconds timespan((int)(1000*delay));
this_thread::sleep_for(timespan);
string ins;
ReadStatus status = ReadStatus::SUCCESS;
try {
ifstream infile;
infile.open(inpath+to_string(port)+"/"+name, ios::in);
if(infile) {
ostringstream ss;
ss << infile.rdbuf(); // reading data
ins = ss.str(); //saving data as string
infile.close();
}
else {
status = ReadStatus::FILE_NOT_FOUND;
throw 505;}
}
catch (...) {
ins = initstr;
if (status == ReadStatus::SUCCESS)
status = ReadStatus::FILE_NOT_FOUND;
}
int retry = 0;
const int MAX_RETRY = 100;
while ((int)ins.length()==0 && retry < MAX_RETRY){
this_thread::sleep_for(timespan);
try{
ifstream infile;
infile.open(inpath+to_string(port)+"/"+name, ios::in);
if(infile) {
ostringstream ss;
ss << infile.rdbuf(); // reading data
ins = ss.str();
retrycount++;
infile.close();
}
else{
retrycount++;
throw 505;
}
}
//observed retry count in C++ from various tests is approx 80.
catch(...){
cout<<"Read error";
}
retry++;
}
if ((int)ins.length()==0)
status = ReadStatus::RETRIES_EXCEEDED;
s += ins;
vector<double> inval = parser(ins);
if(inval.empty()) {
if (status == ReadStatus::SUCCESS)
status = ReadStatus::PARSE_ERROR;
inval = parser(initstr);
}
if(inval.empty()) {
if (status == ReadStatus::SUCCESS)
status = ReadStatus::PARSE_ERROR;
last_read_status = status;
return inval;
}
simtime = simtime > inval[0] ? simtime : inval[0];
last_read_status = status;
//returning a string with data excluding simtime
inval.erase(inval.begin());
return inval;
}
/**
* @brief Reads data from the shared memory segment based on the specified port and name.
* @param port The port number.
* @param name The name of the file.
* @param initstr The initial string to use if the shared memory is not found.
* @return string of file content
*/
vector<double> read_SM(int port, string name, string initstr){
chrono::milliseconds timespan((int)(1000*delay));
this_thread::sleep_for(timespan);
string ins = "";
ReadStatus status = ReadStatus::SUCCESS;
try {
if (shmId_get != -1) {
if (sharedData_get && sharedData_get[0] != '\0') {
std::string message(sharedData_get, strnlen(sharedData_get, SHM_SIZE));
ins = message;
}
else
{
throw 505;
}
}
else
{
status = ReadStatus::FILE_NOT_FOUND;
throw 505;
}
} catch (...) {
ins = initstr;
if (status == ReadStatus::SUCCESS)
status = ReadStatus::FILE_NOT_FOUND;
}
int retry = 0;
const int MAX_RETRY = 100;
while ((int)ins.length()==0 && retry < MAX_RETRY){
this_thread::sleep_for(timespan);
try{
if(shmId_get != -1) {
std::string message(sharedData_get, strnlen(sharedData_get, SHM_SIZE));
ins = message;
retrycount++;
}
else{
retrycount++;
throw 505;
}
}
//observed retry count in C++ from various tests is approx 80.
catch(...){
std::cout << "Read error" << std::endl;
}
retry++;
}
if ((int)ins.length()==0)
status = ReadStatus::RETRIES_EXCEEDED;
s += ins;
vector<double> inval = parser(ins);
if(inval.empty()) {
if (status == ReadStatus::SUCCESS)
status = ReadStatus::PARSE_ERROR;
inval = parser(initstr);
}
if(inval.empty()) {
if (status == ReadStatus::SUCCESS)
status = ReadStatus::PARSE_ERROR;
last_read_status = status;
return inval;
}
simtime = simtime > inval[0] ? simtime : inval[0];
last_read_status = status;
//returning a string with data excluding simtime
inval.erase(inval.begin());
return inval;
}
/**
* @brief deviate the write to either the SM (Shared Memory) or FM (File Method) communication protocol based on iport and oport.
* @param port The port number.
* @param name The name of the file.
* @param val The vector of double values to write.
* @param delta The delta value (default: 0).
*/
void write(int port, string name, vector<double> val, int delta=0)
{
if(communication_oport == 1)
{
return write_SM(port, name, val, delta);
}
return write_FM(port, name, val, delta);
}
/**
* @brief deviate the write to either the SM (Shared Memory) or FM (File Method) communication protocol based on iport and oport.
* @param port The port number.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write(int port, string name, string val, int delta=0)
{
if(communication_oport == 1)
{
return write_SM(port, name, val, delta);
}
return write_FM(port, name, val, delta);
}
/**
* @brief write method, accepts a vector double and writes it to the file
* @param port The port number.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write_FM(int port, string name, vector<double> val, int delta=0){
try {
ofstream outfile;
outfile.open(outpath+to_string(port)+"/"+name, ios::out);
if(outfile){
val.insert(val.begin(),simtime+delta);
outfile<<'[';
for(int i=0;i<val.size()-1;i++)
outfile<<val[i]<<',';
outfile<<val[val.size()-1]<<']';
outfile.close();
// simtime must not be mutated here (issue #385).
}
else{
throw 505;
}
}
catch(...){
cout<<"skipping +"<<outpath<<port<<" /"<<name;
}
}
/**
* @brief write method, accepts a string and writes it to the file
* @param port The port number.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write_FM(int port, string name, string val, int delta=0){
chrono::milliseconds timespan((int)(2000*delay));
this_thread::sleep_for(timespan);
try {
string temp;
ofstream outfile;
outfile.open(outpath+to_string(port)+"/"+name, ios::out);
if(outfile){
outfile<<val;
outfile.close();
}
else throw 505;
}
catch(...){
cout<<"skipping +"<<outpath<<port<<" /"<<name;
}
}
/**
* @brief Writes a vector of double values to the shared memory segment based on the specified port and name.
* @param port The port number.
* @param name The name of the file.
* @param val The vector of double values to write.
* @param delta The delta value (default: 0).
*/
void write_SM(int port, string name, vector<double> val, int delta=0){
try {
std::ostringstream outfile;
if(shmId_create != -1){
if (sharedData_create == nullptr)
throw 506;
val.insert(val.begin(),simtime+delta);
outfile<<'[';
for(int i=0;i<val.size()-1;i++)
outfile<<val[i]<<',';
outfile<<val[val.size()-1]<<']';
std::string result = outfile.str();
if (result.size() >= SHM_SIZE) {
std::cerr << "ERROR: write_SM payload (" << result.size()
<< " bytes) exceeds " << SHM_SIZE - 1
<< "-byte shared memory limit. Data truncated!" << std::endl;
}
std::strncpy(sharedData_create, result.c_str(), SHM_SIZE - 1);
sharedData_create[SHM_SIZE - 1] = '\0';
// simtime must not be mutated here (issue #385).
}
else{
throw 505;
}
}
catch(...){
cout<<"skipping +"<<outpath<<port<<" /"<<name;
}
}
/**
* @brief Writes a string to the shared memory segment based on the specified port and name.
* @param port The port number.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write_SM(int port, string name, string val, int delta=0){
chrono::milliseconds timespan((int)(2000*delay));
this_thread::sleep_for(timespan);
try {
if(shmId_create != -1){
if (sharedData_create == nullptr)
throw 506;
if (val.size() >= SHM_SIZE) {
std::cerr << "ERROR: write_SM payload (" << val.size()
<< " bytes) exceeds " << SHM_SIZE - 1
<< "-byte shared memory limit. Data truncated!" << std::endl;
}
std::strncpy(sharedData_create, val.c_str(), SHM_SIZE - 1);
sharedData_create[SHM_SIZE - 1] = '\0';
}
else throw 505;
}
catch(...){
cout<<"skipping +"<<outpath<<port<<" /"<<name;
}
}
#ifdef CONCORE_USE_ZMQ
/**
* @brief Registers a ZMQ port for use with read()/write().
* @param port_name The ZMQ port name.
* @param port_type "bind" or "connect".
* @param address The ZMQ address.
* @param socket_type_str The socket type string.
*/
void init_zmq_port(string port_name, string port_type, string address, string socket_type_str) {
if (zmq_ports.count(port_name)) return;
int sock_type = concore_base::zmq_socket_type_from_string(socket_type_str);
if (sock_type == -1) {
cerr << "init_zmq_port: unknown socket type '" << socket_type_str << "'" << endl;
return;
}
zmq_ports[port_name] = new concore_base::ZeroMQPort(port_type, address, sock_type);
}
/**
* @brief Reads data from a ZMQ port. Strips simtime prefix, updates simtime.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param initstr The initial string.
* @return a vector of double values
*/
vector<double> read_ZMQ(string port_name, string name, string initstr) {
ReadStatus status = ReadStatus::SUCCESS;
auto it = zmq_ports.find(port_name);
if (it == zmq_ports.end()) {
cerr << "read_ZMQ: port '" << port_name << "' not initialized" << endl;
status = ReadStatus::FILE_NOT_FOUND;
last_read_status = status;
return parser(initstr);
}
vector<double> inval = it->second->recv_with_retry();
if (inval.empty()) {
status = ReadStatus::TIMEOUT;
inval = parser(initstr);
}
if (inval.empty()) {
if (status == ReadStatus::SUCCESS)
status = ReadStatus::PARSE_ERROR;
last_read_status = status;
return inval;
}
last_read_status = status;
simtime = simtime > inval[0] ? simtime : inval[0];
s += port_name;
inval.erase(inval.begin());
return inval;
}
/**
* @brief Writes a vector of double values to a ZMQ port. Prepends simtime+delta.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param val The vector of double values to write.
* @param delta The delta value (default: 0).
*/
void write_ZMQ(string port_name, string name, vector<double> val, int delta=0) {
auto it = zmq_ports.find(port_name);
if (it == zmq_ports.end()) {
cerr << "write_ZMQ: port '" << port_name << "' not initialized" << endl;
return;
}
val.insert(val.begin(), simtime + delta);
it->second->send_with_retry(val);
// simtime must not be mutated here (issue #385).
}
/**
* @brief Writes a string to a ZMQ port.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write_ZMQ(string port_name, string name, string val, int delta=0) {
auto it = zmq_ports.find(port_name);
if (it == zmq_ports.end()) {
cerr << "write_ZMQ: port '" << port_name << "' not initialized" << endl;
return;
}
chrono::milliseconds timespan((int)(2000*delay));
this_thread::sleep_for(timespan);
it->second->send_string_with_retry(val);
}
/**
* @brief deviate the read to ZMQ communication protocol when port identifier is a string key.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param initstr The initial string.
* @return
*/
vector<double> read(string port_name, string name, string initstr) {
return read_ZMQ(port_name, name, initstr);
}
ReadResult read_result(string port_name, string name, string initstr) {
ReadResult result;
result.data = read(port_name, name, initstr);
result.status = last_read_status;
return result;
}
/**
* @brief deviate the write to ZMQ communication protocol when port identifier is a string key.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param val The vector of double values to write.
* @param delta The delta value (default: 0).
*/
void write(string port_name, string name, vector<double> val, int delta=0) {
return write_ZMQ(port_name, name, val, delta);
}
/**
* @brief deviate the write to ZMQ communication protocol when port identifier is a string key.
* @param port_name The ZMQ port name.
* @param name The name of the file.
* @param val The string to write.
* @param delta The delta value (default: 0).
*/
void write(string port_name, string name, string val, int delta=0) {
return write_ZMQ(port_name, name, val, delta);
}
#endif // CONCORE_USE_ZMQ
/**
* @brief Strips leading and trailing whitespace from a string.
* @param str The input string.
* @return The stripped string.
*/
string stripstr(string str){
return concore_base::stripstr(str);
}
/**
* @brief Strips surrounding single or double quotes from a string.
* @param str The input string.
* @return The unquoted string.
*/
string stripquotes(string str){
return concore_base::stripquotes(str);
}
/**
* @brief Parses a dict-formatted string into a string-to-string map.
* @param str The input string in {key: val, ...} format.
* @return A map of key-value string pairs.
*/
map<string, string> parsedict(string str){
return concore_base::parsedict(str);
}
/**
* @brief Sets maxtime from the concore.maxtime file, falling back to defaultValue.
* @param defaultValue The fallback value if the file is missing.
*/
void default_maxtime(int defaultValue){
maxtime = (int)concore_base::load_maxtime(
inpath + "/1/concore.maxtime", (double)defaultValue);
}
/**
* @brief Loads simulation parameters from concore.params into the params map.
*/
void load_params(){
params = concore_base::load_params(inpath + "/1/concore.params");
}
/**
* @brief Returns the value of a param by name, or a default if not found.
* @param n The parameter name.
* @param i The default value.
* @return The parameter value or the default.
*/
string tryparam(string n, string i){
return concore_base::tryparam(params, n, i);
}
/**
* @brief Initializes the system with the given input values.
* @param f The input string containing the values.
* @return A vector of double values representing the initialized system state.
*/
vector<double> initval(string f){
//parsing
vector<double> val = parser(f);
if (val.empty()) return val;
//determining simtime
simtime = val[0];
//returning the rest of the values(except simtime) in val
val.erase(val.begin());
return val;
}
};
#endif // CONCORE_HPP