COSA
An Object-Oriented Platform for Arduino Programming
Actor.cpp
Go to the documentation of this file.
1 
21 #include "Actor.hh"
22 
23 using namespace Nucleo;
24 
25 int
26 Actor::send(uint8_t port, const void* buf, size_t size)
27 {
28  // Do not allow send to the running thread
29  if (UNLIKELY(s_running == this)) return (EINVAL);
30 
31  // Store message in sender actor
32  Actor* sender = (Actor*) s_running;
33  sender->m_port = port;
34  sender->m_size = size;
35  sender->m_buf = buf;
36 
37  // And queue in sending. Resume receiver or next thread
38  Thread* thread = (m_receiving ? this : (Thread*) sender->succ());
39  m_sending.attach(sender);
40  sender->resume(thread);
41  return (size);
42 }
43 
44 int
45 Actor::recv(Actor*& sender, uint8_t& port, void* buf, size_t size)
46 {
47  // Do not allow receive of other actor queue
48  if (UNLIKELY(s_running != this)) return (EINVAL);
49 
50  // Check if receiver needs to wait for sending actor
51  uint8_t key = lock();
52  if (m_sending.is_empty()) {
53  m_receiving = true;
54  Thread* thread = (Thread*) succ();
55  detach();
56  unlock(key);
57  resume(thread);
58  key = lock();
59  }
60 
61  // Copy sender message parameters
62  int res = -2;
63  sender = (Actor*) m_sending.succ();
64  port = sender->m_port;
65  if (size >= sender->m_size) {
66  memcpy(buf, sender->m_buf, sender->m_size);
67  res = sender->m_size;
68  }
69  m_receiving = false;
70 
71  // Reschedule the sender
72  succ()->attach(sender);
73  unlock(key);
74  return (res);
75 }
76 
Definition: Actor.hh:26
#define EINVAL
Definition: Errno.h:49
Head m_sending
Definition: Actor.hh:70
int recv(Actor *&sender, uint8_t &port, void *buf=NULL, size_t size=0)
Definition: Actor.cpp:45
size_t m_size
Definition: Actor.hh:72
uint8_t m_port
Definition: Actor.hh:71
uint8_t lock()
Definition: Types.h:319
void resume(Thread *thread)
Definition: Thread.cpp:90
Linkage * succ() const
Definition: Linkage.hh:51
const void * m_buf
Definition: Actor.hh:73
int send(uint8_t port, const void *buf=NULL, size_t size=0)
Definition: Actor.cpp:26
bool is_empty() const
Definition: Linkage.hh:155
void unlock(uint8_t key)
Definition: Types.h:331
static Thread * s_running
Definition: Thread.hh:124
#define UNLIKELY(x)
Definition: Types.h:153
volatile bool m_receiving
Definition: Actor.hh:69
void attach(Linkage *pred)
Definition: Linkage.hh:71