blob: 5136c87cbcdabf36b0252a416c3d4aafd120209d [file] [log] [blame]
Brian Silverman431500a2013-10-28 19:50:15 -07001#include "aos/common/network/team_number.h"
2
3#include <netinet/in.h>
Brian Silverman8f8b06f2013-10-30 22:04:27 -07004#include <inttypes.h>
Austin Schuhbe2456e2015-02-16 02:58:00 -08005#include <unistd.h>
6
7#include <string>
Brian Silverman431500a2013-10-28 19:50:15 -07008
9#include "aos/common/once.h"
Brian Silverman14fd0fb2014-01-14 21:42:01 -080010#include "aos/linux_code/configuration.h"
Brian Silverman8f8b06f2013-10-30 22:04:27 -070011#include "aos/common/logging/logging.h"
Austin Schuhbe2456e2015-02-16 02:58:00 -080012#include "aos/common/util/string_to_num.h"
Brian Silverman431500a2013-10-28 19:50:15 -070013
14namespace aos {
15namespace network {
16namespace {
17
Philipp Schraderf75a8bf2015-02-02 05:30:16 +000018uint16_t override_team;
Brian Silvermande0a53a2014-02-10 22:27:44 -080019
Austin Schuhbe2456e2015-02-16 02:58:00 -080020::std::string GetHostname() {
21 char buf[256];
22 buf[sizeof(buf) - 1] = '\0';
23 PCHECK(gethostname(buf, sizeof(buf) - 1));
24 return buf;
25}
26
27int ParseTeamNumber(const std::string &hostname, uint16_t *teamnumber) {
28 for (size_t i = 0; i < hostname.size(); i++) {
29 if (hostname[i] == '-') {
30 const std::string num_as_s = hostname.substr(i + 1);
31
32 int num;
33 if (!::aos::util::StringToNumber(num_as_s, &num)) {
34 return -1;
35 }
36 if (hostname.substr(0, i) == "roboRIO" &&
37 std::to_string(num) == num_as_s) {
38 *teamnumber = num;
39 return 0;
40 } else {
41 return -1;
42 }
43 }
44 }
45 return -1;
46}
47
Brian Silverman431500a2013-10-28 19:50:15 -070048uint16_t *DoGetTeamNumber() {
Brian Silvermande0a53a2014-02-10 22:27:44 -080049 if (override_team != 0) return &override_team;
Austin Schuhbe2456e2015-02-16 02:58:00 -080050 static uint16_t r;
51 int error = ParseTeamNumber(GetHostname(), &r);
52 if (error) {
53 LOG(FATAL, "Invalid hostname %s\n", GetHostname().c_str());
54 }
Brian Silverman8f8b06f2013-10-30 22:04:27 -070055 LOG(INFO, "team number is %" PRIu16 "\n", r);
Brian Silverman431500a2013-10-28 19:50:15 -070056 return &r;
57}
58
59} // namespace
60
61uint16_t GetTeamNumber() {
62 static Once<uint16_t> once(DoGetTeamNumber);
63 return *once.Get();
64}
65
Brian Silvermande0a53a2014-02-10 22:27:44 -080066void OverrideTeamNumber(uint16_t team) { override_team = team; }
67
Brian Silverman431500a2013-10-28 19:50:15 -070068} // namespace network
69} // namespace aos