/
1WireForWindows.cpp
467 lines (389 loc) · 11.2 KB
/
1WireForWindows.cpp
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include "stdafx.h"
#ifdef WIN32
#include "1WireForWindows.h"
#include "../../main/Logger.h"
#include <boost/optional.hpp>
#include "../../json/json.h"
#include <WS2tcpip.h>
#define _1WIRE_SERVICE_PORT "1664"
void Log(const _eLogLevel level, const char* logline, ...)
{
#ifdef _DEBUG
va_list argList;
char cbuffer[1024];
va_start(argList, logline);
vsnprintf(cbuffer, 1024, logline, argList);
va_end(argList);
_log.Log(level,cbuffer);
#else // _DEBUG
#endif // _DEBUG
}
SOCKET ConnectToService()
{
// Connection
SOCKET theSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory(&hints,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
int getaddrinfoRet = getaddrinfo("localhost",_1WIRE_SERVICE_PORT,&hints,&result);
if (getaddrinfoRet != 0)
{
Log(LOG_ERROR,"getaddrinfo failed with error: %d\n", getaddrinfoRet);
return INVALID_SOCKET;
}
// Attempt to connect to an address until one succeeds
for(ptr=result;ptr!=NULL;ptr=ptr->ai_next)
{
// Create a SOCKET for connecting to server
theSocket = socket(ptr->ai_family,ptr->ai_socktype,ptr->ai_protocol);
if (theSocket == INVALID_SOCKET)
{
Log(LOG_ERROR,"socket function failed with error = %d\n", WSAGetLastError());
return INVALID_SOCKET;
}
// Connect to server
if (connect(theSocket, ptr->ai_addr, static_cast<int>(ptr->ai_addrlen)) == SOCKET_ERROR)
{
Log(LOG_ERROR,"1Wire: connect function failed with error: %ld\n", WSAGetLastError());
closesocket(theSocket);
theSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (theSocket==INVALID_SOCKET)
{
return INVALID_SOCKET;
}
// Set receive timeout
struct timeval tv;
tv.tv_sec = 10*1000; /* 10 Secs Timeout */
if (setsockopt(theSocket,SOL_SOCKET,SO_RCVTIMEO,(char*)&tv,sizeof(struct timeval))==SOCKET_ERROR)
{
Log(LOG_ERROR,"setsockopt failed with error: %u\n", WSAGetLastError());
closesocket(theSocket);
return INVALID_SOCKET;
}
return theSocket;
}
void DisconnectFromService(SOCKET theSocket)
{
closesocket(theSocket);
}
bool Send(SOCKET theSocket, const std::string &requestToSend)
{
// Send message size
size_t requestSize = requestToSend.length();
if (send(theSocket,(char*)&requestSize,sizeof(requestSize),0) == SOCKET_ERROR)
return false;
// Send message
if (send(theSocket,requestToSend.c_str(),requestToSend.length(),0) == SOCKET_ERROR)
return false;
return true;
}
std::string Receive(SOCKET theSocket)
{
// Wait for answer (with timeout, see ConnectToService)
// First receive answer size
size_t answerSize;
if (recv(theSocket,(char*)&answerSize,sizeof(answerSize),0)==SOCKET_ERROR)
return "";
// Now the answer content
char* answerBuffer = new char[answerSize];
if (recv(theSocket,answerBuffer,answerSize,0)==SOCKET_ERROR)
return "";
std::string answer(answerBuffer, answerSize);
delete[] answerBuffer;
return answer;
}
std::string SendAndReceive(SOCKET theSocket,const std::string &requestToSend)
{
if (!Send(theSocket,requestToSend))
return "";
return Receive(theSocket);
}
std::string C1WireForWindows::SendAndReceive(const std::string &requestToSend) const
{
// SendAndReceive can be called by 2 different thread contexts : writeData and GetDevices
// So we have to set protection
std::lock_guard<std::mutex> locker(*(const_cast<std::mutex*>(&m_SocketMutex)));
return ::SendAndReceive(m_Socket,requestToSend);
}
//Giz: To Author, please rewrite to use this without boost!
bool C1WireForWindows::IsAvailable()
{
#ifdef _DEBUG
return false;
#else
static boost::optional<bool> IsAvailable;
if (IsAvailable.is_initialized())
return IsAvailable.get();
// Make a connection only to know if 1-wire is available
SOCKET theSocket = ConnectToService();
if (theSocket == INVALID_SOCKET)
{
IsAvailable=false;
return false;
}
// Request
Json::Value reqRoot;
reqRoot["IsAvailable"]="";
Json::FastWriter writer;
// Send request and wait for answer
std::string answer = ::SendAndReceive(theSocket,writer.write(reqRoot));
// Answer processing
if (answer.empty())
{
IsAvailable=false;
DisconnectFromService(theSocket);
return false;
}
Json::Value ansRoot;
Json::Reader reader;
if (!reader.parse(answer,ansRoot))
{
IsAvailable=false;
DisconnectFromService(theSocket);
return false;
}
DisconnectFromService(theSocket);
IsAvailable=ansRoot.get("Available",false).asBool();
return IsAvailable.get();
#endif
}
C1WireForWindows::C1WireForWindows()
{
// Connect to service
m_Socket = ConnectToService();
_log.Log(LOG_STATUS,"Using 1-Wire support (Windows)...");
}
C1WireForWindows::~C1WireForWindows()
{
// Disconnect from service
if (m_Socket==INVALID_SOCKET)
return;
DisconnectFromService(m_Socket);
}
void C1WireForWindows::GetDevices(/*out*/std::vector<_t1WireDevice>& devices) const
{
if (m_Socket==INVALID_SOCKET)
return;
// Request
Json::Value reqRoot;
reqRoot["GetDevices"]="";
Json::FastWriter writer;
// Send request and wait for answer
std::string answer = SendAndReceive(writer.write(reqRoot));
// Answer processing
Json::Value ansRoot;
Json::Reader reader;
if (answer.empty() || !reader.parse(answer,ansRoot))
return;
if (!ansRoot["InvalidRequest"].isNull())
{
Log(LOG_ERROR,"1-wire GetDevices : get an InvalidRequest answer with reason \"%s\"\n", ansRoot.get("Reason","unknown reason").asString().c_str());
return;
}
for ( Json::ArrayIndex itDevice = 0; itDevice<ansRoot["Devices"].size(); itDevice++)
{
_t1WireDevice device;
device.family=(_e1WireFamilyType)ansRoot["Devices"][itDevice]["Family"].asUInt();
device.devid=ansRoot["Devices"][itDevice]["Id"].asString();
device.filename="";
if (!device.devid.empty())
devices.push_back(device);
}
}
Json::Value C1WireForWindows::readData(const _t1WireDevice& device,int unit) const
{
if (m_Socket==INVALID_SOCKET)
throw C1WireForWindowsReadException("invalid socket");
// Request
Json::Value reqRoot;
reqRoot["ReadData"]["Id"]=device.devid;
reqRoot["ReadData"]["Unit"]=unit;
Json::FastWriter writer;
// Send request and wait for answer
std::string answer = SendAndReceive(writer.write(reqRoot));
// Answer processing
Json::Value ansRoot;
Json::Reader reader;
if (answer.empty() || !reader.parse(answer,ansRoot))
throw C1WireForWindowsReadException("invalid answer");
if (!ansRoot["InvalidRequestReason"].isNull())
throw C1WireForWindowsReadException(std::string("1-wire readData : get an InvalidRequest answer with reason ").append(ansRoot.get("InvalidRequestReason","unknown").asString()));
return ansRoot;
}
unsigned int C1WireForWindows::readChanelsNb(const _t1WireDevice& device) const
{
if (m_Socket==INVALID_SOCKET)
throw C1WireForWindowsReadException("invalid socket");
// Request
Json::Value reqRoot;
reqRoot["ReadChanelsNb"]["Id"]=device.devid;
Json::FastWriter writer;
// Send request and wait for answer
std::string answer = SendAndReceive(writer.write(reqRoot));
// Answer processing
Json::Value ansRoot;
Json::Reader reader;
if (answer.empty() || !reader.parse(answer,ansRoot))
throw C1WireForWindowsReadException("invalid answer");
if (!ansRoot["InvalidRequestReason"].isNull())
throw C1WireForWindowsReadException(std::string("1-wire readData : get an InvalidRequest answer with reason ").append(ansRoot.get("InvalidRequestReason","unknown").asString()));
return ansRoot.get("ChanelsNb",0).asUInt();
}
float C1WireForWindows::GetTemperature(const _t1WireDevice& device) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device);
}
catch (C1WireForWindowsReadException&)
{
return -1000.0;
}
return ansRoot.get("Temperature",0.0f).asFloat();
}
float C1WireForWindows::GetHumidity(const _t1WireDevice& device) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device);
}
catch (C1WireForWindowsReadException&)
{
return -1000.0;
}
return ansRoot.get("Humidity",0.0f).asFloat();
}
float C1WireForWindows::GetPressure(const _t1WireDevice& device) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device);
}
catch (C1WireForWindowsReadException&)
{
return -1000.0;
}
return ansRoot.get("Pressure",0.0f).asFloat();
}
bool C1WireForWindows::GetLightState(const _t1WireDevice& device,int unit) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device,unit);
}
catch (C1WireForWindowsReadException&)
{
return false;
}
return !ansRoot.get("DigitalIo",false).asBool();
}
unsigned int C1WireForWindows::GetNbChannels(const _t1WireDevice& device) const
{
try
{
return readChanelsNb(device);
}
catch (C1WireForWindowsReadException&)
{
return 0;
}
}
unsigned long C1WireForWindows::GetCounter(const _t1WireDevice& device,int unit) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device,unit);
}
catch (C1WireForWindowsReadException&)
{
return 0;
}
return ansRoot.get("Counter",0).asUInt();
}
int C1WireForWindows::GetVoltage(const _t1WireDevice& device,int unit) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device,unit);
}
catch (C1WireForWindowsReadException&)
{
return -1000;
}
return ansRoot.get("Voltage",0).asInt();
}
float C1WireForWindows::GetIlluminance(const _t1WireDevice& device) const
{
Json::Value ansRoot;
try
{
ansRoot=readData(device);
}
catch (C1WireForWindowsReadException&)
{
return -1000.0;
}
return ansRoot.get("Illuminescence",0.0f).asFloat();
}
int C1WireForWindows::GetWiper(const _t1WireDevice& device) const
{
Json::Value ansRoot;
try
{
ansRoot = readData(device);
}
catch (C1WireForWindowsReadException&)
{
return -1;
}
return ansRoot.get("Wiper", -1).asUInt();
}
void C1WireForWindows::StartSimultaneousTemperatureRead()
{
}
void C1WireForWindows::PrepareDevices()
{
}
void C1WireForWindows::SetLightState(const std::string& sId,int unit,bool value, const unsigned int)
{
if (m_Socket==INVALID_SOCKET)
return;
// Request
Json::Value reqRoot;
reqRoot["WriteData"]["Id"]=sId;
reqRoot["WriteData"]["Unit"]=unit;
reqRoot["WriteData"]["Value"]=!value;
Json::FastWriter writer;
// Send request and wait for answer
SendAndReceive(writer.write(reqRoot));
// No answer processing
}
void C1WireForWindows::GetDevice(const std::string& deviceName, /*out*/_t1WireDevice& device) const
{
// 1W-Kernel device name format : ff-iiiiiiiiiiii, with :
// - ff : family (1 byte)
// - iiiiiiiiiiii : id (6 bytes)
// Retrieve family from the first 2 chars
device.family=ToFamily(deviceName.substr(0,2));
// Device Id (6 chars after '-')
device.devid=deviceName.substr(3,3+6*2);
// Filename (full path)
device.filename=deviceName;
}
#endif // WIN32