#include "Config.h" #include "trim.h" #include #include #include using namespace std; Config::Entry::Entry(const string & name) { this->name = name; pin = -1; on_start = NONE; on_exit = NONE; on_lock = NONE; on_unlock = NONE; } Config::Config() { reset(); } void Config::reset() { port = "LPT1"; /* default to first parallel port */ entries.clear(); /* erase any entries previously configured */ } void Config::read(const char * file) { reset(); ifstream ifs(file); if (ifs.is_open()) { int entry_num = -1; /* start in "global" section (-1) */ string line; while (!ifs.eof()) { getline(ifs, line); line = trim(line); if (line == "") /* skip blank lines */ continue; if (line[0] == ';') /* skip comments */ continue; /* Look for the beginning of a new entry section */ if (line[0] == '[' && line[line.size()-1] == ']') { entries.push_back(Entry(string(line, 1, line.size() - 2))); entry_num++; continue; } /* split the line into variable and value parts */ pair parts = split(line); if (entry_num == -1) { if (parts.first == "port") { if (parts.second != "") { port = parts.second; } } else { cerr << "Warning: Unrecognized global command: " << line << endl; } } else { if (parts.first == "pin") { int pin = atoi(parts.second.c_str()); if (pin >= 0 && pin <= 7) entries[entry_num].pin = pin; else cerr << "Bad pin #: " << parts.second << endl; } else if (parts.first == "on_start") { entries[entry_num].on_start = parseAction(parts.second); } else if (parts.first == "on_exit") { entries[entry_num].on_exit = parseAction(parts.second); } else if (parts.first == "on_lock") { entries[entry_num].on_lock = parseAction(parts.second); } else if (parts.first == "on_unlock") { entries[entry_num].on_unlock = parseAction(parts.second); } else { cerr << "Warning: Unrecognized entry command: " << line << endl; } } } } else { cerr << "Warning: Could not open '" << file << "'" << endl; } } pair Config::split(const string & line) { pair res; size_t pos = line.find('='); if (pos != string::npos) { res.first = trim(string(line, 0, pos)); res.second = trim(string(line, pos + 1, line.size() - pos - 1)); } return res; } Config::Action Config::parseAction(const string & str) { string s = str; Action res = NONE; /* lowercase the string */ for (int sz = s.size(), i = 0; i < sz; i++) { s[i] = tolower(s[i]); } if (s == "on") res = ON; else if (s == "off") res = OFF; else if (s == "previous") res = PREVIOUS; return res; }