aboutsummaryrefslogtreecommitdiff
path: root/src/ServerUtils.cpp
blob: 2cfa0e4b2a6c208fb2c872f58ef3ce507454c85c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright 2017 Paul Nettle. 
// 
// This file is part of Gobbledegook. 
// 
// Gobbledegook is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
// 
// Gobbledegook is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
// 
// You should have received a copy of the GNU General Public License 
// along with Gobbledegook.  If not, see <http://www.gnu.org/licenses/>. 
 
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// 
// >> 
// >>>  INSIDE THIS FILE 
// >> 
// 
// This file contains helper functions for our server's implementation. That is, methods that are used by the server itself (when 
// responding to D-Bus or BlueZ requests.) 
// 
// >> 
// >>>  DISCUSSION 
// >> 
// 
// Generally speaking, these are blocks of code that are too big to comfortably fit as lambdas within the `Server::Server()` 
// constructor are here. 
// 
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
 
#include <glib.h>
#include <string>
#include <fstream>
#include <regex>
 
#include "ServerUtils.h"
#include "DBusObject.h"
#include "DBusInterface.h"
#include "GattProperty.h"
#include "GattService.h"
#include "GattCharacteristic.h"
#include "GattDescriptor.h"
#include "Server.h"
#include "Logger.h"
#include "Utils.h"
 
namespace ggk {
 
// Adds an object to the tree of managed objects as returned from the `GetManagedObjects` method call from the D-Bus interface 
// `org.freedesktop.DBus.ObjectManager`. 
// 
// According to the spec: 
// 
//     The return value of this method is a dict whose keys are object paths. 
//     All returned object paths are children of the object path implementing this interface, 
//     i.e. their object paths start with the ObjectManager's object path plus '/'. 
// 
//     Each value is a dict whose keys are interfaces names. Each value in this inner dict 
//     is the same dict that would be returned by the org.freedesktop.DBus.Properties.GetAll() 
//     method for that combination of object path and interface. If an interface has no properties, 
//     the empty dict is returned. 
// 
//     (a{oa{sa{sv}}}) 
static void addManagedObjectsNode(const DBusObject &object, const DBusObjectPath &basePath, GVariantBuilder *pObjectArray)
{
if (!object.isPublished())
{
return;
}
 
if (!object.getInterfaces().empty())
{
DBusObjectPath path = basePath + object.getPathNode();
Logger::debug(SSTR << "  Object: " << path);
 
GVariantBuilder *pInterfaceArray = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
for (std::shared_ptr<const DBusInterface> pInterface : object.getInterfaces())
{
Logger::debug(SSTR << "  + Interface (type: " << pInterface->getInterfaceType() << ")");
 
if (std::shared_ptr<const GattService> pService = TRY_GET_CONST_INTERFACE_OF_TYPE(pInterface, GattService))
{
if (!pService->getProperties().empty())
{
Logger::debug(SSTR << "    GATT Service interface: " << pService->getName());
 
GVariantBuilder *pPropertyArray = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
for (const GattProperty &property : pService->getProperties())
{
Logger::debug(SSTR << "      Property " << property.getName());
g_variant_builder_add
(
pPropertyArray,
"{sv}",
property.getName().c_str(),
property.getValue()
);
}
 
g_variant_builder_add
(
pInterfaceArray,
"{sa{sv}}",
pService->getName().c_str(),
pPropertyArray
);
}
}
else if (std::shared_ptr<const GattCharacteristic> pCharacteristic = TRY_GET_CONST_INTERFACE_OF_TYPE(pInterface, GattCharacteristic))
{
if (!pCharacteristic->getProperties().empty())
{
Logger::debug(SSTR << "    GATT Characteristic interface: " << pCharacteristic->getName());
 
GVariantBuilder *pPropertyArray = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
for (const GattProperty &property : pCharacteristic->getProperties())
{
Logger::debug(SSTR << "      Property " << property.getName());
g_variant_builder_add
(
pPropertyArray,
"{sv}",
property.getName().c_str(),
property.getValue()
);
}
 
g_variant_builder_add
(
pInterfaceArray,
"{sa{sv}}",
pCharacteristic->getName().c_str(),
pPropertyArray
);
}
}
else if (std::shared_ptr<const GattDescriptor> pDescriptor = TRY_GET_CONST_INTERFACE_OF_TYPE(pInterface, GattDescriptor))
{
if (!pDescriptor->getProperties().empty())
{
Logger::debug(SSTR << "    GATT Descriptor interface: " << pDescriptor->getName());
 
GVariantBuilder *pPropertyArray = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
for (const GattProperty &property : pDescriptor->getProperties())
{
Logger::debug(SSTR << "      Property " << property.getName());
g_variant_builder_add
(
pPropertyArray,
"{sv}",
property.getName().c_str(),
property.getValue()
);
}
 
g_variant_builder_add
(
pInterfaceArray,
"{sa{sv}}",
pDescriptor->getName().c_str(),
pPropertyArray
);
}
}
else
{
Logger::error(SSTR << "    Unknown interface type");
return;
}
}
 
g_variant_builder_add
(
pObjectArray,
"{oa{sa{sv}}}",
path.c_str(),
pInterfaceArray
);
}
 
for (const DBusObject &child : object.getChildren())
{
addManagedObjectsNode(child, basePath + object.getPathNode(), pObjectArray);
}
}
 
// Builds the response to the method call `GetManagedObjects` from the D-Bus interface `org.freedesktop.DBus.ObjectManager` 
void ServerUtils::getManagedObjects(GDBusMethodInvocation *pInvocation)
{
Logger::debug(SSTR << "Reporting managed objects");
 
GVariantBuilder *pObjectArray = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
for (const DBusObject &object : TheServer->getObjects())
{
addManagedObjectsNode(object, DBusObjectPath(""), pObjectArray);
}
 
GVariant *pParams = g_variant_new("(a{oa{sa{sv}}})", pObjectArray);
g_dbus_method_invocation_return_value(pInvocation, pParams);
}
 
// WARNING: Hacky code - don't count on this working properly on all systems 
// 
// This routine will attempt to parse /proc/cpuinfo to return the CPU count/model. Results are cached on the first call, with 
// cached results returned on successive calls. 
// 
// If this routine fails, it will respond with something reasonable, if not _entirely_ accurate. 
std::string ServerUtils::getCpuInfo(int16_t &cpuCount)
{
static int16_t cachedCount = -1;
static std::string cachedModel;
static const std::string kCpuInfoFile = "/proc/cpuinfo";
 
// If we haven't cached a result, let's go get one 
if (cachedCount == -1)
{
// Reset our counter 
cachedCount = 0;
 
// Open the cpuinfo file 
std::ifstream cpuInfo(kCpuInfoFile);
if (cpuInfo.is_open())
{
std::string line;
while(getline(cpuInfo, line))
{
// Count the processors 
std::regex processorRegex("^processor.*: [0-9].*$", std::regex::ECMAScript);
std::smatch processorMatch;
 
if (std::regex_search(line, processorMatch, processorRegex))
{
cachedCount++;
}
 
// Extract the first model name we find 
if (cachedModel.empty())
{
std::regex modelRegex("^model name.*: (.*)$", std::regex::ECMAScript);
std::smatch modelMatch;
if (std::regex_search(line, modelMatch, modelRegex))
{
if (modelMatch.size() == 2)
{
cachedModel = Utils::trim(modelMatch[1].str());
}
}
}
}
 
cpuInfo.close();
}
 
// If we never found one, provide a reasonable default 
if (cachedModel.empty()) { cachedModel = "Gooberfest Cyclemaster 3000 (v8)"}
if (cachedCount == 0{ cachedCount = 42}
}
 
cpuCount = cachedCount;
return cachedModel;
}
 
// Build a variant that meets the standard for the Current Time (0x2A2B) Bluetooth Characteristic standard 
// 
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.current_time.xml 
GVariant *ServerUtils::gvariantCurrentTime()
{
time_t timeValue = time(nullptr);
struct tm *pTimeStruct = localtime(&timeValue);
guint16 year = pTimeStruct->tm_year + 1900;
guint8 wday = guint8(pTimeStruct->tm_wday == 0 ? 7 : pTimeStruct->tm_wday);
 
g_auto(GVariantBuilder) builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
 
g_variant_builder_add(&builder, "y", (year >> 0) & 0xff);
g_variant_builder_add(&builder, "y", (year >> 8) & 0xff);
g_variant_builder_add(&builder, "y", guint8(pTimeStruct->tm_mon+1));  // month (1-12) 
g_variant_builder_add(&builder, "y", guint8(pTimeStruct->tm_mday));   // day (1-31) 
g_variant_builder_add(&builder, "y", guint8(pTimeStruct->tm_hour));   // hour (0-23) 
g_variant_builder_add(&builder, "y", guint8(pTimeStruct->tm_min));    // minute (0-59) 
g_variant_builder_add(&builder, "y", guint8(pTimeStruct->tm_sec));    // seconds (0-59) 
g_variant_builder_add(&builder, "y", wday);                           // weekday (1-7 where 1=Monday) 
g_variant_builder_add(&builder, "y", guint8(0));                      // Fractions (1/256th of second) 
g_variant_builder_add(&builder, "y", guint8(0));                      // Adjust reason bitmask (0 for testing) 
 
GVariant * const pVariant = g_variant_builder_end(&builder);
return pVariant;
}
 
// Build a variant that meets the standard for the Local Time Information (0x2A0F) Bluetooth Characteristic standard 
// 
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.local_time_information.xml 
GVariant *ServerUtils::gvariantLocalTime()
{
tzset();
time_t timeValue = time(nullptr);
struct tm *pTimeStruct = localtime(&timeValue);
 
gint8 utcOffset = -gint8(timezone / 60 / 15); // UTC time (uses 15-minute increments, 0 = UTC time) 
guint8 dstOffset = pTimeStruct->tm_isdst == 0 ? 0 : 4;  // 0 = no DST offset, 4 = +1 hour for DST 
 
g_auto(GVariantBuilder) builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
 
g_variant_builder_add(&builder, "y", utcOffset);
g_variant_builder_add(&builder, "y", dstOffset);
 
GVariant * const pVariant = g_variant_builder_end(&builder);
return pVariant;
}
 
}// namespace ggk