blob: 925139a27d82414fc15e93f06fc3ace8a4bde845 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#ifndef AOS_ATOM_CODE_OUTPUT_MOTOR_OUTPUT_H_
2#define AOS_ATOM_CODE_OUTPUT_MOTOR_OUTPUT_H_
3
4#include <stdint.h>
5#include <string.h>
6#include <algorithm>
7#include <string>
8
9#include "aos/common/network/SendSocket.h"
10#include "aos/common/byteorder.h"
11#include "aos/common/type_traits.h"
12
13namespace aos {
14
15class MotorOutput {
16 public:
17 MotorOutput();
18 void Run();
19
20 // Constants for the first argument of AddMotor.
21 static const char VICTOR = 'v';
22 static const char TALON = 't';
23
24 protected:
25 // num is 1-indexed
26 int AddMotor(char type, uint8_t num, float value);
27 int AddSolenoid(uint8_t num, bool on);
28 int AddDSLine(uint8_t line, const char *data);
29 // loop_queuegroup is expected to be a control loop queue group.
30 // This function will fetch the latest goal and serve it.
31 template <class T>
32 int AddControlLoopGoal(T *loop_queuegroup);
33
34 virtual void RunIteration() = 0;
35
36 private:
37 SendSocket sock;
38};
39
40template <class T>
41int MotorOutput::AddControlLoopGoal(T *loop_queuegroup) {
42 typedef typename std::remove_reference<
43 decltype(*(loop_queuegroup->goal.MakeMessage().get()))>::type GoalType;
44 // TODO(aschuh): This assumes a static serialized message size.
45 const uint16_t size = GoalType::Size();
46 if (sock.hold_msg_len_ + 4 + 1 + size > sock.MAX_MSG) {
47 return -1;
48 }
49
50 const bool zero = !loop_queuegroup->goal.FetchLatest();
51
52 sock.hold_msg_[sock.hold_msg_len_ ++] = 'g';
53 const uint32_t hash = loop_queuegroup->hash();
54
55 // Place the loop hash at the front.
56 to_network(&hash, &sock.hold_msg_[sock.hold_msg_len_]);
57 sock.hold_msg_len_ += 4;
58
59 if (zero) {
60 GoalType zero_message;
61 zero_message.Zero();
62 zero_message.Serialize(&sock.hold_msg_[sock.hold_msg_len_]);
63 sock.hold_msg_len_ += size;
64 return -1;
65 } else {
66 loop_queuegroup->goal->Serialize(&sock.hold_msg_[sock.hold_msg_len_]);
67 sock.hold_msg_len_ += size;
68 return 0;
69 }
70}
71
72} // namespace aos
73
74#endif