OctopOS  0.6.0
Data communication bus for SPACE HAUC
publisher.h
Go to the documentation of this file.
1 // Copyright 2017 Space HAUC Command and Data Handling
2 // This file is part of octopOS which is released under AGPLv3.
3 // See file LICENSE.txt or go to <http://www.gnu.org/licenses/> for full
4 // license details.
5 
9 #ifndef INCLUDE_PUBLISHER_H_
10 #define INCLUDE_PUBLISHER_H_
11 
12 #include <string>
13 #include <sstream>
14 #include <vector>
15 #include <algorithm>
16 #include <iterator>
17 #include <utility>
18 
19 #include "tentacle.h" // NOLINT
20 
26 template <typename T>
27 class publisher : public tentacle {
28  public:
34  publisher(std::string _name, key_t message_key):
35  tentacle(message_key), name(_name) {
36  id = getTempId(tentacle::role_t::PUBLISHER);
37 
38  write(CREATE_PUB, std::to_string(id) + " " +
39  std::to_string(sizeof(T)) + " " + name);
40 
41  std::pair<long, std::string> response; // NOLINT
42 
43  response = read(id);
44 
45  std::istringstream iss(response.second);
46  std::vector<std::string> tokens{std::istream_iterator<std::string>{iss},
47  std::istream_iterator<std::string>{}};
48  if ((semid = semget(std::stoi(tokens[1]), 2, 0600)) < 0) {
49  throw std::system_error(
50  errno,
51  std::generic_category(),
52  "Unable to get r/w sem");
53  }
54 
55  rw = reinterpret_cast<shm_object*>(shared_data + std::stoi(tokens[0]));
56 
57  data_ptr = reinterpret_cast<T*>(rw + 1);
58  id = std::stoi(tokens[2]);
59  }
60 
67  bool publish(T data) {
68  bool return_value = false;
69  if (p(semid, 1) >= 0) {
70  rw->rw_array[1] += 1;
71  if (rw->rw_array[1] == 1) {
72  p(semid, 3); // TODO(JoshuaHassler) check for success
73  }
74 
75  v(semid, 1);
76  }
77 
78  if (p(semid, 2) >= 0) {
79  *data_ptr = data;
80  return_value = true;
81  write(PUBLISH_CODE, name);
82  v(semid, 2);
83  }
84 
85  if (p(semid, 1) >= 0) {
86  rw->rw_array[1] -= 1;
87  if (rw->rw_array[1] == 0)
88  v(semid, 3); // TODO(JoshuaHassler) check for success
89  v(semid, 1);
90  }
91  return return_value;
92  }
93 
94  private:
96  long id; // NOLINT
98  std::string name;
100  int semid;
103  shm_object* rw;
105  T* data_ptr;
106 };
107 
108 #endif // INCLUDE_PUBLISHER_H_
Definition: utility.h:52
static long getTempId(role_t role)
Definition: tentacle.cpp:72
Definition: publisher.h:27
Definition: tentacle.h:31
const unsigned CREATE_PUB
Definition: utility.h:38
publisher(std::string _name, key_t message_key)
Definition: publisher.h:34
bool write(long type, std::string data)
Definition: tentacle.cpp:50
int v(int sem, int counter)
Definition: utility.cpp:54
static std::pair< long, std::string > read(long type, bool block=true, bool under=false)
Definition: tentacle.cpp:28
bool publish(T data)
Definition: publisher.h:67
int p(int sem, int counter)
Definition: utility.cpp:39
unsigned rw_array[2]
Definition: utility.h:54
static intptr_t * shared_data
Definition: tentacle.h:47
const unsigned PUBLISH_CODE
Definition: utility.h:40