MoteHost: Introduce remote::error exception with easy usable constructor
[remote/remote-mci.git] / diku_mch / DeviceManager.cc
blob1457a1e84cfc2fd37022048d72d5f084c39160ad
1 #include "DeviceManager.h"
3 namespace remote { namespace diku_mch {
5 struct delMote : public std::unary_function<std::pair<const std::string, Mote *>,void>
7 void operator()(std::pair<const std::string, Mote *> x) { delete x.second; }
8 };
10 struct invalidate : public std::unary_function<std::pair<const std::string, Mote *>,void>
12 void operator()(std::pair<const std::string, Mote *> x)
13 { if (x.second) x.second->invalidate(); }
16 void DeviceManager::refresh(std::string devicePath)
18 /* Invalidate all existing motes. */
19 std::for_each(motes.begin(), motes.end(), invalidate());
21 /* Clear new motes and delete and clear lost motes. */
22 newMotes.clear();
23 std::for_each(lostMotes.begin(), lostMotes.end(), delMote());
24 lostMotes.clear();
26 /* Read all mote devices */
27 readMoteDevices(devicePath);
29 /* Finally, clean up the motes that were lost since the last
30 * refresh based on whether they have been revalidated. */
31 motemap_t::iterator moteI = motes.begin();
32 while (moteI != motes.end()) {
33 if (moteI->second) {
34 if (!moteI->second->isValid()) {
35 moteI->second->closeTty();
36 lostMotes.insert(*moteI);
37 motes.erase(moteI);
39 } else {
40 motes.erase(moteI);
42 moteI++;
46 void DeviceManager::readMoteDevices(std::string devicePath)
48 struct dirent *dentry;
49 DIR *deviceDir;
51 deviceDir = opendir(devicePath.c_str());
52 if (!deviceDir) {
53 /* FIXME: Print error message if the error is not ENOENT. */
54 return;
57 while ((dentry = readdir(deviceDir))) {
58 std::string mac = dentry->d_name;
60 if (mac == "." || mac == "..")
61 continue;
63 updateMote(mac, devicePath + "/" + mac + "/");
66 closedir(deviceDir);
69 /** Update the mote device.
70 * Search for an existing mote based on the MAC given in the serial
71 * number. */
72 void DeviceManager::updateMote(std::string mac, std::string directory)
74 motemap_t::iterator m = motes.find(mac);
75 if (m != motes.end()) {
76 // we found a mote with the same MAC address
77 // just make sure the info is up-to-date
78 m->second->validate();
80 } else {
81 Mote *mote = new Mote(mac, directory);
83 if (mote->isValid()) {
84 // this must be a new mote, add it to the collection
85 motemap_t::value_type elm(mac, mote);
86 motes.insert(elm);
87 newMotes.insert(elm);
89 } else {
90 delete mote;